package com.qiaoba.module.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.qiaoba.api.system.entity.SysDept;
import com.qiaoba.api.system.entity.param.SysDeptParam;
import com.qiaoba.api.auth.utils.SecurityUtil;
import com.qiaoba.common.base.constant.BaseConstant;
import com.qiaoba.common.base.enums.BaseEnum;
import com.qiaoba.common.base.exception.ServiceException;
import com.qiaoba.module.system.mapper.SysDeptMapper;
import com.qiaoba.module.system.service.SysDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 部门管理 服务层实现
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/5/6 15:02
 */
@Service
@RequiredArgsConstructor
public class SysDeptServiceImpl implements SysDeptService {

    private final SysDeptMapper sysDeptMapper;


    @Override
    public int insert(SysDept sysDept) {
        if (checkDeptNameNotUnique(sysDept)) {
            throw new ServiceException("同级下部门名称不允许重复!");
        }
        sysDept.setCreateTime(new Date());
        sysDept.setCreateUser(SecurityUtil.getLoginUsername());
        if (Objects.isNull(sysDept.getParentId()) || BaseConstant.DEFAULT_PARENT_ID_VALUE.equals(sysDept.getParentId())) {
            return sysDeptMapper.insert(sysDept);
        }
        SysDept info = sysDeptMapper.selectById(sysDept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (BaseEnum.ABNORMAL.getCode().equals(info.getStatus())) {
            throw new ServiceException("上级部门停用，不允许新增");
        }
        sysDept.setAncestors(info.getAncestors() + BaseConstant.DEFAULT_SPLIT_STR + sysDept.getParentId());
        return sysDeptMapper.insert(sysDept);
    }

    @Override
    public int updateById(SysDept sysDept) {
        if (checkDeptNameNotUnique(sysDept)) {
            throw new ServiceException("同级下部门名称不允许重复!");
        }
        sysDept.setUpdateTime(new Date());
        sysDept.setUpdateUser(SecurityUtil.getLoginUsername());
        SysDept newParentDept = sysDeptMapper.selectById(sysDept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (Objects.nonNull(newParentDept) && BaseEnum.ABNORMAL.getCode().equals(newParentDept.getStatus())) {
            throw new ServiceException("上级部门停用，不允许插入");
        }
        SysDept oldDept = sysDeptMapper.selectById(sysDept.getDeptId());
        if (Objects.nonNull(newParentDept) && Objects.nonNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + BaseConstant.DEFAULT_SPLIT_STR + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            sysDept.setAncestors(newAncestors);
            updateDeptChildren(sysDept.getDeptId(), newAncestors, oldAncestors);
        }
        return sysDeptMapper.updateById(sysDept);
    }

    @Override
    public List<SysDept> selectList(SysDeptParam param) {
        return sysDeptMapper.selectList(param2Wrapper(param));
    }

    @Override
    public SysDept selectById(String deptId) {
        return sysDeptMapper.selectById(deptId);
    }

    @Override
    public int deleteById(String deptId) {
        if (StrUtil.isNotBlank(sysDeptMapper.existChild(deptId))) {
            throw new ServiceException("存在子级部门，不允许删除");
        }
        String nickname = sysDeptMapper.existUsed(deptId);
        if (StrUtil.isNotBlank(nickname)) {
            throw new ServiceException(StrUtil.format("用户[{}]已绑定该部门，请解绑后删除", nickname));
        }
        return sysDeptMapper.deleteById(deptId);
    }


    @Override
    public List<String> selectDeptIdsByRoleId(String roleId) {
        return sysDeptMapper.selectDeptIdsByRoleId(roleId);
    }

    @Override
    public List<SysDept> excludeChild(String deptId) {
        List<SysDept> deptList = selectList(new SysDeptParam());
        deptList.removeIf(dept -> dept.getDeptId().equals(deptId)
                || StrUtil.split(dept.getAncestors(), BaseConstant.DEFAULT_SPLIT_STR).contains(deptId));
        return deptList;
    }

    @Override
    public List<Tree<String>> buildDeptTree(List<SysDept> list) {
        if (CollUtil.isEmpty(list)) {
            return CollUtil.newArrayList();
        }
        TreeNodeConfig config = TreeNodeConfig.DEFAULT_CONFIG.setNameKey(BaseConstant.TREE_KEY_NAME);
        return TreeUtil.build(list, BaseConstant.DEFAULT_PARENT_ID_VALUE, config, (dept, tree) ->
                tree.setId(dept.getDeptId())
                        .setParentId(dept.getParentId())
                        .setName(dept.getDeptName())
                        .setWeight(dept.getOrderNum()));
    }

    private QueryWrapper<SysDept> param2Wrapper(SysDeptParam param) {
        QueryWrapper<SysDept> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .orderByAsc(SysDept::getOrderNum)
                .like(StrUtil.isNotBlank(param.getDeptName()), SysDept::getDeptName, param.getDeptName())
                .eq(StrUtil.isNotBlank(param.getStatus()), SysDept::getStatus, param.getStatus());
        return wrapper;
    }

    private boolean checkDeptNameNotUnique(SysDept dept) {
        return StrUtil.isNotBlank(sysDeptMapper.checkDeptNameUnique(dept));
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    private void updateDeptChildren(String deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = selectChildrenDeptById(deptId);
        if (CollUtil.isEmpty(children)) {
            return;
        }
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        List<SysDept> list = new ArrayList<>();
        for (SysDept child : children) {
            SysDept dept = new SysDept();
            dept.setDeptId(child.getDeptId());
            dept.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
            list.add(dept);
        }
        if (CollUtil.isEmpty(list)) {
            return;
        }
        Db.updateBatchById(list);
    }

    private List<SysDept> selectChildrenDeptById(String deptId) {
        List<SysDept> deptList = selectList(new SysDeptParam());
        deptList.removeIf(dept -> !StrUtil.split(dept.getAncestors(), BaseConstant.DEFAULT_SPLIT_STR).contains(deptId));
        return deptList;
    }
}
