package com.microservices.system.service.impl;

import com.microservices.common.core.constant.CacheConstants;
import com.microservices.common.core.constant.SecurityConstants;
import com.microservices.common.core.constant.UserConstants;
import com.microservices.common.core.enums.SystemRole;
import com.microservices.common.core.exception.ServiceException;
import com.microservices.common.core.text.Convert;
import com.microservices.common.core.utils.DateUtils;
import com.microservices.common.core.utils.StringUtils;
import com.microservices.common.datascope.annotation.DataScope;
import com.microservices.common.security.utils.SecurityUtils;
import com.microservices.system.api.RemoteZoneService;
import com.microservices.system.api.domain.SysDept;
import com.microservices.system.api.domain.SysRole;
import com.microservices.system.api.domain.SysUser;
import com.microservices.system.api.utils.FeignUtils;
import com.microservices.system.domain.vo.TreeSelect;
import com.microservices.system.mapper.SysDeptMapper;
import com.microservices.system.mapper.SysRoleMapper;
import com.microservices.system.service.ISysDeptRoleService;
import com.microservices.system.service.ISysDeptService;
import com.microservices.system.service.ISysUserDeptRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 部门管理 服务实现
 *
 * @author microservices
 */
@Service
public class SysDeptServiceImpl implements ISysDeptService {
    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private ISysDeptRoleService sysDeptRoleService;

