package com.sckw.system.service;

import cn.hutool.core.collection.CollectionUtil;
import com.sckw.core.exception.SystemException;
import com.sckw.core.model.constant.Global;
import com.sckw.core.utils.CollectionUtils;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.HttpResult;
import com.sckw.system.dao.KwsDeptDao;
import com.sckw.system.dao.KwsUserDeptDao;
import com.sckw.system.model.KwsDept;
import com.sckw.system.model.KwsUserDept;
import com.sckw.system.model.pojo.FindDeptUserPojo;
import com.sckw.system.model.vo.res.KwsDeptResVo;
import org.checkerframework.checker.units.qual.K;
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.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 组织机构service接口
 * @author zk
 * @date 2023-05-31
 */
@Service
public class KwsDeptService {

    @Autowired
    KwsDeptDao kwsDeptDao;

    @Autowired
    KwsRoleService kwsRoleService;

    @Autowired
    KwsUserDeptDao kwsUserDeptDao;

    /**
     * @param params 新增入参
     * @desc: 添加新纪录
     * @author: czh
     * @date: 2023/7/3
     */
    @Transactional(rollbackFor = {})
    public void add(KwsDept params) {
        Long deptId = new IdWorker(1).nextId();
        if (Objects.nonNull(params.getParentId()) && params.getParentId().compareTo(0L) != 0) {
            KwsDept kwsDept = kwsDeptDao.selectByKey(params.getParentId());
            if (Objects.isNull(kwsDept)) {
                throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.PARENT_UNIT_NOT_EXISTS);
            }
            params.setParentIds(kwsDept.getParentIds() + Global.COMMA + deptId);
            params.setLevel(kwsDept.getLevel() != null ? kwsDept.getLevel() + 1 : 1);
        } else {
            params.setParentId(Long.parseLong(Global.PID));
            params.setParentIds(String.valueOf(deptId));
            params.setLevel(Global.NUMERICAL_ONE);
        }

        //查该父级机构有多少子机构，sort依次增加
        KwsDept kwsDeptParam = new KwsDept();
        kwsDeptParam.setParentId(params.getParentId());
        List<KwsDeptResVo> list = kwsDeptDao.findList(kwsDeptParam);
        int sort = 1;
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> deptNameList = list.stream().map(KwsDeptResVo::getName).toList();
            if (deptNameList.contains(params.getName())) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.MSG_024);
            }
            sort = list.get(0).getSort() + 1;
        }
        params.setId(deptId);
        params.setSort(sort);
        if(Objects.isNull(params.getSystemType())) {
            params.setSystemType(LoginUserHolder.getSystemType());
        }

        if (kwsDeptDao.insert(params) <= 0) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
        }
    }

    /**
     * @param ids 主键
     * @desc: 删除记录-根据主键
     * @author: czh
     * @date: 2023/7/3
     */
    public void deleteByKey(String ids) {
        List<Long> list = Arrays.stream(ids.split(",")).map(Long::parseLong).toList();
        List<FindDeptUserPojo> findDeptUserPojoList = kwsDeptDao.findDeptUserByDeptIds(list);
        if (CollectionUtils.isNotEmpty(findDeptUserPojoList)) {
            throw new SystemException(HttpStatus.QUERY_FAIL_CODE, HttpStatus.MSG_020);
        }
        deleteDept(kwsDeptDao.selectByKeys(list));
    }

    /**
     * @param kwsDepts 机构实体类集合
     * @desc: 删除机构
     * @author: czh
     * @date: 2023/6/28
     */
    public void deleteDept(List<KwsDept> kwsDepts) {
        if (CollectionUtils.isEmpty(kwsDepts)) {
            return;
        }

        for (KwsDept kwsDept : kwsDepts) {
            if (kwsDept.getParentId().equals(0L)) {
                throw new SystemException(HttpStatus.CODE_10301, HttpStatus.MSG_027);
            }
            kwsDept.setDelFlag(Global.YES);
            if (kwsDeptDao.update(kwsDept) <= 0) {
                throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.DELETE_FAIL);
            }
        }
    }

    /**
     * 更新记录
     * @param params
     * @return
     * @throws Exception
     */
    public void update(KwsDept params) {
        if(kwsDeptDao.update(params) <= 0){
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
        }
    }

    /**
     * 根据主键查询
     * @param key
     * @return
     * @throws Exception
     */
    public KwsDept selectByKey(Long key) {
        return kwsDeptDao.selectByKey(key);
    }

    /**
     * 分页查询
     * @param params
     * @return
     * @throws Exception
     */
    public List<KwsDeptResVo> findTree(KwsDept params) {
        //机构数据
        List<KwsDeptResVo> deptList = findList(params);
        //跟节点
        List<KwsDeptResVo> rootList = new ArrayList();

        //获取根节点数据
        if (CollectionUtil.isNotEmpty(deptList)) {
            int level = deptList.get(0).getLevel();
            for(KwsDeptResVo kwsDept:deptList){
                if (kwsDept.getLevel() == level) {
                    rootList.add(kwsDept);
                }
            }
        }

        //遍历，找到二级机构（根机构的id和所有机构中的pid比较）
        for (KwsDeptResVo kwsDept : rootList) {
            List<KwsDeptResVo> child = getChild(kwsDept.getId(), deptList);
            kwsDept.setChildren(child);
        }

        return rootList;
    }

    /**
     * @param kwsDept
     * @return  List<KwsDeptResVo>
     * @desc: 全量查机构
     * @author: czh
     * @date: 2023/6/15
     */
    public List<KwsDeptResVo> findList(KwsDept kwsDept){
        return kwsDeptDao.findList(kwsDept);
    }

    /**
     * 递归获取下级机构
     * @param parentId 父级机构id
     * @param deptList 所有机构
     * @return
     */
    public List<KwsDeptResVo> getChild(Long parentId, List<KwsDeptResVo> deptList) {
        List<KwsDeptResVo> childList = new ArrayList();
        for (KwsDeptResVo kwsDept : deptList) {
            if(parentId.equals(kwsDept.getParentId())){
                //获取当前机构id的所有子列表
                childList.add(kwsDept);
            }
        }
        for (KwsDeptResVo kwsDept : childList) {
            //将该id的子机构进行遍历，通过递归调用，获取每一个子机构的子机构数据
            List<KwsDeptResVo> child = getChild(kwsDept.getId(), deptList);
            kwsDept.setChildren(child);
        }
        if(childList.size()==0){
            //子机构的长度为0,返回null,null不会被阿里的FastJson包解析
            return  null;
        }
        return childList;
    }

    /**
     * @param kwsUserDeptList
     * @desc: 存用户机构关联关系
     * @author: czh
     * @date: 2023/6/14
     */
    public void addUserDept(List<KwsUserDept> kwsUserDeptList) {
        if (kwsUserDeptDao.saveBatch(kwsUserDeptList) < kwsUserDeptList.size()) {
            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
        }
    }

}
