package com.testor.ddd.safetyControl.domain.lecls.service.impl;

import cn.hutool.core.util.StrUtil;
import com.testor.ddd.safetyControl.domain.lecls.entity.TSafeRiskLeclsConfRepo;
import com.testor.ddd.safetyControl.domain.lecls.entity.TSafeRiskLeclsRelationRepo;
import com.testor.ddd.safetyControl.domain.lecls.service.RiskLeclsService;
import com.testor.ddd.safetyControl.interfaces.model.dto.lecls.TSafeRiskLeclsConfDTO;
import com.testor.ddd.safetyControl.interfaces.model.dto.lecls.TSafeRiskLeclsRelationDTO;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.constants.enumeration.BaseStatusEnum;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class RiskLeslsServiceImpl implements RiskLeclsService {

    @Resource
    private TSafeRiskLeclsConfRepo riskLeclsConfRepo;
    @Resource
    private TSafeRiskLeclsRelationRepo riskLeclsRelationRepo;

    /**
     * 编辑空间
     *
     * @param riskLeclsConfDtoList
     * @return
     */
    @Transactional
    public BaseResponse<List<TSafeRiskLeclsConfDTO>> editRiskLeclsConf(String userId, List<TSafeRiskLeclsConfDTO> riskLeclsConfDtoList) {
        BaseResponse baseResponse = new BaseResponse<>();

        if(riskLeclsConfDtoList == null || riskLeclsConfDtoList.size() == 0) {
            baseResponse.setCode(BaseStatusEnum.UNKNOWN.code());
            baseResponse.setMsg("参数缺失");
            return baseResponse;
        }

        boolean isNew =  StrUtil.isBlank(riskLeclsConfDtoList.get(0).getId());

        List<TSafeRiskLeclsConfDTO> editList = new ArrayList<>();
        for(TSafeRiskLeclsConfDTO riskLeclsConfDto : riskLeclsConfDtoList) {

            String dataId = riskLeclsConfDto.getId();
            boolean checkResult = checkUniqueness(dataId, riskLeclsConfDto.getType(), riskLeclsConfDto.getCode());
            if (!checkResult) {
                baseResponse.setCode(BaseStatusEnum.UNKNOWN.code());
                baseResponse.setMsg("已存在相同编号的数据");
                return baseResponse;
            }

            if (isNew) { // 新增
                riskLeclsConfDto.setCreateBy(userId);
            } else {
                riskLeclsConfDto.setUpdateBy(userId);
            }
            editList.add(riskLeclsConfDto);
        }

//        for(TSafeRiskLeclsConfDTO conf : editList) {
//            riskLeclsConfRepo.u
//        }
        List<TSafeRiskLeclsConfDTO> resultList = riskLeclsConfRepo.saveOrUpdateBatch(editList);
        if(resultList == null) {
            baseResponse.setCode(BaseStatusEnum.UNKNOWN.code());
            baseResponse.setMsg("编辑失败");
            return baseResponse;
        }
        baseResponse.setData(resultList);
        return baseResponse;
    }

    public TSafeRiskLeclsConfDTO findById(String id){
        return riskLeclsConfRepo.findById(id);
    }

    /**
     * 检测 编码 是否都唯一
     * @return true - 唯一； false - 不唯一
     */
    public boolean checkUniqueness(String leclsConfId, Integer type, String code){
        List<TSafeRiskLeclsConfDTO> confDTOList = riskLeclsConfRepo.checkUniqueness(leclsConfId, type, code);
        if(confDTOList == null || confDTOList.size() == 0) {
            return true;
        }
        return false;
    }

    /**
     * @param riskLeclsRelationDtoList
     * @return
     */
    public BaseResponse<List<TSafeRiskLeclsRelationDTO>> editRiskLeclsRelation(String userId, List<TSafeRiskLeclsRelationDTO> riskLeclsRelationDtoList) {
        BaseResponse baseResponse = new BaseResponse<>();

        if(riskLeclsRelationDtoList == null || riskLeclsRelationDtoList.size() == 0) {
            baseResponse.setCode(BaseStatusEnum.UNKNOWN.code());
            baseResponse.setMsg("参数缺失");
            return baseResponse;
        }

        boolean isNew =  StrUtil.isBlank(riskLeclsRelationDtoList.get(0).getId());

        List<TSafeRiskLeclsRelationDTO> editList = new ArrayList<>();
        for(TSafeRiskLeclsRelationDTO riskLeclsRelationDto : riskLeclsRelationDtoList) {

            if(riskLeclsRelationDto.getMinValue() != null && riskLeclsRelationDto.getMaxValue() != null
                    && riskLeclsRelationDto.getMinValue() > riskLeclsRelationDto.getMaxValue()){
                baseResponse.setCode(BaseStatusEnum.UNKNOWN.code());
                baseResponse.setMsg("范围值错误");
                return baseResponse;
            }

            String formulaStr = generateFormulaStr(riskLeclsRelationDto);
            riskLeclsRelationDto.setFormulaStr(formulaStr);
            if (isNew) { // 新增
                riskLeclsRelationDto.setCreateBy(userId);
            } else {
                riskLeclsRelationDto.setUpdateBy(userId);
            }
            editList.add(riskLeclsRelationDto);
        }

        List<TSafeRiskLeclsRelationDTO> resultList = riskLeclsRelationRepo.saveOrUpdateBatch(editList);
        if(resultList == null) {
            baseResponse.setCode(BaseStatusEnum.UNKNOWN.code());
            baseResponse.setMsg("编辑失败");
            return baseResponse;
        }
        baseResponse.setData(resultList);
        return baseResponse;
    }

    public TSafeRiskLeclsRelationDTO findRelationById(String id){
        return riskLeclsRelationRepo.findById(id);
    }

    /**
     * 组装表达式
     * @param leclsRelationDTO
     */
    private String generateFormulaStr(TSafeRiskLeclsRelationDTO leclsRelationDTO) {
        if(leclsRelationDTO.getValueType() != 1) { // 1-采用范围值，2-采用具体值 非范围值 不组装表达式
            return null;
        }

        StringBuilder formulaStr = new StringBuilder();
        Float minVal = leclsRelationDTO.getMinValue();
        String isIncMin = leclsRelationDTO.getIsIncludeMin();
        Float maxVal = leclsRelationDTO.getMaxValue();
        String isIncMax = leclsRelationDTO.getIsIncludeMax();

        if(minVal != null) {
            formulaStr.append(minVal);
            if("0".equals(isIncMin)) {
                formulaStr.append("<");
            } else {
                formulaStr.append("<=");
            }
            formulaStr.append("param");
        }

        if(minVal != null && maxVal != null) {
            formulaStr.append(" && ");
        }

        if(maxVal != null) {
            formulaStr.append("param");
            if("0".equals(isIncMax)) {
                formulaStr.append("<");
            } else {
                formulaStr.append("<=");
            }
            formulaStr.append(maxVal);
        }

        return formulaStr.toString();
    }
}
