package com.fastbee.system.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONUtil;
import com.fastbee.common.annotation.DataScope;
import com.fastbee.common.constant.UserConstants;
import com.fastbee.common.core.domain.TreeSelect;
import com.fastbee.common.core.domain.entity.SysDept;
import com.fastbee.common.core.domain.entity.SysRole;
import com.fastbee.common.core.domain.entity.SysUser;
import com.fastbee.common.core.domain.model.LoginUser;
import com.fastbee.common.core.text.Convert;
import com.fastbee.common.exception.ServiceException;
import com.fastbee.common.holder.ProjectHolder;
import com.fastbee.common.utils.DateUtils;
import com.fastbee.common.utils.SecurityUtils;
import com.fastbee.common.utils.StringUtils;
import com.fastbee.common.utils.spring.SpringUtils;
import com.fastbee.system.mapper.SysDeptMapper;
import com.fastbee.system.mapper.SysRoleDeptMapper;
import com.fastbee.system.mapper.SysRoleMapper;
import com.fastbee.system.service.ISysDeptService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

import static com.fastbee.common.utils.SecurityUtils.getLoginUser;

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

    @Autowired
    private SysRoleMapper roleMapper;

    @Resource
    private SysRoleDeptMapper sysRoleDeptMapper;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept)
    {
        LoginUser loginUser = getLoginUser();
        Long deptId = loginUser.getDeptId();
        List<SysDept> sysDeptList = new ArrayList<>();
        if (null != deptId) {
            dept.setDeptId(deptId);
            sysDeptList = deptMapper.listDeptAndChild(dept);
        }
        return sysDeptList;
    }

    /**
     * 查询部门树结构信息
     *
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    @Override
    public List<TreeSelect> selectDeptTreeList(SysDept dept)
    {
        List<SysDept> depts = SpringUtils.getAopProxy(this).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 选中部门列表
     */
    @Cacheable(value = "dept", key = "#root.methodName + '_' + #roleId", unless = "#result == null")
    @Override
    public List<Long> selectDeptListByRoleId(Long roleId)
    {
        SysRole role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Cacheable(value = "dept", key = "#root.methodName + '_' + #deptId", unless = "#result == null")
    @Override
    public SysDept selectDeptById(Long deptId)
    {
        return deptMapper.selectDeptById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Cacheable(value = "dept", key = "#root.methodName + '_' + #deptId")
    @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 String 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);
            List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
            if (StringUtils.isEmpty(depts))
            {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Caching(put = {
            @CachePut(value = "dept", key = "'selectDeptById' + '_' + #dept.deptId"),
            @CachePut(value = "dept", key = "'selectNormalChildrenDeptById' + '_' + #dept.deptId")
    })
    @Override
    public int insertDept(SysDept dept)
    {
        SysDept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("部门停用，不允许新增");
        }
        //设置祖级别列表
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        //设置项目id
        dept.setProjectId(Long.valueOf(ProjectHolder.getProjectInfo().getProjectId()));
        //处理机构所管理行政区划信息
        parseAdministrativeDivisionInfo(dept);
        dept.setCreateTime(DateUtils.getNowDate());
        return deptMapper.insertDept(dept);
    }

    /**
     * 解析项目行政区划信息
     * @param sysDept 部门
     */
    private void parseAdministrativeDivisionInfo(SysDept sysDept) {
        //项目行政区域处理
        //拆解项目行政区域代码信息
        if(org.apache.commons.lang3.StringUtils.isBlank(sysDept.getAdministrativeAreaCode())){
            throw new ServiceException("项目行政区域代码不能为空！");
        }
        //判断行政区域代码json格式
        if(isNotValidJsonArray(sysDept.getAdministrativeAreaCode())){
            throw new ServiceException("项目行政区域代码多选列表非json数组！");
        }
        //项目省代码列表
        List<String> provincialCodeList =new ArrayList<>();
        //项目市代码列表
        List<String> cityCodeList =new ArrayList<>();
        //项目县代码列表
        List<String> countyCodeList =new ArrayList<>();
        //项目镇代码列表
        List<String> townCodeList =new ArrayList<>();
        //项目村代码列表
        List<String> villageCodeList =new ArrayList<>();
        JSONArray administrativeAreaList = JSONUtil.parseArray(sysDept.getAdministrativeAreaCode());
        administrativeAreaList.forEach(item->{
            if(isNotValidJsonArray(item.toString())){
                throw new ServiceException("项目行政区域代码多选列表的元素非json数组！");
            }
            //单个行政区划代码列表
            JSONArray administrativeArea = JSONUtil.parseArray(item);
            //拆解出每个行政区划代码里面的镇或村
            //保存项目省代码列表
            provincialCodeList.add(administrativeArea.get(0).toString());
            //保存项目市代码列表
            cityCodeList.add(administrativeArea.get(1).toString());
            //保存项目县代码列表
            countyCodeList.add(administrativeArea.get(2).toString());
            //保存项目镇代码列表

            if(administrativeArea.size()>=4){
                //保存项目镇代码列表
                townCodeList.add(administrativeArea.get(3).toString());
            }
            if(administrativeArea.size()>=5){
                //保存项目村代码列表
                villageCodeList.add(administrativeArea.get(4).toString());
            }
        });

        //设置项目省、市、县、镇、村行政区划代码列表
        sysDept.setProvinceCode(JSONUtil.toJsonStr(provincialCodeList));
        sysDept.setCityCode(JSONUtil.toJsonStr(cityCodeList));
        sysDept.setCountyCode(JSONUtil.toJsonStr(countyCodeList));
        sysDept.setTownCode(JSONUtil.toJsonStr(townCodeList));
        sysDept.setVillageCode(JSONUtil.toJsonStr(villageCodeList));
    }

    /**
     * 验证json对象是否是数组
     */
    public  boolean isNotValidJsonArray(String jsonStr) {
        try {
            JSONUtil.parseArray(jsonStr);
        } catch (JSONException e) {
            return true;
        }
        return false;
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Caching(put = {
            @CachePut(value = "dept", key = "'selectDeptById' + '_' + #dept.deptId"),
            @CachePut(value = "dept", key = "'selectNormalChildrenDeptById' + '_' + #dept.deptId")
    })
    @Override
    public int updateDept(SysDept dept)
    {   //查询当前修改部门的父部门
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        //查询当前修改部门修改前的旧数据
        SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());
        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);
        }

        //处理机构所管理行政区划信息
        parseAdministrativeDivisionInfo(dept);
        //更新部门信息
        dept.setUpdateTime(DateUtils.getNowDate());
        int result = deptMapper.updateDept(dept);


        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        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.size() > 0)
        {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @CacheEvict(value = "dept", allEntries = true)
    @Override
    public int deleteDeptById(Long deptId)
    {
        return deptMapper.deleteDeptById(deptId);
    }

    @Caching(put = {
            @CachePut(value = "dept", key = "'selectDeptById' + '_' + #deptId"),
            @CachePut(value = "dept", key = "'selectNormalChildrenDeptById' + '_' + #deptId")
    })
    @Override
    public int updateDeptUserId(Long deptId, Long deptUserId) {
        return deptMapper.updateDeptUserId(deptId, deptUserId);
    }

    @Override
    public List<SysRole> getRole(Long deptId) {
        List<Long> roleIdList = sysRoleDeptMapper.selectByDeptId(deptId);
        if (CollectionUtils.isEmpty(roleIdList)) {
            return new ArrayList<>();
        }
        return roleMapper.selectRoleByIds(roleIdList, null, null);
    }

    /**
     * 查询机构的所有上级绑定租户
     * @param deptId
     * @return
     */
    @Override
    public List<Long> selectSeniorDeptUser(Long deptId){
       return deptMapper.selectSeniorDeptUser(deptId);
    }

    @Override
    public Long selectRoleIdByDeptId(Long deptId) {
        return deptMapper.selectRoleIdByDeptId(deptId);
    }

    /**
     * 递归列表
     */
    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;
    }
}
