package com.testor.ddd.safetyControl.application.service.equipmentManage.impl;

import cn.hutool.core.util.StrUtil;
import com.testor.ddd.safetyControl.application.service.equipmentManage.EquipmentManageService;
import com.testor.ddd.safetyControl.application.service.equipmentManage.EquipmentTypeManageService;
import com.testor.ddd.safetyControl.domain.equipment.entity.TSafeEquipmentRepo;
import com.testor.ddd.safetyControl.domain.equipment.entity.TSafeEquipmentTypeRepo;
import com.testor.ddd.safetyControl.domain.equipment.service.EquipmentTypeService;
import com.testor.ddd.safetyControl.infrastructure.client.funConfClient.TableNumClient;
import com.testor.ddd.safetyControl.infrastructure.repository.equipment.dao.TSafeEquipmentDao;
import com.testor.ddd.safetyControl.infrastructure.uitls.GenerateCode;
import com.testor.ddd.safetyControl.interfaces.model.dto.equipment.TSafeEquipmentDTO;
import com.testor.ddd.safetyControl.interfaces.model.dto.equipment.TSafeEquipmentDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.dto.equipment.TSafeEquipmentTypeDTO;
import com.testor.ddd.safetyControl.interfaces.model.dto.equipment.TSafeEquipmentTypeDTOParam;
import com.testor.ddd.safetyControl.interfaces.model.vo.equipment.TSafeEquipmentTypeVO;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.constants.enumeration.BaseStatusEnum;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.sys.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class EquipmentTypeManageServiceImpl implements EquipmentTypeManageService {

    @Resource
    private EquipmentTypeService equipmentTypeService;

    @Resource
    private TSafeEquipmentTypeRepo tSafeEquipmentTypeRepo;

    @Resource
    private EquipmentManageService equipmentManageService;

    @Resource
    private TableNumClient tableNumClient;

    @Resource
    private GenerateCode generateCode;

    @Resource
    private TSafeEquipmentRepo equipmentRepo;

    @Autowired(required = false)
    private TSafeEquipmentDao tSafeEquipmentDao;

    /**
     * 编辑空间
     *
     * @param equipmentTypeDto
     * @return
     */
    @Transactional
    public BaseResponse editEquipmentType(TSafeEquipmentTypeDTO equipmentTypeDto) {
        BaseResponse baseResponse = new BaseResponse<>();

        UserInfo curUser = ContextUtils.getLoginUser();
        if (StrUtil.isBlank(curUser.getOrgId())) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("用户信息错误");
            return baseResponse;
        }

        if(StrUtil.isBlank(equipmentTypeDto.getName()) ||
            StrUtil.isBlank(equipmentTypeDto.getCode())){
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("参数缺失");
            return baseResponse;
        }

        String curUserOrgId = curUser.getOrgId();
        equipmentTypeDto.setOrgId(curUserOrgId);

        // todo 逻辑待续 编号发生变化时，获取旧的 设备编号
        String id = equipmentTypeDto.getId();
        String fieldNameOld = null;
        if(!StrUtil.isBlank(id)) {
            TSafeEquipmentTypeDTO oldEquipmentType = findById(id);
            String oldCode = oldEquipmentType.getCode();
            String oldParentId = oldEquipmentType.getParentId();
            if(!equipmentTypeDto.getCode().equals(oldCode)) {
                TSafeEquipmentDTO equipmentDTOOld = new TSafeEquipmentDTO();
                equipmentDTOOld.setOrgId(curUserOrgId);
                if("0".equals(oldParentId)) {
                    equipmentDTOOld.setSysTypeId(id);
                } else {
                    equipmentDTOOld.setSysTypeId(oldParentId);
                    equipmentDTOOld.setEquipmentTypeId(id);
                }

                fieldNameOld = generateCode.generateEquipmentTableNumFieldName(equipmentDTOOld);
            }
        }

        baseResponse = equipmentTypeService.editEquipmentType(curUser.getUserId(), curUserOrgId, equipmentTypeDto);

        if (!StrUtil.isBlank(fieldNameOld) && BaseStatusEnum.SUCCESS.code() == baseResponse.getCode().intValue()) {
            // 逻辑待续 车间类型编号变化 同时 修改 t_table_num表中的 fieldName的值
            TSafeEquipmentDTO equipmentDTONew = new TSafeEquipmentDTO();
            equipmentDTONew.setOrgId(curUserOrgId);
            if("0".equals(equipmentTypeDto.getParentId())) {
                equipmentDTONew.setSysTypeId(id);
            } else {
                equipmentDTONew.setSysTypeId(equipmentTypeDto.getParentId());
                equipmentDTONew.setEquipmentTypeId(id);
            }
           // equipmentDTONew.setEquipmentTypeId(equipmentTypeDto.getId());
            String fieldNameNew = generateCode.generateEquipmentTableNumFieldName(equipmentDTONew);

            tableNumClient.replaceFieldName("t_safe_equipment", fieldNameOld, fieldNameNew);
            equipmentManageService.replaceCode(id, fieldNameOld, fieldNameNew);
        }
        return baseResponse;
    }


    public BaseResponseList<TSafeEquipmentTypeVO> listByPage(TSafeEquipmentTypeDTOParam param) {
//        UserInfo curUser = ContextUtils.getLoginUser();
//        String curUserOrgId = curUser.getOrgId();
//        param.setOrgId(curUserOrgId);
        return equipmentTypeService.listByPage(param);
    }

    public TSafeEquipmentTypeDTO findById(String id) {
        return tSafeEquipmentTypeRepo.findById(id);
    }

    /**
     *
     * @param type 0-设备系统类型； 1-设备类型
     * @param id
     * @return
     */
    @Transactional
    public BaseResponse deleteById(int type, String id) {
        BaseResponse baseResponse = new BaseResponse<>();
        if(StrUtil.isBlank(id)) {
            return baseResponse;
        }

        UserInfo curUser = ContextUtils.getLoginUser();
        if (StrUtil.isBlank(curUser.getOrgId())) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("用户信息错误");
            return baseResponse;
        }
        String curUserOrgId = curUser.getOrgId();
        TSafeEquipmentTypeDTO oldEquipmentTypeDto = tSafeEquipmentTypeRepo.findById(id);
        if (!curUserOrgId.equals(oldEquipmentTypeDto.getOrgId())) {
            baseResponse.setCode(BaseStatusEnum.UNAUTHORIZED.code());
            baseResponse.setMsg("无权限操作");
            return baseResponse;
        }

        Boolean result = tSafeEquipmentTypeRepo.deleteById(id);
        if(!result) {
            return baseResponse;
        }

         //*  删除车间场所类型下的 所有车间场所、作业区域
        equipmentManageService.deleteByEquipmentType(type, id);

        return baseResponse;
    }

    @Override
    public BaseResponseList<TSafeEquipmentTypeVO> listByPages(TSafeEquipmentTypeDTOParam param) {
        TSafeEquipmentDTOParam params=new TSafeEquipmentDTOParam();
        List<String>s=new ArrayList<>();
        s.add(param.getOrgId());
        params.setCondOrgIdList(s);
        BaseResponseList<TSafeEquipmentTypeVO> tSafeEquipmentTypeVOBaseResponseList = equipmentTypeService.listByPage(param);
        List<TSafeEquipmentTypeVO> data = tSafeEquipmentTypeVOBaseResponseList.getData();
        List<TSafeEquipmentTypeVO> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(data)&& data.size()>0) {
            for (TSafeEquipmentTypeVO datum : data) {
                List<String>types=new ArrayList<>();
                types.add(datum.getId());
                params.setCondEquipmentTypeIdList(types);
                if (equipmentRepo.listPage(params).getData().size()>0) {
                    list.add(datum);
                }
            }

        }
        tSafeEquipmentTypeVOBaseResponseList.setData(list);

        return tSafeEquipmentTypeVOBaseResponseList;
    }
}
