package cn.palmte.work.service;


import cn.palmte.work.model.*;
import cn.palmte.work.utils.InterfaceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.jfunc.common.db.bean.Page;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class SysPermissionService {

    @Autowired
    private SysPermissionRepositoryCustom sysPermissionRepositoryCustom;
    @Autowired
    private SysPermissionRepository sysPermissionRepository;
    @Autowired
    private SysRolePermissionRepository sysRolePermissionRepository;

    @Autowired
    private SysRoleRepository sysRoleRepository;
    private static final Logger logger = LoggerFactory.getLogger(SysPermissionService.class);

    /**
     * 分页获取所有资源列表
     */
    public Page<SysPermission> getAllPermissionListByPage(ConcurrentHashMap<String, String> searchInfo, String pageNumber) {
        return sysPermissionRepositoryCustom.getAllPermissionListByPage(searchInfo, pageNumber);

    }

    public List<String> getAllPermissionList() {
        return sysPermissionRepository.findAllPermissionUrls();
    }

    /**
     * 批量删除资源
     */
    public boolean deletePermissionByIDs(String[] ids) {
        boolean deleted = true;
        for (String id : ids) {
            SysPermission permission = sysPermissionRepository.findOne(Integer.parseInt(id));

            permission.setIsDeleted(1);
            permission.setLastUpdatedBy(InterfaceUtil.getAdminId());// 当前登录人
            permission.setLastUpdatedTime(new Date());
            try {
                sysPermissionRepository.save(permission);
            } catch (Exception e) {
                e.printStackTrace();
                deleted = false;
                break;
            }
        }

        return deleted;
    }


    /**
     * 添加资源
     */
    @Transactional(rollbackFor = Exception.class)
    public void addPermission(SysPermission sysPermission) {

        sysPermission.setCreatedBy(InterfaceUtil.getAdminId()); // 当前登录人
        sysPermission.setCreatedTime(new Date());
        sysPermission.setLastUpdatedBy(InterfaceUtil.getAdminId());
        sysPermission.setLastUpdatedTime(new Date());
        sysPermission = sysPermissionRepository.saveAndFlush(sysPermission);

        int permissionID = sysPermission.getId();

        // 新增权限时，默认在角色-权限表中新增一组关系。默认给系统管理员授权。(注意：角色表中必须只要一个系统管理员角色。)即使用其它角色新增一个资源时，也是默认赋给系统管理员角色授权。
        int superAdminRoleId = 1;
        try {
            SysRole sysRole = sysRoleRepository.findSuperAdminRole();
            superAdminRoleId = sysRole.getId();
        } catch (Exception e) {
            e.printStackTrace();
        }
        SysRolePermission rolePermission = new SysRolePermission();
        rolePermission.setRoleId(superAdminRoleId);// 即最高权限-系统管理员角色id。
        rolePermission.setPermissionId(permissionID);
        rolePermission.setCreatedBy(InterfaceUtil.getAdminId()); // 当前登录人
        rolePermission.setCreatedTime(new Date());
        rolePermission.setLastUpdatedBy(InterfaceUtil.getAdminId());
        rolePermission.setLastUpdatedTime(new Date());
        sysRolePermissionRepository.save(rolePermission);


    }


    /**
     * 更新权限
     */
    public void updatePermission(SysPermission sysPermission, String permissionID) {

        SysPermission permission = sysPermissionRepository.findOne(Integer.parseInt(permissionID));

        permission.setName(sysPermission.getName());
        permission.setIcon(sysPermission.getIcon());
        permission.setUrl(sysPermission.getUrl());
        permission.setLevel(sysPermission.getLevel());
        permission.setType(sysPermission.getType());
        permission.setSort(sysPermission.getSort());
        permission.setRemark(sysPermission.getRemark());
        permission.setParentId(sysPermission.getParentId());
        permission.setPermission(sysPermission.getPermission());
        permission.setLastUpdatedBy(InterfaceUtil.getAdminId());
        permission.setLastUpdatedTime(new Date());
        sysPermissionRepository.saveAndFlush(permission);

    }


    public String check(SysPermission sysPermission, String permissionID) {
        SysPermission byUrlEquals = sysPermissionRepository.findByUrlEquals(sysPermission.getUrl());
        String message = "";
        if ("-1".equals(permissionID)) {
            if (null != byUrlEquals) {
                message = "该URL已存在！";
                return message;
            }
        } else {
            if (null != byUrlEquals && byUrlEquals.getId() != Integer.parseInt(permissionID)) {
                message = "该URL已存在！";
                return message;
            }
        }

        SysPermission byPermissionEquals = sysPermissionRepository.findByPermissionEquals(sysPermission.getPermission());

        if ("-1".equals(permissionID)) {
            if (null != byPermissionEquals) {
                message = "该权限编码已存在！";
                return message;
            }
        } else {
            if (null != byPermissionEquals && byPermissionEquals.getId() != Integer.parseInt(permissionID)) {
                message = "该权限编码已存在！";
                return message;
            }
        }

        return message;
    }
}
