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

import cn.estsh.i3plus.ext.mes.api.base.ISxKpsnRuleService;
import cn.estsh.i3plus.ext.mes.api.base.bu.IPartDataExtService;
import cn.estsh.i3plus.ext.mes.api.busi.bu.IBuRecordChangeDataService;
import cn.estsh.i3plus.ext.mes.pojo.model.bu.BuKpsnRuleModel;
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.TimeTool;
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.mes.bean.MesKpsnRule;
import cn.estsh.i3plus.pojo.mes.bean.MesPart;
import cn.estsh.i3plus.pojo.mes.repository.MesKpsnRuleRepository;
import cn.estsh.i3plus.pojo.mes.sqlpack.MesHqlPack;
import cn.estsh.impp.framework.boot.exception.ImppExceptionBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

    @Autowired
    private MesKpsnRuleRepository kpsnRuleRepository;

    @Autowired
    private IPartDataExtService partService;

    @Autowired
    private IBuRecordChangeDataService recordChangeDataService;

    @Override
    public ListPager<MesKpsnRule> queryKpsnRuleByPager(MesKpsnRule kpsnRule, Pager pager) {
        DdlPackBean hqlPack = MesHqlPack.getMesKpsnRule(kpsnRule, kpsnRule.getOrganizeCode());
        pager = PagerHelper.getPager(pager, kpsnRuleRepository.findByHqlWhereCount(hqlPack));
        hqlPack.setOrderByStr(kpsnRule.orderBy());
        return new ListPager(kpsnRuleRepository.findByHqlWherePage(hqlPack, pager), pager);
    }

    @Override
    public MesKpsnRule insertKpsnRule(MesKpsnRule kpsnRule) {
        MesKpsnRule kpsnRuleDb = kpsnRuleRepository.getByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.IS_DELETED, MesExtConstWords.IS_VALID, MesExtConstWords.PART_NO},
                new Object[]{kpsnRule.getOrganizeCode(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue(), CommonEnumUtil.IS_VAILD.VAILD.getValue(), kpsnRule.getPartNo()});
        if (null != kpsnRuleDb) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_EXIT.getCode())
                    .setErrorDetail("物料代码[%s]的记录已存在", kpsnRule.getPartNo())
                    .build();
        }

        ConvertBean.serviceModelInitialize(kpsnRule, kpsnRule.getCreateUser());
        return kpsnRuleRepository.insert(kpsnRule);
    }

    @Override
    public MesKpsnRule updateKpsnRule(MesKpsnRule kpsnRule) {
        //对id做有效性校验
        MesKpsnRule kpsnRuleDb = kpsnRuleRepository.getById(kpsnRule.getId());
        if (null == kpsnRuleDb) {
            throw ImppExceptionBuilder.newInstance()
                    .setSystemID(CommonEnumUtil.SOFT_TYPE.MES.getCode())
                    .setErrorCode(ImppExceptionEnum.VARIFY_EXCEPTION_DATA_NOT_EXIT.getCode())
                    .setErrorDetail("ID[%s]记录不存在", kpsnRule.getId())
                    .build();
        }

        ConvertBean.serviceModelUpdate(kpsnRuleDb, kpsnRule.getModifyUser());
        //新增关键件规则字段变更履历
        doRecordChangeData(getModel(kpsnRuleDb), getModel(kpsnRule), BuKpsnRuleModel.class);
        BeanUtils.copyProperties(kpsnRule, kpsnRuleDb, MesExtConstWords.MODIFY_DATE_TIME, MesExtConstWords.MODIFY_USER);
        return kpsnRuleRepository.save(kpsnRuleDb);
    }

    @Override
    public int updateKpsnRuleValidById(Long id, 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();
        }
        return kpsnRuleRepository.updateByProperties(new String[]{MesExtConstWords.ID}, new Object[]{id},
                new String[]{MesExtConstWords.IS_VALID, MesExtConstWords.MODIFY_USER, MesExtConstWords.MODIFY_DATE_TIME},
                new Object[]{status, userName, TimeTool.getNowTime(true)});
    }

    private BuKpsnRuleModel getModel(MesKpsnRule kpsnRule){
        BuKpsnRuleModel kpsnRuleModel = new BuKpsnRuleModel();
        BeanUtils.copyProperties(kpsnRule, kpsnRuleModel);
        kpsnRuleModel.setIsDeletedName(CommonEnumUtil.TRUE_OR_FALSE.valueOf(kpsnRuleModel.getIsDeleted()));
        kpsnRuleModel.setIsValidName(MesExtEnumUtil.IS_VAILD.valueOfDescription(kpsnRuleModel.getIsValid()));
        return kpsnRuleModel;
    }

    /**
     * 表字段修改记录
     * @param sourceData 源数据
     * @param newData 新数据
     * @param clazz 反射类
     */
    private void doRecordChangeData(BuKpsnRuleModel sourceData, BuKpsnRuleModel newData, Class clazz){
        MesPart mesPart = partService.getMesPart(sourceData.getOrganizeCode(), sourceData.getPartNo());
        recordChangeDataService.doRecordChangeData(MesExtEnumUtil.FIELD_MENU_TYPE.KPSN_RULE.getValue(), sourceData, newData, clazz, sourceData.getPartNo(), mesPart != null ? mesPart.getPartName() : "", sourceData.getOrganizeCode(), sourceData.getModifyDatetime());
    }

}
