package com.cico.nest.lcdp.boot.core.system.service.dept;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cico.nest.lcdp.boot.core.system.controller.admin.dept.vo.dept.DeptListReqVO;
import com.cico.nest.lcdp.boot.core.system.controller.admin.dept.vo.dept.DeptRespVO;
import com.cico.nest.lcdp.boot.core.system.controller.admin.dept.vo.dept.DeptSaveReqV2VO;
import com.cico.nest.lcdp.boot.core.system.controller.admin.dept.vo.dept.DeptSaveReqVO;
import com.cico.nest.lcdp.boot.core.system.dal.dataobject.dept.DeptDO;
import com.cico.nest.lcdp.boot.core.system.dal.mysql.dept.DeptMapper;
import com.cico.nest.lcdp.boot.core.system.dal.redis.RedisKeyConstants;
import com.cico.nest.lcdp.framework.common.enums.CommonStatusEnum;
import com.cico.nest.lcdp.framework.common.util.object.BeanUtils;
import com.cico.nest.lcdp.framework.datapermission.core.annotation.DataPermission;
import com.cico.nest.lcdp.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.google.common.annotations.VisibleForTesting;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.util.*;

import static com.cico.nest.lcdp.boot.api.system.enums.ErrorCodeConstants.*;
import static com.cico.nest.lcdp.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cico.nest.lcdp.framework.common.util.collection.CollectionUtils.convertSet;

/**
 * 部门 Service 实现类
 *
 * @author zws
 */
@Service
@Validated
@Slf4j
public class DeptServiceImpl implements DeptService {

    @Resource
    private DeptMapper deptMapper;

    @Override
    @CacheEvict(cacheNames = {RedisKeyConstants.DEPT_CHILDREN_ID_LIST, RedisKeyConstants.DEPT_BY_ID},
            allEntries = true) // allEntries 清空所有缓存，因为操作一个部门，涉及到多个缓存
    public String createDept(DeptSaveReqVO createReqVO) {
        if (createReqVO.getParentId() == null) {
            createReqVO.setParentId(DeptDO.PARENT_ID_ROOT);
        }
        // 校验父部门的有效性
        validateParentDept(null, createReqVO.getParentId());
        // 校验部门名的唯一性
        validateDeptNameUnique(null, createReqVO.getParentId(), createReqVO.getName());

        // 插入部门
        DeptDO dept = BeanUtils.toBean(createReqVO, DeptDO.class);
        //增加部门等级字段
        if(DeptDO.PARENT_ID_ROOT.equals(dept.getParentId())){
            dept.setLevel(DeptDO.PARENT_LEVEL);
        }else{
            DeptDO parentDep = deptMapper.selectById(dept.getParentId());
            dept.setLevel(parentDep.getLevel() + 1);
        }
        deptMapper.insert(dept);
        return dept.getId();
    }

    @Override
    @CacheEvict(cacheNames = {RedisKeyConstants.DEPT_CHILDREN_ID_LIST, RedisKeyConstants.DEPT_BY_ID},
            allEntries = true) // allEntries 清空所有缓存，因为操作一个部门，涉及到多个缓存
    public void updateDept(DeptSaveReqVO updateReqVO) {
        if (updateReqVO.getParentId() == null) {
            updateReqVO.setParentId(DeptDO.PARENT_ID_ROOT);
        }
        // 校验自己存在
        validateDeptExists(updateReqVO.getId());
        // 校验父部门的有效性
        validateParentDept(updateReqVO.getId(), updateReqVO.getParentId());
        // 校验部门名的唯一性
        validateDeptNameUnique(updateReqVO.getId(), updateReqVO.getParentId(), updateReqVO.getName());
        // 更新部门
        DeptDO updateObj = BeanUtils.toBean(updateReqVO, DeptDO.class);//增加部门等级字段
        if(DeptDO.PARENT_ID_ROOT.equals(updateObj.getParentId())){
            updateObj.setLevel(DeptDO.PARENT_LEVEL);
        }else{
            DeptDO parentDep = deptMapper.selectById(updateObj.getParentId());
            updateObj.setLevel(parentDep.getLevel() + 1);
        }
        deptMapper.updateById(updateObj);
    }

