package cn.estsh.i3plus.ext.mes.apiservice.serviceimpl.base.bu3;

import cn.estsh.i3plus.ext.mes.api.base.bu3.ISxPartCategoryPlanRateService;
import cn.estsh.i3plus.ext.mes.api.base.bu3.ISxPartCategoryTargetCfgService;
import cn.estsh.i3plus.ext.mes.pojo.bean.MesPartCategoryTargetCfg;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesPartCategoryTargetCfgRepository;
import cn.estsh.i3plus.ext.mes.pojo.sqlpack.MesExtHqlPack;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.platform.common.exception.ImppExceptionEnum;
import cn.estsh.i3plus.platform.common.tool.MathOperation;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.bean.ListPager;
import cn.estsh.i3plus.pojo.base.common.Pager;
import cn.estsh.i3plus.pojo.base.common.PagerHelper;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

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

/**
 * @author wangjie
 * @version 1.0
 * @date 2021/1/13 9:28
 **/
@Slf4j
@Service
public class SxPartCategoryTargetCfgService implements ISxPartCategoryTargetCfgService {

    @Autowired
    private MesPartCategoryTargetCfgRepository partCategoryTargetCfgRepository;

    @Autowired
    private ISxPartCategoryPlanRateService partCategoryPlanRateService;

    @Override
    public ListPager<MesPartCategoryTargetCfg> queryPartCategoryTargetCfgByPager(MesPartCategoryTargetCfg partCategoryTargetCfg, Pager pager) {
        DdlPackBean hqlPack = MesExtHqlPack.getPartCategoryTargetCfg(partCategoryTargetCfg);
        pager = PagerHelper.getPager(pager, partCategoryTargetCfgRepository.findByHqlWhereCount(hqlPack));
        hqlPack.setOrderByStr(partCategoryTargetCfg.orderBy());
        List<MesPartCategoryTargetCfg> partCategoryTargetCfgList = partCategoryTargetCfgRepository.findByHqlWherePage(hqlPack, pager);
        if (!StringUtils.isEmpty(partCategoryTargetCfgList)) {
            Map<String, String> categoryMap = partCategoryPlanRateService.getCategoryMap(partCategoryTargetCfg.getOrganizeCode());
            for (MesPartCategoryTargetCfg item : partCategoryTargetCfgList) {
                if (null == item) continue;
                item.setCategoryName((!CollectionUtils.isEmpty(categoryMap) && categoryMap.containsKey(item.getCategoryCode())) ? categoryMap.get(item.getCategoryCode()) : null);
            }
        }
        return new ListPager(partCategoryTargetCfgList, pager);
    }

    @Override
    public MesPartCategoryTargetCfg insertPartCategoryTargetCfg(MesPartCategoryTargetCfg partCategoryTargetCfg) {
        checkValue(partCategoryTargetCfg.getCfgValue(), "目标");
        checkValue(partCategoryTargetCfg.getCfgValue2(), "ST能率目标");
        if (!StringUtils.isEmpty(partCategoryTargetCfg.getRate())) checkValue(partCategoryTargetCfg.getRate(), "比例");
        MesPartCategoryTargetCfg partCategoryTargetCfgDb = getPartCategoryTargetCfg(partCategoryTargetCfg.getOrganizeCode(), partCategoryTargetCfg.getCategoryCode(), partCategoryTargetCfg.getDataKey());
        if (null != partCategoryTargetCfgDb && CommonEnumUtil.IS_VAILD.VAILD.getValue() == partCategoryTargetCfgDb.getIsValid())
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("产品类别目标配置产品类别代码[%s]配置键[%s]记录已存在,操作失败", partCategoryTargetCfg.getCategoryCode(), partCategoryTargetCfg.getDataKey())
                    .build();
        if (null == partCategoryTargetCfgDb) partCategoryTargetCfgDb = new MesPartCategoryTargetCfg();
        partCategoryTargetCfgDb.setCategoryCode(partCategoryTargetCfg.getCategoryCode());
        partCategoryTargetCfgDb.setDataKey(partCategoryTargetCfg.getDataKey());
        partCategoryTargetCfgDb.setCfgValue(partCategoryTargetCfg.getCfgValue());
        partCategoryTargetCfgDb.setCfgValue2(partCategoryTargetCfg.getCfgValue2());
        partCategoryTargetCfgDb.setRate(partCategoryTargetCfg.getRate());
        partCategoryTargetCfgDb.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        if (StringUtils.isEmpty(partCategoryTargetCfgDb.getId())) {
            partCategoryTargetCfgDb.setOrganizeCode(partCategoryTargetCfg.getOrganizeCode());
            ConvertBean.serviceModelInitialize(partCategoryTargetCfgDb, partCategoryTargetCfg.getCreateUser());
            partCategoryTargetCfgDb = partCategoryTargetCfgRepository.insert(partCategoryTargetCfgDb);
        } else {
            partCategoryTargetCfgDb.setIsValid(CommonEnumUtil.IS_VAILD.VAILD.getValue());
            ConvertBean.serviceModelUpdate(partCategoryTargetCfgDb, partCategoryTargetCfg.getCreateUser());
            partCategoryTargetCfgDb = partCategoryTargetCfgRepository.save(partCategoryTargetCfgDb);
        }
        return partCategoryTargetCfgDb;
    }

