package com.zksy.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.common.annotation.DataScope;
import com.zksy.common.constant.UserConstants;
import com.zksy.common.core.domain.TreeSelect;
import com.zksy.common.core.domain.entity.SysDept;
import com.zksy.common.core.domain.entity.SysRole;
import com.zksy.common.core.domain.entity.SysUser;
import com.zksy.common.core.text.Convert;
import com.zksy.common.exception.ServiceException;
import com.zksy.common.utils.SecurityUtils;
import com.zksy.common.utils.StringUtils;
import com.zksy.common.utils.result.Response;
import com.zksy.common.utils.spring.SpringUtils;
import com.zksy.system.mapper.SysDeptMapper;
import com.zksy.system.mapper.SysRoleMapper;
import com.zksy.system.mapper.SysUserMapper;
import com.zksy.system.mapper.SysUserRoleMapper;
import com.zksy.system.model.request.AddSysDeptReq;
import com.zksy.system.model.request.NextDeptExportReq;
import com.zksy.system.model.request.NextDeptReq;
import com.zksy.system.model.request.RevokeOrDelLabourReq;
import com.zksy.system.model.respone.DataDeptRecord;
import com.zksy.system.model.respone.FindNextDeptPagerVo;
import com.zksy.system.model.respone.FindNextDeptRes;
import com.zksy.system.model.respone.NextDeptExport;
import com.zksy.system.service.ISysDeptService;
import com.zksy.system.service.ISysDictDataService;
import com.zksy.system.service.ISysUserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

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

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private ISysDictDataService dictDataService;

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

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = new ArrayList<Long>();
        for (SysDept dept : depts) {
            tempList.add(dept.getDeptId());
        }
        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 this.baseMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

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

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

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

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        int result = this.baseMapper.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 = this.baseMapper.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 结果
     */
    @Override
    public int insertDept(SysDept dept) {
        SysDept info = this.baseMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new ServiceException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return this.baseMapper.insertDept(dept);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(SysDept dept) {
        SysDept newParentDept = this.baseMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = this.baseMapper.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);
        }
        int result = this.baseMapper.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);
        this.baseMapper.updateDeptStatusNormal(deptIds);
    }

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

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId) {
        return this.baseMapper.deleteDeptById(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;
    }


    /**
     * 新增 编辑部门
     *
     * @param req
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response addSysDept(AddSysDeptReq req) {
        SysDept sysDept;
        if (req.getDeptId() == null) {
            sysDept = new SysDept();
            BeanUtils.copyProperties(req, sysDept);
            sysDept.setCreateBy(SecurityUtils.getUsername());
            sysDept.setCreateTime(new Date());
            int i = this.baseMapper.insert(sysDept);

            //如果部门添加成功则 添加一个系统用户
            if (i > 0) {
                SysUser sysUser = new SysUser();
                BaseMapper<SysUser> baseMapper = userService.getBaseMapper();
                QueryWrapper<SysUser> wrapper = new QueryWrapper();
                wrapper.eq("user_name", sysDept.getDeptName());
                baseMapper.delete(wrapper);
                sysUser.setUserName(sysDept.getDeptName());
                sysUser.setNickName(sysDept.getDeptName());
                //默认密码
                String pwd = "tjxzgh@123456&";
                sysUser.setPassword(SecurityUtils.encryptPassword(pwd));
                sysUser.setCreateTime(new Date());
                sysUser.setCreateBy(SecurityUtils.getUsername());
                sysUser.setUserType("0");//默认系统用户
                sysUser.setStatus("0");//状态正常
                sysUser.setDeptId(sysDept.getDeptId());
                userService.save(sysUser);

                // 基层部门管理员
                QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
                sysRoleQueryWrapper.eq("role_name", "基层部门管理员");
                SysRole sysRole = roleMapper.selectOne(sysRoleQueryWrapper);

                //分配基层管理员的角色
                userRoleMapper.inserUserRole(sysUser.getUserId(), sysRole.getRoleId());

            }
        } else {
            sysDept = this.baseMapper.selectById(req.getDeptId());
            BeanUtils.copyProperties(req, sysDept);
            sysDept.setUpdateBy(SecurityUtils.getUsername());
            //sysDept.setApproveStatus("0");//默认待审核
            sysDept.setUpdateTime(new Date());
            this.baseMapper.updateById(sysDept);
        }
        return Response.success();
    }

    /**
     * 查看下级部门
     *
     * @param req 当前部门id
     * @return
     */
    @Override
    public Response<FindNextDeptPagerVo> findNextDept(NextDeptReq req) {
        Page<FindNextDeptRes> page = PageHelper.startPage(req.getPageNumber(), req.getPageSize());
        //查看下级部门
        List<FindNextDeptRes> res = this.baseMapper.selectFindNextDept(req);
        FindNextDeptPagerVo vo = new FindNextDeptPagerVo();
        vo.setCurrPage(req.getPageNumber());
        vo.setPageSize(req.getPageSize());
        vo.setTotalRecord(Long.valueOf(page.getTotal()).intValue());
        vo.setNextDeptRes(res);
        return Response.success(vo);
    }

    /**
     * 查看部门资料
     *
     * @param deptId
     * @return
     */
    @Override
    public Response<DataDeptRecord> findDataDept(String deptId) {
        //查看部门资料
        DataDeptRecord record = this.baseMapper.findDataDept(deptId);

        return Response.success(record);
    }

    /**
     * 传入部门ID查询本级和子极
     *
     * @param deptId
     * @return
     */
    public Response<List<SysDept>> selectLevelAndChild(Long deptId) {
        List<SysDept> sysDepts = this.baseMapper.selectLevelAndChild(deptId);
        List<SysDept> tree = buildDeptTree(sysDepts);
        return Response.success(tree);
    }


    /**
     * 下级单位导出
     *
     * @param req
     * @return
     */
    @Override
    public List<NextDeptExport> exportDept(NextDeptExportReq req) {
        List<NextDeptExport> deptRes = this.baseMapper.exportDept(req);
        return deptRes;
    }

    /**
     * 变更部门信息 查上级 及同级部门
     *
     * @param deptId
     * @return
     */
    @Override
    public Response<List<SysDept>> findUpDept(Long deptId) {
        QueryWrapper<SysDept> deptQueryWrapper = new QueryWrapper<>();
        deptQueryWrapper.eq("del_flag", "0");
        List<SysDept> all = this.baseMapper.selectList(deptQueryWrapper);
        //本级的子级
        List<SysDept> depts = this.baseMapper.selectLevelAndChild(deptId);


        all.removeAll(depts);
        return Response.success(all);
    }
}