    @Override
    @CacheEvict(cacheNames = {RedisKeyConstants.DEPT_CHILDREN_ID_LIST, RedisKeyConstants.DEPT_BY_ID},
            allEntries = true) // allEntries 清空所有缓存，因为操作一个部门，涉及到多个缓存
    public void deleteDept(String id) {
        // 校验是否存在
        validateDeptExists(id);
        // 校验是否有子部门
        if (deptMapper.selectCountByParentId(id) > 0) {
            throw exception(DEPT_EXITS_CHILDREN);
        }
        // 删除部门
        deptMapper.deleteById(id);
    }

//    @VisibleForTesting
    void validateDeptExists(String id) {
        if (id == null) {
            return;
        }
        DeptDO dept = deptMapper.selectById(id);
        if (dept == null) {
            throw exception(DEPT_NOT_FOUND);
        }
    }

//    @VisibleForTesting
    void validateParentDept(String id, String parentId) {
        if (parentId == null || DeptDO.PARENT_ID_ROOT.equals(parentId)) {
            return;
        }
        // 1. 不能设置自己为父部门
        if (Objects.equals(id, parentId)) {
            throw exception(DEPT_PARENT_ERROR);
        }
        // 2. 父部门不存在
        DeptDO parentDept = deptMapper.selectById(parentId);
        if (parentDept == null) {
            throw exception(DEPT_PARENT_NOT_EXITS);
        }
        // 3. 递归校验父部门，如果父部门是自己的子部门，则报错，避免形成环路
        if (id == null) { // id 为空，说明新增，不需要考虑环路
            return;
        }
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            // 3.1 校验环路
            parentId = parentDept.getParentId();
            if (Objects.equals(id, parentId)) {
                throw exception(DEPT_PARENT_IS_CHILD);
            }
            // 3.2 继续递归下一级父部门
            if (parentId == null || DeptDO.PARENT_ID_ROOT.equals(parentId)) {
                break;
            }
            parentDept = deptMapper.selectById(parentId);
            if (parentDept == null) {
                break;
            }
        }
    }

    @VisibleForTesting
    void validateDeptNameUnique(String id, String parentId, String name) {
        DeptDO dept = deptMapper.selectByParentIdAndName(parentId, name);
        if (dept == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的部门
        if (id == null) {
            throw exception(DEPT_NAME_DUPLICATE);
        }
        if (ObjectUtil.notEqual(dept.getId(), id)) {
            throw exception(DEPT_NAME_DUPLICATE);
        }
    }

    @Override
    @Cacheable(cacheNames = RedisKeyConstants.DEPT_BY_ID, key = "#id")
    public DeptDO getDept(String id) {
        return deptMapper.selectById(id);
    }

    @Override
    public List<DeptDO> getDeptList(Collection<String> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return deptMapper.selectBatchIds(ids);
    }

    @Override
    public List<DeptDO> listDeptByNames(Collection<String> deptNames) {
        LambdaQueryWrapperX<DeptDO> wrapper = new LambdaQueryWrapperX<>();
        wrapper.in(DeptDO::getName, deptNames);
        return deptMapper.selectList(wrapper);
    }

    @Override
    public List<DeptDO> getDeptList(DeptListReqVO reqVO) {
        List<DeptDO> list = deptMapper.selectList(reqVO);
        list.sort(Comparator.comparing(DeptDO::getSort));
        return list;
    }

    @Override
    public List<DeptRespVO> getDeptListV2(DeptListReqVO reqVO) {
        List<DeptRespVO> list = deptMapper.selectListV2(reqVO);
        list.sort(Comparator.comparing(DeptRespVO::getSort));
        return list;
    }

    @Override
    public List<DeptRespVO> getSubDeptList(String deptId) {
        LambdaQueryWrapper<DeptDO> wrapper = new LambdaQueryWrapper<DeptDO>()
                .eq(DeptDO::getDeleted, 0)
                .eq(DeptDO::getParentId,deptId)
                .orderByAsc(DeptDO::getSort);
        List<DeptDO> list = deptMapper.selectList(wrapper);
        List<DeptRespVO> respList = BeanUtils.toBean(list, DeptRespVO.class);
        return respList;
    }

    @Override
    public List<DeptDO> getChildDeptList(String id) {
        List<DeptDO> children = new LinkedList<>();
        // 遍历每一层
        Collection<String> parentIds = Collections.singleton(id);
        for (int i = 0; i < Short.MAX_VALUE; i++) { // 使用 Short.MAX_VALUE 避免 bug 场景下，存在死循环
            // 查询当前层，所有的子部门
            List<DeptDO> depts = deptMapper.selectListByParentId(parentIds);
            // 1. 如果没有子部门，则结束遍历
            if (CollUtil.isEmpty(depts)) {
                break;
            }
            // 2. 如果有子部门，继续遍历
            children.addAll(depts);
            parentIds = convertSet(depts, DeptDO::getId);
        }
        return children;
    }

    @Override
    @DataPermission(enable = false) // 禁用数据权限，避免建立不正确的缓存
    @Cacheable(cacheNames = RedisKeyConstants.DEPT_CHILDREN_ID_LIST, key = "#id")
    public Set<String> getChildDeptIdListFromCache(String id) {
        List<DeptDO> children = getChildDeptList(id);
        return convertSet(children, DeptDO::getId);
    }

    @Override
    public void validateDeptList(Collection<String> ids) {
        if (CollUtil.isEmpty(ids)) {
            return;
        }
        // 获得科室信息
        Map<String, DeptDO> deptMap = getDeptMap(ids);
        // 校验
        ids.forEach(id -> {
            DeptDO dept = deptMap.get(id);
            if (dept == null) {
                throw exception(DEPT_NOT_FOUND);
            }
            if (!CommonStatusEnum.ENABLE.getStatus().equals(dept.getStatus())) {
                throw exception(DEPT_NOT_ENABLE, dept.getName());
            }
        });
    }

    @Override
    @CacheEvict(cacheNames = {RedisKeyConstants.DEPT_CHILDREN_ID_LIST, RedisKeyConstants.DEPT_BY_ID},
            allEntries = true) // allEntries 清空所有缓存，因为操作一个部门，涉及到多个缓存
    public String createDeptV2(DeptSaveReqV2VO createReqVO) {
        if (createReqVO.getParentId() == null) {
            createReqVO.setParentId(DeptDO.PARENT_ID_ROOT);
        }
        // 校验父部门的有效性
        validateParentDept(null, createReqVO.getParentId());
        // 校验部门名的唯一性
        validateDeptNameUnique(null, createReqVO.getParentId(), createReqVO.getName());
        // 插入部门
        DeptDO dept = BeanUtils.toBean(createReqVO, DeptDO.class);
        //增加部门等级字段
        if(DeptDO.PARENT_ID_ROOT.equals(dept.getParentId())){
            dept.setLevel(DeptDO.PARENT_LEVEL);
        }
        String id = StringUtils.isEmpty(dept.getId())?String.valueOf(IdUtil.getSnowflake().nextId()):dept.getId();
        dept.setId(id);
        dept.setStatus(CommonStatusEnum.ENABLE.getStatus());//默认开启
        deptMapper.insert(dept);
        return dept.getId();
    }



    @Override
    @CacheEvict(cacheNames = {RedisKeyConstants.DEPT_CHILDREN_ID_LIST, RedisKeyConstants.DEPT_BY_ID},
            allEntries = true) // allEntries 清空所有缓存，因为操作一个部门，涉及到多个缓存
    public void updateDeptV2(DeptSaveReqV2VO updateReqVO) {
        if (updateReqVO.getParentId() == null) {
            updateReqVO.setParentId(DeptDO.PARENT_ID_ROOT);
        }
        // 校验自己存在
        validateDeptExists(updateReqVO.getId());
        // 校验父部门的有效性
        validateParentDept(updateReqVO.getId(), updateReqVO.getParentId());
        // 校验部门名的唯一性
        validateDeptNameUnique(updateReqVO.getId(), updateReqVO.getParentId(), updateReqVO.getName());
        // 更新部门
        DeptDO updateObj = BeanUtils.toBean(updateReqVO, DeptDO.class);//增加部门等级字段
        if(DeptDO.PARENT_ID_ROOT.equals(updateObj.getParentId())){
            updateObj.setLevel(DeptDO.PARENT_LEVEL);
        }
        deptMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDepts(List<String> ids) {
        for (String id : ids){
            deleteDept(id);
        }
    }
}
