package cn.iocoder.yudao.module.server.service.workorderType;

import cn.iocoder.yudao.module.server.dal.dataobject.workorderInfos.WorkorderInfosDO;
import cn.iocoder.yudao.module.server.dal.mysql.workorderInfos.WorkorderInfosMapper;
import cn.iocoder.yudao.module.system.dal.dataobject.dept.DeptDO;
import cn.iocoder.yudao.module.system.dal.mysql.dept.DeptMapper;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.iocoder.yudao.module.server.controller.admin.workorderType.vo.*;
import cn.iocoder.yudao.module.server.dal.dataobject.workorderType.WorkorderTypeDO;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.server.dal.mysql.workorderType.WorkorderTypeMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.server.enums.ErrorCodeConstants.*;

/**
 * 工单类型 Service 实现类
 *
 * @author wyj
 */
@Service
@Validated
public class WorkorderTypeServiceImpl implements WorkorderTypeService {

    @Resource
    private WorkorderTypeMapper workorderTypeMapper;

    @Resource
    private AdminUserMapper adminUserMapper;

    @Resource
    private DeptMapper deptMapper;

    @Resource
    private WorkorderInfosMapper workorderInfosMapper;

    @Override
    public Long createWorkorderType(WorkorderTypeSaveReqVO createReqVO) {
        // 校验父栏目id的有效性
        validateParentWorkorderType(null, createReqVO.getParentId());
        // 校验工单类型名称的唯一性
        validateWorkorderTypeNameUnique(null, createReqVO.getParentId(), createReqVO.getName());

        // 插入
        WorkorderTypeDO workorderType = BeanUtils.toBean(createReqVO, WorkorderTypeDO.class);
        workorderTypeMapper.insert(workorderType);
        // 返回
        return workorderType.getId();
    }

    @Override
    public void updateWorkorderType(WorkorderTypeSaveReqVO updateReqVO) {
        // 校验存在
        validateWorkorderTypeExists(updateReqVO.getId());
        // 校验父栏目id的有效性
        validateParentWorkorderType(updateReqVO.getId(), updateReqVO.getParentId());
        // 校验工单类型名称的唯一性
        validateWorkorderTypeNameUnique(updateReqVO.getId(), updateReqVO.getParentId(), updateReqVO.getName());

        // 更新
        WorkorderTypeDO updateObj = BeanUtils.toBean(updateReqVO, WorkorderTypeDO.class);
        workorderTypeMapper.updateById(updateObj);
    }

    @Override
    public void deleteWorkorderType(Long id) {
        // 校验存在
        validateWorkorderTypeExists(id);
        // 校验是否有子工单类型
        if (workorderTypeMapper.selectCountByParentId(id) > 0) {
            throw exception(WORKORDER_TYPE_EXITS_CHILDREN);
        }
        //校验是否有该类型工单
        LambdaQueryWrapper<WorkorderInfosDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WorkorderInfosDO::getCategoryId,id);
        List<WorkorderInfosDO> list = workorderInfosMapper.selectList(wrapper);
        if(list.size() > 0) {
            throw exception(WORKORDER_INFO_EXITS);
        }
        // 删除
        workorderTypeMapper.deleteById(id);
    }

    private void validateWorkorderTypeExists(Long id) {
        if (workorderTypeMapper.selectById(id) == null) {
            throw exception(WORKORDER_TYPE_NOT_EXISTS);
        }
    }

    private void validateParentWorkorderType(Long id, Long parentId) {
        if (parentId == null || WorkorderTypeDO.PARENT_ID_ROOT.equals(parentId)) {
            return;
        }
        // 1. 不能设置自己为父工单类型
        if (Objects.equals(id, parentId)) {
            throw exception(WORKORDER_TYPE_PARENT_ERROR);
        }
        // 2. 父工单类型不存在
        WorkorderTypeDO parentWorkorderType = workorderTypeMapper.selectById(parentId);
        if (parentWorkorderType == null) {
            throw exception(WORKORDER_TYPE_PARENT_NOT_EXITS);
        }
        // 3. 递归校验父工单类型，如果父工单类型是自己的子工单类型，则报错，避免形成环路
        if (id == null) { // id 为空，说明新增，不需要考虑环路
            return;
        }
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            // 3.1 校验环路
            parentId = parentWorkorderType.getParentId();
            if (Objects.equals(id, parentId)) {
                throw exception(WORKORDER_TYPE_PARENT_IS_CHILD);
            }
            // 3.2 继续递归下一级父工单类型
            if (parentId == null || WorkorderTypeDO.PARENT_ID_ROOT.equals(parentId)) {
                break;
            }
            parentWorkorderType = workorderTypeMapper.selectById(parentId);
            if (parentWorkorderType == null) {
                break;
            }
        }
    }

    private void validateWorkorderTypeNameUnique(Long id, Long parentId, String name) {
        WorkorderTypeDO workorderType = workorderTypeMapper.selectByParentIdAndName(parentId, name);
        if (workorderType == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的工单类型
        if (id == null) {
            throw exception(WORKORDER_TYPE_NAME_DUPLICATE);
        }
        if (!Objects.equals(workorderType.getId(), id)) {
            throw exception(WORKORDER_TYPE_NAME_DUPLICATE);
        }
    }

    @Override
    public WorkorderTypeDO getWorkorderType(Long id) {
        return workorderTypeMapper.selectById(id);
    }

    @Override
    public List<WorkorderTypeDO> getWorkorderTypeList(WorkorderTypeListReqVO listReqVO) {
        return workorderTypeMapper.selectList(listReqVO);
    }

    @Override
    public List<DeptDO> getSuplierListWorkorder(String suplier) {
        String[] listSuplier = suplier.split(",");
        LambdaQueryWrapper<DeptDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DeptDO::getId,listSuplier );
        return deptMapper.selectList(wrapper);
    }

    @Override
    public List<DeptDO> getSuplierList(String suplier) {
        LambdaQueryWrapper<DeptDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DeptDO::getParentId,110 );
        return deptMapper.selectList(wrapper);
    }

}