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

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.Dept;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.enums.code.dept.QueryDeptChildListCodeEnum;
import com.tuoheng.admin.mapper.DeptMapper;
import com.tuoheng.admin.utils.CurrentUserUtil;
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.List;

/**
 *  根据id查询子部门列表业务层处理
 *
 * @author wanjing
 * @team tuoheng
 * @date 2022-11-22
 */
@Slf4j
@Service
public class QueryChildListService {

    @Autowired
    private DeptMapper deptMapper;

    /**
     * 获取部门树形列表
     *
     * @return
     */
    public JsonResult getChildList(String deptId) {
        log.info("进入查询子部门列表业务");
        String tenantId = CurrentUserUtil.getTenantId();
        JsonResult result = this.check(tenantId, deptId);
        if (0 != result.getCode()) {
            log.info("根据id查询子部门列表业务：校验失败：{}", result.getMsg());
            return result;
        }
        List<String> deptIdList = deptMapper.selectAllChildListById(deptId);
        if (CollectionUtil.isEmpty(deptIdList)) {
            log.info("获取部门列表为空");
            return JsonResult.error(QueryDeptChildListCodeEnum.DEPT_LIST_IS_FAILED.getCode(), QueryDeptChildListCodeEnum.DEPT_LIST_IS_FAILED.getMsg());
        }
        List<Dept> deptList = deptMapper.selectListByIdList(deptIdList);
        return JsonResult.success(deptList);
    }

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

        // 判断部门是否存在
        Integer count = deptMapper.selectCount(new LambdaQueryWrapper<Dept>()
                .eq(Dept::getTenantId, tenantId)
                .eq(Dept::getId, id)
                .eq(Dept::getMark, MarkEnum.VALID.getCode()));
        if (count <= 0) {
            return JsonResult.error(QueryDeptChildListCodeEnum.DEPT_IS_NOT_EXIST.getCode(), QueryDeptChildListCodeEnum.DEPT_IS_NOT_EXIST.getMsg());
        }
        return JsonResult.success();
    }
}
