package com.fs.company.service.impl;

import com.fs.common.constant.UserConstants;
import com.fs.common.core.domain.entity.SysDept;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.DateUtils;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.CompanyDept;
import com.fs.company.domain.CompanyDeptTreeSelect;
import com.fs.company.domain.CompanyRole;
import com.fs.company.mapper.CompanyDeptMapper;
import com.fs.company.mapper.CompanyRoleMapper;
import com.fs.company.service.ICompanyDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * 部门Service业务层处理
 * 
 * @author fs
 * @date 2021-05-25
 */
@Service
public class CompanyDeptServiceImpl implements ICompanyDeptService
{
    @Autowired
    private CompanyDeptMapper companyDeptMapper;

    @Autowired
    private CompanyRoleMapper roleMapper;
    /**
     * 查询部门
     * 
     * @param deptId 部门ID
     * @return 部门
     */
    @Override
    public CompanyDept selectCompanyDeptById(Long deptId)
    {
        return companyDeptMapper.selectCompanyDeptById(deptId);
    }

    /**
     * 查询部门列表
     * 
     * @param companyDept 部门
     * @return 部门
     */
    @Override
    public List<CompanyDept> selectCompanyDeptList(CompanyDept companyDept)
    {
        return companyDeptMapper.selectCompanyDeptList(companyDept);
    }

    /**
     * 新增部门
     * 
     * @param companyDept 部门
     * @return 结果
     */
    @Override
    public int insertCompanyDept(CompanyDept companyDept)
    {
        CompanyDept info = companyDeptMapper.selectCompanyDeptById(companyDept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new CustomException("部门停用，不允许新增");
        }
        companyDept.setAncestors(info.getAncestors() + "," + companyDept.getParentId());
        return companyDeptMapper.insertCompanyDept(companyDept);
    }

    /**
     * 修改部门
     * 
     * @param companyDept 部门
     * @return 结果
     */
    @Override
    public int updateCompanyDept(CompanyDept companyDept)
    {
        CompanyDept newParentDept = companyDeptMapper.selectCompanyDeptById(companyDept.getParentId());
        CompanyDept oldDept = companyDeptMapper.selectCompanyDeptById(companyDept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            companyDept.setAncestors(newAncestors);
            updateDeptChildren(companyDept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = companyDeptMapper.updateCompanyDept(companyDept);
        if (UserConstants.DEPT_NORMAL.equals(companyDept.getStatus()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(companyDept);
        }
        return result;
    }


    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(CompanyDept dept)
    {
        String updateBy = dept.getUpdateBy();
        dept = companyDeptMapper.selectCompanyDeptById(dept.getDeptId());
        dept.setUpdateBy(updateBy);
        companyDeptMapper.updateDeptStatus(dept);
    }

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

    /**
     * 批量删除部门
     * 
     * @param deptIds 需要删除的部门ID
     * @return 结果
     */
    @Override
    public int deleteCompanyDeptByIds(Long[] deptIds)
    {
        return companyDeptMapper.deleteCompanyDeptByIds(deptIds);
    }

    /**
     * 删除部门信息
     * 
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteCompanyDeptById(Long deptId)
    {
        return companyDeptMapper.deleteCompanyDeptById(deptId);
    }

    @Override
    public List<CompanyDeptTreeSelect> buildDeptTreeSelect(List<CompanyDept> depts) {
        List<CompanyDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(CompanyDeptTreeSelect::new).collect(Collectors.toList());
    }
    @Override
    public List<CompanyDept> buildDeptTree(List<CompanyDept> depts) {
        List<CompanyDept> returnList = new ArrayList<CompanyDept>();
        List<Long> tempList = new ArrayList<Long>();
        for (CompanyDept dept : depts)
        {
            tempList.add(dept.getDeptId());
        }
        for (Iterator<CompanyDept> iterator = depts.iterator(); iterator.hasNext();)
        {
            CompanyDept dept = (CompanyDept) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    @Override
    public List<Integer> selectDeptListByRoleId(Long roleId) {
        CompanyRole role = roleMapper.selectCompanyRoleById(roleId);
        return companyDeptMapper.selectDeptListByRoleId(roleId, role.getDeptCheckStrictly());
    }

    @Override
    public int checkDeptNameUnique(CompanyDept dept) {
        return companyDeptMapper.checkDeptNameUnique(dept.getCompanyId(),dept.getDeptName());
    }

    @Override
    public int checkDeptExistUser(Long deptId) {
        int result = companyDeptMapper.checkDeptExistUser(deptId);
        return result;
    }

    @Override
    public int hasChildByDeptId(Long deptId) {
        int result = companyDeptMapper.hasChildByDeptId(deptId);
        return result;
    }

    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        return companyDeptMapper.selectNormalChildrenDeptById(deptId);
    }

    @Override
    public List<String> selectCompanyDeptNamesByIds(String ids) {
        return companyDeptMapper.selectCompanyDeptNamesByIds(ids);
    }

    /**
     * 获取公司默认部门
     * @param companyId 公司ID
     * @return 部门
     */
    @Override
    public CompanyDept getDefaultCompanyDeptByCompanyId(Long companyId) {
        return companyDeptMapper.getTopCompanyDeptByCompanyId(companyId);
    }

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

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

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