package com.tuoheng.admin.service.dept.delete;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.*;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.code.dept.DeleteDeptCodeEnum;
import com.tuoheng.admin.mapper.DeptMapper;
import com.tuoheng.admin.mapper.RoadDeptMapper;
import com.tuoheng.admin.mapper.SectionDeptMapper;
import com.tuoheng.admin.mapper.UserMapper;
import com.tuoheng.admin.utils.CurrentUserUtil;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 删除部门业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-11-19
 */
@Slf4j
@Service
public class DeleteDeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoadDeptMapper roadDeptMapper;

    @Autowired
    private SectionDeptMapper sectionDeptMapper;


    public JsonResult deleteById(String id) {
        log.info("进入删除部门业务接口");
        String tenantId = CurrentUserUtil.getTenantId();
        JsonResult result = this.check(tenantId, id);
        if (0 != result.getCode()) {
            log.info("删除部门业务接口：校验失败：{}", result.getMsg());
            return result;
        }

        // 在校验中，判断部门是否存在时，若部门存在，直接将部门信息返回，减少数据库查询次数
        Dept dept = (Dept) result.getData();
//        dept.setUpdateUser(SecurityUtils.getUserId());
        dept.setUpdateTime(DateUtils.now());

        Integer rowId = deptMapper.deleteById(id);

        log.info("删除部门, 返回结果: deptId={}", rowId);

        if (rowId <= 0) {
            log.info("删除部门业务接口：删除部门失败：{}", result.getMsg());
            return JsonResult.error(DeleteDeptCodeEnum.DELETE_DEPT_IS_FAILED.getCode(), DeleteDeptCodeEnum.DELETE_DEPT_IS_FAILED.getMsg());
        }

        // 删除该部门下所有公路与部门数据
        this.deleteRoadDept(tenantId, id);

        // 删除该部门下所有路段与部门数据
        this.deleteSectionDept(tenantId, id);

        log.info("删除部门业务接口：删除部门成功：{}");
        return JsonResult.success("删除部门成功");
    }

    /**
     * 检查参数
     * @param tenantId
     * @param id
     * @return
     */
    private JsonResult check(String tenantId, String id) {
        // 判断id是否为空
        if (StringUtils.isEmpty(id)) {
            return JsonResult.error(DeleteDeptCodeEnum.DEPT_ID_IS_NULL.getCode(),DeleteDeptCodeEnum.DEPT_ID_IS_NULL.getMsg());
        }

        // 判断部门是否存在
        Dept dept = deptMapper.selectOne(new LambdaQueryWrapper<Dept>()
                .eq(Dept::getTenantId, tenantId)
                .eq(Dept::getId, id)
                .eq(Dept::getMark, MarkEnum.VALID.getCode()));
        if (null == dept) {
            return JsonResult.error(DeleteDeptCodeEnum.DEPT_IS_NOT_EXIST.getCode(), DeleteDeptCodeEnum.DEPT_IS_NOT_EXIST.getMsg());
        }

        // 该部门下有用户禁止删除
        Integer count = userMapper.selectCount(new LambdaQueryWrapper<User>()
                .eq(User::getTenantId, tenantId)
                .eq(User::getDeptId, id)
                .eq(User::getMark, MarkEnum.VALID.getCode()));
        if (count > 0) {
            return JsonResult.error(DeleteDeptCodeEnum.DEPT_IEXIST_USER.getCode(), DeleteDeptCodeEnum.DEPT_IEXIST_USER.getMsg());
        }

        // 该部门下有部门禁止删除
        count = deptMapper.selectCount(new LambdaQueryWrapper<Dept>()
                .eq(Dept::getTenantId, tenantId)
                .eq(Dept::getPid, id)
                .eq(Dept::getMark, MarkEnum.VALID.getCode()));
        if (count > 0) {
            return JsonResult.error(DeleteDeptCodeEnum.DEPT_IEXIST_CHILDREN_DEPT.getCode(), DeleteDeptCodeEnum.DEPT_IEXIST_CHILDREN_DEPT.getMsg());
        }
        return JsonResult.success(dept);
    }

    /**
     * 删除公路部门数据
     *
     * @param tenantId 租户Id
     * @param deptId   部门Id
     * @return 结果
     */
    private void deleteRoadDept(String tenantId, String deptId) {
        List<String> deptIdList = deptMapper.selectAllChildListById(deptId);
        if (CollectionUtil.isEmpty(deptIdList)) {
            return;
        }
        roadDeptMapper.delete(new LambdaQueryWrapper<RoadDept>()
                .eq(RoadDept::getTenantId, tenantId)
                .in(RoadDept::getDeptId, deptIdList));
    }

    /**
     * 删除路段部门数据
     *
     * @param tenantId 租户Id
     * @param deptId   部门Id
     * @return 结果
     */
    private void deleteSectionDept(String tenantId, String deptId) {
        List<String> deptIdList = deptMapper.selectAllChildListById(deptId);
        if (CollectionUtil.isEmpty(deptIdList)) {
            return;
        }
        sectionDeptMapper.delete(new LambdaQueryWrapper<SectionDept>()
                .eq(SectionDept::getTenantId, tenantId)
                .in(SectionDept::getDeptId, deptIdList));
    }
}
