package com.mortals.xhx.module.dept.service.impl;

import com.mortals.xhx.module.staff.model.StaffEntity;
import com.mortals.xhx.module.staff.model.StaffQuery;
import com.mortals.xhx.module.staff.service.StaffService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.common.code.DeptStatusEnum;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.xhx.module.dept.dao.DeptDao;
import com.mortals.xhx.module.dept.model.DeptEntity;
import com.mortals.xhx.module.dept.model.DeptQuery;
import com.mortals.xhx.module.dept.service.DeptService;
import com.mortals.xhx.module.dept.model.DeptTreeSelect;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * DeptService
 * 部门信息 service实现
 *
 * @author zxfei
 * @date 2023-03-06
 */
@Service("deptService")
public class DeptServiceImpl extends AbstractCRUDServiceImpl<DeptDao, DeptEntity, Long> implements DeptService {

    @Autowired
    private StaffService staffService;

    @Override
    protected void saveBefore(DeptEntity entity, Context context) throws AppException {
        if(ObjectUtils.isEmpty(entity.getParentId())){
            //如果父节点为空，默认挂载到根目录
            entity.setParentId(0L);
        }

        DeptEntity parentDeptEntity = this.get(entity.getParentId());
        if (!ObjectUtils.isEmpty(parentDeptEntity) && DeptStatusEnum.停用.getValue() == parentDeptEntity.getDeptStatus()) {
            throw new AppException("部门信息停用，不允许新增");
        }

        if (!ObjectUtils.isEmpty(parentDeptEntity)) {
            entity.setAncestors(parentDeptEntity.getAncestors() + "," + entity.getParentId());
        }

        super.saveBefore(entity, context);
    }

    @Override
    protected void updateBefore(DeptEntity entity, Context context) throws AppException {
        DeptEntity newParentEntity = this.get(entity.getParentId());
        DeptEntity oldEntity = this.get(entity.getId());
        if (!ObjectUtils.isEmpty(newParentEntity) && !ObjectUtils.isEmpty(oldEntity)) {
            String newAncestors = newParentEntity.getAncestors() + "," +entity.getId();
            String oldAncestors = oldEntity.getAncestors();
            entity.setAncestors(newAncestors);
            updateDeptChildren(entity.getId(), newAncestors, oldAncestors, context);
        }
        super.updateBefore(entity, context);
    }


    @Override
    protected void updateAfter(DeptEntity entity, Context context) throws AppException {
        if (DeptStatusEnum.启用.getValue() == entity.getDeptStatus()) {
            updateParentDeptStatus(entity, context);
        }
        super.updateAfter(entity, context);
    }

    /**
     * 修改该部门信息的父级部门信息状态
     *
     * @param dept 当前部门信息
     */
    private void updateParentDeptStatus(DeptEntity dept, Context context) {
        DeptEntity deptEntity = this.get(dept.getParentId());
        if(!ObjectUtils.isEmpty(deptEntity)){
            deptEntity.setDeptStatus(DeptStatusEnum.启用.getValue());
            deptEntity.setUpdateTime(new Date());
            deptEntity.setUpdateUser(context==null?"admin":context.getUser().getLoginName());
            DeptEntity condition = new DeptEntity();
            condition.setId(deptEntity.getId());
            this.updateBatch(deptEntity, condition, context);
        }
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门信息ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors, Context context) {

        List<DeptEntity> children = getDao().selectChildrenDeptById(deptId.toString());
        for (DeptEntity child : children) {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            this.updateAfter(children, context);
        }
    }


    @Override
    protected void removeBefore(Long[] ids, Context context) throws AppException {
        //有子节点 禁止删除
        if (hasChildByDeptId(ids[0])) {
            throw new AppException("存在下级部门信息,不允许删除");
        }
        super.removeBefore(ids, context);
    }

    @Override
    public boolean hasChildByDeptId(Long deptId) {
        List<DeptEntity> list = this.find(new DeptQuery().parentId(deptId));

        return list.size() > 0 ? true : false;
    }

    @Override
    public List<DeptEntity> selectDeptList(DeptEntity dept) {
        return this.find(new DeptQuery());
    }

    @Override
    public List<DeptTreeSelect> buildDeptTreeSelect(List<DeptEntity> list) {
        List<DeptEntity> returnList = new ArrayList<>();
        List<Long> tempList = list.stream().map(DeptEntity::getId).collect(Collectors.toList());

        for (Iterator<DeptEntity> iterator = list.iterator(); iterator.hasNext(); ) {
            DeptEntity deptEntity = iterator.next();
            List<StaffEntity> staffEntities = staffService.find(new StaffQuery().deptId(deptEntity.getId()));
            List<Map<String,Object>> personList = new ArrayList<>();
            staffEntities.forEach(item->{
                Map<String,Object> map= new HashMap<>();
                map.put("staffId",item.getId());
                map.put("staffName",item.getName());
                map.put("deptId",item.getDeptId());
                personList.add(map);
            });
            deptEntity.setPersonList(personList);
            if (!tempList.contains(deptEntity.getParentId())) {
                recursionFn(list, deptEntity);
                returnList.add(deptEntity);
            }
        }
        if (returnList.isEmpty()) {
            returnList = list;
        }
        return returnList.stream().map(DeptTreeSelect::new).collect(Collectors.toList());
    }


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

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

    /**
     * 得到子节点列表
     */
    private List<DeptEntity> getChildList(List<DeptEntity> list, DeptEntity t) {
        return list.stream().map(item -> {
            if (!ObjectUtils.isEmpty(item.getParentId()) && item.getParentId() == t.getId()) {
                return item;
            }
            return null;
        }).filter(f -> f != null).collect(Collectors.toList());
    }

    @Override
    public List<DeptTreeSelect> getListByParentId(Long parentId, Context context) {
        if (ObjectUtils.isEmpty(parentId)) {
            parentId = 0L;
        }
        //只做一层
        List<DeptTreeSelect> collect = this.find(new DeptQuery().parentId(parentId), context).stream().map(item -> new DeptTreeSelect(item)
        ).collect(Collectors.toList());
        if ("0".equals(parentId)) {
            return collect;
        }

        return collect;
    }




}