    @Autowired
    private ISysUserDeptRoleService sysUserDeptRoleService;
    @Autowired
    private RemoteZoneService remoteZoneService;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept)
    {
        return deptMapper.selectDeptList(dept);
    }

    /**
     * 查询部门树结构信息
     * 
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<TreeSelect> selectDeptTreeList(SysDept dept) {
//todo：神奇的异常        List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
        List<SysDept> depts = selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }

    /**
     * 构建前端所需要树结构
     * 
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts)
    {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = depts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        for (SysDept dept : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     * 
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts)
    {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询部门树信息
     * 
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    @Override
    public List<Long> selectDeptListByRoleId(Long roleId)
    {
        SysRole role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 根据部门ID查询信息
     * 
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Long deptId)
    {
        return deptMapper.selectDeptById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     * 
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId)
    {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 是否存在子节点
     * 
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public boolean hasChildByDeptId(Long deptId)
    {
        int result = deptMapper.hasChildByDeptId(deptId);
        return result > 0;
    }

    /**
     * 查询部门是否存在用户
     * 
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId)
    {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0;
    }

    /**
     * 校验部门名称是否唯一
     * 
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean checkDeptNameUnique(SysDept dept)
    {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验部门是否有数据权限
     * 
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(Long deptId)
    {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
// todo:神奇的异常
//            List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
            List<SysDept> depts = selectDeptList(dept);
            if (StringUtils.isEmpty(depts)) {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    @Override
    public void checkDeptName(String name) {
        if (StringUtils.isEmpty(name)) {
            return;
        }
        if (name.length() < 1 || name.length() > 30) {
            throw new ServiceException("组织名称长度应该为1-30(组织名称[" + name + "])");
        }
        String NAME_REGEX = "^[a-zA-Z0-9_\u4e00-\u9fa5\\-\\.]+$";
        boolean isValidName = Pattern.matches(NAME_REGEX, name);
        if (!isValidName) {
            throw new ServiceException("组织名称不符合规范，当前仅支持：中文、英文、数字、下划线、中划线和英文句号(组织名称[" + name + "])");
        }
    }

    @Override
    public List<String> getGitLinkUserNamesByDeptIdAndRoleKeys(Long deptId, String roleKeys) {
        return deptMapper.getGitLinkUserNamesByDeptIdAndRoleKeys(deptId, roleKeys);
    }

    @Override
    public Long addDeptByZone(String zoneName) {
        SysDept parentDept = deptMapper.selectParentDeptByType(CacheConstants.DEPT_TYPE_TSZQ);
        // 如果父节点不为正常状态,则不允许新增子节点
        if (parentDept == null || !UserConstants.DEPT_NORMAL.equals(parentDept.getStatus())) {
            throw new ServiceException("当前部门停用，不允许新增");
        }
        SysDept dept = deptMapper.selectDeptByNameAndParentId(zoneName, parentDept.getDeptId());
        if (dept != null) {
            throw new ServiceException("已存在相同名称部门(部门名称[%s])", zoneName);
        }
        dept = insertSysDept(parentDept, zoneName);
        // 设置该组织下可选角色为：专区管理员、专区运营人员、专区会员
        addDefaultRoleForDept(dept);
        return dept.getDeptId();
    }

    private SysDept insertSysDept(SysDept parentDept, String deptName) {
        SysDept dept = new SysDept();
        dept.setDeptName(deptName);
        dept.setParentId(parentDept.getDeptId());
        dept.setAncestors(parentDept.getAncestors() + "," + dept.getParentId());
        dept.setCreateBy(SecurityUtils.getUsername());
        dept.setOrderNum(1);
        dept.setDeptType(parentDept.getDeptType());
        deptMapper.insertDept(dept);
        return dept;
    }

    @Override
    public Long addDeptByPmsEnterprise(String pmsEnterpriseName) {

        SysDept parentDept = deptMapper.selectParentDeptByType(CacheConstants.DEPT_TYPE_PMS);
        if (parentDept == null) {
            SysDept firstDept = deptMapper.selectFirstDept();
            parentDept = insertSysDept(firstDept, "项目管理部");
            SysRole platformAdminRole = roleMapper.selectRoleByKey(SystemRole.PLATFORM_ADMIN.getRoleKey());
            Long[] roleIds = new Long[]{platformAdminRole.getRoleId()};
            sysDeptRoleService.addSysRoleListForSysDept(parentDept.getDeptId(), roleIds);
        }
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(parentDept.getStatus())) {
            throw new ServiceException("当前部门停用，不允许新增");
        }

        SysDept dept = deptMapper.selectDeptByNameAndParentId(pmsEnterpriseName, parentDept.getDeptId());
        if (dept != null) {
            throw new ServiceException("已存在相同名称部门(部门名称[%s])", pmsEnterpriseName);
        }
        dept = insertSysDept(parentDept, pmsEnterpriseName);
        // 设置该组织下可选角色为：组织管理员、项目经理、产品经理、普通成员
        SysRole pmsOrgAdmin = roleMapper.selectRoleByKey(SystemRole.PMS_ORG_ADMIN.getRoleKey());
        SysRole pmsProjectManager = roleMapper.selectRoleByKey(SystemRole.PMS_PROJECT_MANAGER.getRoleKey());
        SysRole pmsProductManager = roleMapper.selectRoleByKey(SystemRole.PMS_PRODUCT_MANAGER.getRoleKey());
        SysRole pmsUser = roleMapper.selectRoleByKey(SystemRole.PMS_USER.getRoleKey());
        SysRole pmsTestUser = roleMapper.selectRoleByKey(SystemRole.PMS_TEST_USER.getRoleKey());
        SysRole pmsCustomer = roleMapper.selectRoleByKey(SystemRole.PMS_CUSTOMER.getRoleKey());
        Long[] roleIds = new Long[]{
                pmsOrgAdmin.getRoleId()
                , pmsProjectManager.getRoleId()
                , pmsProductManager.getRoleId()
                , pmsUser.getRoleId()
                , pmsTestUser.getRoleId()
                , pmsCustomer.getRoleId()};
        sysDeptRoleService.addSysRoleListForSysDept(dept.getDeptId(), roleIds);
        return dept.getDeptId();
    }

    @Override
    public Boolean updateDeptNameByDeptId(Long deptId, String deptName) {
        SysDept sysDept = selectDeptById(deptId);
        if (sysDept == null) {
            throw new ServiceException("该部门不存在(部门id[%d])", deptId);
        }
        sysDept.setDeptName(deptName);
        sysDept.setUpdateBy(SecurityUtils.getUsername());
        sysDept.setUpdateTime(DateUtils.getNowDate());
        return deptMapper.updateDept(sysDept) > 0;
    }

    @Override
    public Boolean deleteDeptByPmsEnterprise(String pmsEnterpriseName) {
        // 查找项目管理父级部门，若不存在则返回true
        SysDept parentDept = deptMapper.selectParentDeptByType(CacheConstants.DEPT_TYPE_PMS);
        if (parentDept == null) {
            return true;
        }
        // 根据父级部门id和名称查找部门，若不存在则返回true
        SysDept dept = deptMapper.selectDeptByNameAndParentId(pmsEnterpriseName, parentDept.getDeptId());
        return deleteDept(dept);
    }

    @Override
    public Boolean deleteDeptByDeptId(Long deptId) {
        // 根据id查找部门，若不存在则返回true
        SysDept dept = selectDeptById(deptId);
        return deleteDept(dept);
    }

    private Boolean deleteDept(SysDept dept) {
        if (dept == null) {
            return true;
        }
        // 删除部门下所有身份
        sysUserDeptRoleService.deleteSysUserDeptRoleByDeptId(dept.getDeptId());
        // 删除部门下所有可选角色
        // TODO-pms:设置企业下角色，当前测试用统一设置为平台管理员
        SysRole platformAdminRole = roleMapper.selectRoleByKey(SystemRole.PLATFORM_ADMIN.getRoleKey());
        Long[] roleIds = new Long[]{platformAdminRole.getRoleId()};
        sysDeptRoleService.deleteSysRoleListForSysDept(dept.getDeptId(), roleIds);
        // 删除部门
        deptMapper.deleteDeptById(dept.getDeptId());
        return true;
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public boolean insertDept(SysDept dept) {
        checkDeptName(dept.getDeptName());
        //是否为第三级组织
        boolean isTertiaryDept = false;
        SysDept parentDept = deptMapper.selectDeptById(dept.getParentId());
        //增加业务定制逻辑，只允许用户在二级组织下新增组织
        List<Long> secondaryDeptIds = deptMapper.selectSecondaryDeptIds();
        if (!secondaryDeptIds.contains(dept.getParentId())) {
            if (!SecurityUtils.isAdmin()) {
                throw new ServiceException("用户仅允许添加第三级组织，请联系超级管理员(上级组织Id[" + dept.getParentId() + "])");
            }
        } else {
            if (parentDept == null || parentDept.getDeptType() == null) {
                throw new ServiceException("新增第三级组织时，必须先设置上级组织的组织类型");
            }
            //当新增组织为第三级组织时，设置组织类型属性为上级组织一致
            dept.setDeptType(parentDept.getDeptType());
            isTertiaryDept = true;
        }

        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(parentDept.getStatus())) {
            throw new ServiceException("部门停用，不允许新增");
        }
        dept.setAncestors(parentDept.getAncestors() + "," + dept.getParentId());
        dept.setCreateBy(SecurityUtils.getUsername());
        boolean result = deptMapper.insertDept(dept) > 0;
        if (result && isTertiaryDept) {
            automatedBusinessLogicProcessing(dept, true);
        }
        return result;
    }

    /**
     * 自动处理组织对应的业务逻辑
     *
     * @param dept
     */
    private void automatedBusinessLogicProcessing(SysDept dept, boolean isAdd) {
        boolean result = false;
        String errorMessage = null;
        if (dept.getDeptType() == null) {
            errorMessage = "请先设置上级组织的组织类型(上级组织Id[" + dept.getParentId() + "])";
        } else {
            switch (dept.getDeptType()) {
                case CacheConstants.DEPT_TYPE_TSZQ:
                    if (isAdd) {
                        // 设置该组织下可选角色为：专区管理员、专区运营人员、专区会员
                        addDefaultRoleForDept(dept);
                        errorMessage = createProjectByDept(dept);
                    } else {
                        errorMessage = updateProjectByDept(dept);
                    }

                    result = !StringUtils.isNotEmpty(errorMessage);
                    break;
                default:
                    errorMessage = "该组织类型当前不存在对应的业务方自动处理逻辑(组织类型[" + dept.getDeptType() + "])";
            }
        }

        if (!result) {
            if (isAdd) {
                deleteDeptById(dept.getDeptId());
            }
            throw new ServiceException(errorMessage);
        }

    }

    private void addDefaultRoleForDept(SysDept dept) {
        SysRole zoneAdminRole = roleMapper.selectRoleByKey(SystemRole.ZONE_ADMIN.getRoleKey());
        SysRole zoneOperatorRole = roleMapper.selectRoleByKey(SystemRole.ZONE_OPERATOR.getRoleKey());
        SysRole zoneMemberRole = roleMapper.selectRoleByKey(SystemRole.ZONE_MEMBER.getRoleKey());
        Long[] roleIds = new Long[]{zoneAdminRole.getRoleId(), zoneOperatorRole.getRoleId(), zoneMemberRole.getRoleId()};
        sysDeptRoleService.addSysRoleListForSysDept(dept.getDeptId(), roleIds);
    }

    /**
     * 创建组织对应特色专区项目
     *
     * @param dept
     * @return
     */
    private String createProjectByDept(SysDept dept) {
        String errorMessage = null;
        try {
            Long zoneId = FeignUtils.getReturnData(
                    remoteZoneService.autoAddZoneByDept(dept.getDeptId(), SecurityConstants.INNER));
            if (zoneId == null) {
                errorMessage = "创建特色专区组织对应项目失败(组织名称[" + dept.getDeptName() + "])";
            }
        } catch (Exception e) {
            errorMessage = "创建特色专区组织对应项目失败(组织名称[" + dept.getDeptName() + "])，" +
                    "失败原因：" + e.getMessage();
        }
        return errorMessage;
    }

    /**
     * 更新组织对应特色专区项目
     *
     * @param dept
     * @return
     */
    private String updateProjectByDept(SysDept dept) {
        String errorMessage = null;
        try {
            boolean result = Boolean.TRUE.equals(FeignUtils.getReturnData(
                    remoteZoneService.autoUpdateZoneByDept(dept, SecurityConstants.INNER)));
            if (!result) {
                errorMessage = "更新特色专区组织对应项目失败(组织名称[" + dept.getDeptName() + "])";
            }
        } catch (Exception e) {
            errorMessage = "更新特色专区组织对应项目失败(组织名称[" + dept.getDeptName() + "])，" +
                    "失败原因：" + e.getMessage();
        }
        return errorMessage;
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDept(SysDept dept) {
        //是否为第三级组织
        boolean isTertiaryDept = false;
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());
        List<Long> secondaryDeptIds = deptMapper.selectSecondaryDeptIds();
        if (secondaryDeptIds.contains(dept.getParentId())) {
            if (!dept.getParentId().equals(oldDept.getParentId())) {
                throw new ServiceException("第三级组织不允许修改上级组织");
            }
            if (newParentDept == null || newParentDept.getDeptType() == null) {
                throw new ServiceException("修改第三级组织时，必须先设置上级组织的组织类型");
            }
            isTertiaryDept = true;
            //当新增组织为第三级组织时，设置组织类型属性为上级组织一致
            dept.setDeptType(newParentDept.getDeptType());
        }
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        boolean result = deptMapper.updateDept(dept) > 0;
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        if (result && isTertiaryDept) {
            automatedBusinessLogicProcessing(dept, false);
        }
        // 清理用户身份缓存
        sysUserDeptRoleService.updateUserLoginInfoByDeptId(dept.getDeptId());
        return result;
    }

    /**
     * 修改该部门的上级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept)
    {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        deptMapper.updateDeptStatusNormal(deptIds);
    }

    /**
     * 修改子元素关系
     * 
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (!children.isEmpty())
        {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId) {
        SysDept dept = selectDeptById(deptId);
        // 删除组织下用户
        sysUserDeptRoleService.deleteSysUserDeptRoleByDeptId(deptId);
        if (CacheConstants.DEPT_TYPE_TSZQ == dept.getDeptType()) {
            // 删除专区相关数据
            remoteZoneService.deleteByDeptName(dept.getDeptName(), SecurityConstants.INNER);
            // 删除组织下用户
            sysUserDeptRoleService.deleteSysUserDeptRoleByDeptId(dept.getDeptId());

            // 删除组织前先删除组织下角色
            SysRole zoneAdminRole = roleMapper.selectRoleByKey(SystemRole.ZONE_ADMIN.getRoleKey());
            SysRole zoneOperatorRole = roleMapper.selectRoleByKey(SystemRole.ZONE_OPERATOR.getRoleKey());
            SysRole zoneMemberRole = roleMapper.selectRoleByKey(SystemRole.ZONE_MEMBER.getRoleKey());
            Long[] roleIds = new Long[]{zoneAdminRole.getRoleId(), zoneOperatorRole.getRoleId(), zoneMemberRole.getRoleId()};
            sysDeptRoleService.deleteSysRoleListForSysDept(dept.getDeptId(), roleIds);
        }
        return deptMapper.deleteDeptById(deptId);
    }

    @Override
    public List<SysDept> selectDeptListInIds(List<Long> ids) {
        List<SysDept> deptList = deptMapper.selectDeptListInIds(ids);
        return deptList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t)
    {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext())
        {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }


    public List<Long> getSelfAndChildrenDeptIdListByDeptId(Long deptId) {
        List<Long> deptIdList = new ArrayList<>();
        deptIdList.add(deptId);
        List<SysDept> childList = deptMapper.selectChildrenDeptById(deptId);
        deptIdList.addAll(childList.stream().map(x -> x.getDeptId()).collect(Collectors.toList()));
        return deptIdList;
    }

    @Override
    public void checkUnchangeableDept(Long deptId) {
        //增加业务定制逻辑，二级及以上组织不允许非ADMIN修改
        List<Long> immutableDeptIds = deptMapper.selectImmutableDeptIds();
        if (immutableDeptIds.contains(deptId)) {
            if (!SecurityUtils.isAdmin()) {
                throw new ServiceException("二级及以上组织不允许用户操作，请联系超级管理员(组织Id[" + deptId + "])");
            }
        }
    }

}
