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.pojo.bean.MesPartCategoryPlanRate;
import cn.estsh.i3plus.ext.mes.pojo.repository.MesPartCategoryPlanRateRepository;
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.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;
import java.util.stream.Collectors;

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

    @Autowired
    private MesPartCategoryPlanRateRepository partCategoryPlanRateRepository;

    @Override
    public ListPager<MesPartCategoryPlanRate> queryPartCategoryPlanRateByPager(MesPartCategoryPlanRate partCategoryPlanRate, Pager pager) {
        DdlPackBean hqlPack = MesExtHqlPack.getPartCategoryPlanRate(partCategoryPlanRate);
        pager = PagerHelper.getPager(pager, partCategoryPlanRateRepository.findByHqlWhereCount(hqlPack));
        hqlPack.setOrderByStr(partCategoryPlanRate.orderBy());
        List<MesPartCategoryPlanRate> partCategoryPlanRateList = partCategoryPlanRateRepository.findByHqlWherePage(hqlPack, pager);
        return new ListPager(partCategoryPlanRateList, pager);
    }

    @Override
    public List<MesPartCategoryPlanRate> queryPartCategoryPlanRateList(MesPartCategoryPlanRate partCategoryPlanRate) {
        DdlPackBean hqlPack = MesExtHqlPack.getPartCategoryPlanRate(partCategoryPlanRate);
        hqlPack.setOrderByStr(" order by createDatetime asc ");
        return partCategoryPlanRateRepository.findByHqlWhere(hqlPack);
    }

    @Override
    public List<MesPartCategoryPlanRate> queryAllPartCategoryPlanRateList(String organizeCode) {
        return partCategoryPlanRateRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue()});
    }

    @Override
    public Boolean checkPartCategoryPlanRateIsExist(String organizeCode, String categoryCode) {
        MesPartCategoryPlanRate categoryPlanRate = partCategoryPlanRateRepository.getByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.CATEGORY_CODE},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue(), categoryCode});

        if(categoryPlanRate == null){
            return false;
        }else{
            return true;
        }

    }

    @Override
    public MesPartCategoryPlanRate insertPartCategoryPlanRate(MesPartCategoryPlanRate partCategoryPlanRate) {
        checkPlanRate(partCategoryPlanRate);
        MesPartCategoryPlanRate partCategoryPlanRateDb = partCategoryPlanRateRepository.getByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.CATEGORY_CODE},
                new Object[]{partCategoryPlanRate.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), partCategoryPlanRate.getCategoryCode()});
        if (null != partCategoryPlanRateDb && CommonEnumUtil.IS_VAILD.VAILD.getValue() == partCategoryPlanRateDb.getIsValid())
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("产品类别计划比例产品类别代码[%s]记录已存在", partCategoryPlanRate.getCategoryCode())
                    .build();
        if (null == partCategoryPlanRateDb) partCategoryPlanRateDb = new MesPartCategoryPlanRate();
        partCategoryPlanRateDb.setCategoryCode(partCategoryPlanRate.getCategoryCode());
        partCategoryPlanRateDb.setCategoryName(partCategoryPlanRate.getCategoryName());
        partCategoryPlanRateDb.setPlanRate(partCategoryPlanRate.getPlanRate());
        partCategoryPlanRateDb.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        if (StringUtils.isEmpty(partCategoryPlanRateDb.getId())) {
            partCategoryPlanRateDb.setOrganizeCode(partCategoryPlanRate.getOrganizeCode());
            ConvertBean.serviceModelInitialize(partCategoryPlanRateDb, partCategoryPlanRate.getCreateUser());
            partCategoryPlanRateDb = partCategoryPlanRateRepository.insert(partCategoryPlanRateDb);
        } else {
            partCategoryPlanRateDb.setIsValid(CommonEnumUtil.IS_VAILD.VAILD.getValue());
            ConvertBean.serviceModelUpdate(partCategoryPlanRateDb, partCategoryPlanRate.getCreateUser());
            partCategoryPlanRateDb = partCategoryPlanRateRepository.save(partCategoryPlanRateDb);
        }
        return partCategoryPlanRateDb;
    }

    private void checkPlanRate(MesPartCategoryPlanRate partCategoryPlanRate) {
        try {
            if (MathOperation.compareTo(Double.parseDouble(partCategoryPlanRate.getPlanRate()), new Double(0)) < 0)
                throw ImppExceptionBuilder.newInstance()
                        .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                        .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                        .setErrorDetail("产品类别计划比例[%s]必须是正数,最多四位小数", partCategoryPlanRate.getPlanRate())
                        .build();
        } catch (NumberFormatException e) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION.getCode())
                    .setErrorDetail("产品类别计划比例[%s]格式错误,必须是正数,最多四位小数", partCategoryPlanRate.getPlanRate())
                    .build();
        }
        String[] remainArr = partCategoryPlanRate.getPlanRate().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]必须是正数,最多4位小数", partCategoryPlanRate.getPlanRate())
                    .build();
    }

    @Override
    public MesPartCategoryPlanRate updatePartCategoryPlanRate(MesPartCategoryPlanRate partCategoryPlanRate) {
        checkPlanRate(partCategoryPlanRate);
        MesPartCategoryPlanRate partCategoryPlanRateDb = partCategoryPlanRateRepository.getById(Long.parseLong(partCategoryPlanRate.getIdStr()));
        if (null == partCategoryPlanRateDb)
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("产品类别计划比例ID[%s]记录不存在", partCategoryPlanRate.getIdStr())
                    .build();
        partCategoryPlanRateDb.setCategoryName(partCategoryPlanRate.getCategoryName());
        partCategoryPlanRateDb.setPlanRate(partCategoryPlanRate.getPlanRate());
        partCategoryPlanRateDb.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        partCategoryPlanRateDb.setIsValid(CommonEnumUtil.IS_VAILD.VAILD.getValue());
        ConvertBean.serviceModelUpdate(partCategoryPlanRateDb, partCategoryPlanRate.getModifyUser());
        return partCategoryPlanRateRepository.save(partCategoryPlanRateDb);
    }

    @Override
    public void updatePartCategoryPlanRateValidById(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();
        }
        MesPartCategoryPlanRate partCategoryPlanRateDb = partCategoryPlanRateRepository.getById(Long.parseLong(idStr));
        if (null == partCategoryPlanRateDb)
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("产品类别计划比例ID[%s]对应的记录不存在", idStr)
                    .build();
        partCategoryPlanRateDb.setIsValid(status);
        partCategoryPlanRateDb.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        ConvertBean.serviceModelUpdate(partCategoryPlanRateDb, userName);
        partCategoryPlanRateRepository.save(partCategoryPlanRateDb);
    }

    @Override
    public void deletePartCategoryPlanRateById(String idStr, String userName) {
        MesPartCategoryPlanRate partCategoryPlanRateDb = partCategoryPlanRateRepository.getById(Long.parseLong(idStr));
        if (null == partCategoryPlanRateDb)
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("产品类别计划比例ID[%s]对应的记录不存在", idStr)
                    .build();
        partCategoryPlanRateDb.setIsDeleted(CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue());
        partCategoryPlanRateDb.setSystemSyncStatus(MesExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        ConvertBean.serviceModelUpdate(partCategoryPlanRateDb, userName);
        partCategoryPlanRateRepository.save(partCategoryPlanRateDb);
    }

    @Override
    public List<MesPartCategoryPlanRate> getPartCategoryPlanRateAllList(String organizeCode) {
        return partCategoryPlanRateRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});
    }

    @Override
    public List<MesPartCategoryPlanRate> getPartCategoryPlanRateList(String organizeCode) {
        return partCategoryPlanRateRepository.findByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID},
                new Object[]{organizeCode, CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue()});
    }

    @Override
    public Map<String, String> getCategoryMap(String organizeCode) {
        List<MesPartCategoryPlanRate> partCategoryPlanRateList = getPartCategoryPlanRateList(organizeCode);
        partCategoryPlanRateList = CollectionUtils.isEmpty(partCategoryPlanRateList) ? null :
                partCategoryPlanRateList.stream().filter(o -> !StringUtils.isEmpty(o.getCategoryCode()) && !StringUtils.isEmpty(o.getCategoryName())).collect(Collectors.toList());
        return CollectionUtils.isEmpty(partCategoryPlanRateList) ? null :
                partCategoryPlanRateList.stream().filter(o -> null != o).collect(Collectors.toMap(MesPartCategoryPlanRate::getCategoryCode, MesPartCategoryPlanRate::getCategoryName));
    }
}