    private MesPartCategoryTargetCfg getPartCategoryTargetCfg(String organizeCode, String categoryCode, String dataKey) {
        return partCategoryTargetCfgRepository.getByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.CATEGORY_CODE, MesExtConstWords.DATA_KEY},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), categoryCode, dataKey});
    }

    private void checkValue(String value, String name) {
        try {
            if (MathOperation.compareTo(Double.parseDouble(value), new Double(0)) < 0)
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("产品类别%s[%s]必须是正数,最多四位小数", name, value)
                        .build();
        } catch (NumberFormatException e) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("产品类别%s[%s]格式错误,必须是正数,最多四位小数", name, value)
                    .build();
        }
        String[] remainArr = value.split(MesExtConstWords.DECIMAL_POINT);
        if (remainArr.length == 2 && remainArr[1].length() > 4)
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("产品类别%s[%s]必须是正数,最多4位小数", name, value)
                    .build();
    }

    @Override
    public MesPartCategoryTargetCfg updatePartCategoryTargetCfg(MesPartCategoryTargetCfg partCategoryTargetCfg) {
        checkValue(partCategoryTargetCfg.getCfgValue(), "目标");
        checkValue(partCategoryTargetCfg.getCfgValue2(), "ST能率目标");
        if (!StringUtils.isEmpty(partCategoryTargetCfg.getRate())) checkValue(partCategoryTargetCfg.getRate(), "比例");
        MesPartCategoryTargetCfg partCategoryTargetCfgDb = partCategoryTargetCfgRepository.getById(Long.parseLong(partCategoryTargetCfg.getIdStr()));
        if (null == partCategoryTargetCfgDb)
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("产品类别目标配置ID[%s]记录不存在", partCategoryTargetCfg.getIdStr())
                    .build();
        MesPartCategoryTargetCfg partCategoryTargetCfgDbIsExist = getPartCategoryTargetCfg(partCategoryTargetCfg.getOrganizeCode(), partCategoryTargetCfg.getCategoryCode(), partCategoryTargetCfg.getDataKey());
        if (null != partCategoryTargetCfgDbIsExist && partCategoryTargetCfgDbIsExist.getId().compareTo(partCategoryTargetCfgDb.getId()) != 0) {
            if (CommonEnumUtil.IS_VAILD.VAILD.getValue() == partCategoryTargetCfgDb.getIsValid())
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                        .setErrorDetail("产品类别目标配置产品类别代码[%s]配置键[%s]记录已存在,操作失败", partCategoryTargetCfg.getCategoryCode(), partCategoryTargetCfg.getDataKey())
                        .build();
            else {
                partCategoryTargetCfgDbIsExist.setIsDeleted(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
                partCategoryTargetCfgDbIsExist.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
                ConvertBean.serviceModelUpdate(partCategoryTargetCfgDbIsExist, partCategoryTargetCfg.getModifyUser());
                partCategoryTargetCfgRepository.save(partCategoryTargetCfgDbIsExist);
            }
        }

        partCategoryTargetCfgDb.setCategoryCode(partCategoryTargetCfg.getCategoryCode());
        partCategoryTargetCfgDb.setDataKey(partCategoryTargetCfg.getDataKey());
        partCategoryTargetCfgDb.setCfgValue(partCategoryTargetCfg.getCfgValue());
        partCategoryTargetCfgDb.setCfgValue2(partCategoryTargetCfg.getCfgValue2());
        partCategoryTargetCfgDb.setRate(partCategoryTargetCfg.getRate());
        partCategoryTargetCfgDb.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        partCategoryTargetCfgDb.setIsValid(CommonEnumUtil.IS_VAILD.VAILD.getValue());
        ConvertBean.serviceModelUpdate(partCategoryTargetCfgDb, partCategoryTargetCfg.getModifyUser());
        return partCategoryTargetCfgRepository.save(partCategoryTargetCfgDb);
    }

    @Override
    public void updatePartCategoryTargetCfgValidById(String idStr, Integer status, String userName) {
        if (status != CommonEnumUtil.IS_VAILD.INVAILD.getValue() && status != CommonEnumUtil.IS_VAILD.VAILD.getValue()) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("启用，禁用枚举状态值【%s】未被定义", status)
                    .build();
        }
        MesPartCategoryTargetCfg partCategoryTargetCfgDb = partCategoryTargetCfgRepository.getById(Long.parseLong(idStr));
        if (null == partCategoryTargetCfgDb)
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("产品类别目标配置ID[%s]对应的记录不存在", idStr)
                    .build();
        partCategoryTargetCfgDb.setIsValid(status);
        partCategoryTargetCfgDb.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        ConvertBean.serviceModelUpdate(partCategoryTargetCfgDb, userName);
        partCategoryTargetCfgRepository.save(partCategoryTargetCfgDb);
    }

    @Override
    public void deletePartCategoryTargetCfgById(String idStr, String userName) {
        MesPartCategoryTargetCfg partCategoryTargetCfgDb = partCategoryTargetCfgRepository.getById(Long.parseLong(idStr));
        if (null == partCategoryTargetCfgDb)
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("产品类别目标配置ID[%s]对应的记录不存在", idStr)
                    .build();
        partCategoryTargetCfgDb.setIsDeleted(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
        partCategoryTargetCfgDb.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        ConvertBean.serviceModelUpdate(partCategoryTargetCfgDb, userName);
        partCategoryTargetCfgRepository.save(partCategoryTargetCfgDb);
    }

    @Override
    public List<MesPartCategoryTargetCfg> getPartCategoryTargetCfgList(String organizeCode, String categoryCode) {
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(categoryCode, MesExtConstWords.CATEGORY_CODE, packBean);
        return partCategoryTargetCfgRepository.findByHqlWhere(packBean);
    }

}
