package cn.estsh.i3plus.ext.mes.pcn.apiservice.serviceimpl.busi.collect;

import cn.estsh.i3plus.ext.mes.pcn.api.busi.ISxThirdPartyDbCollectDataRecordService;
import cn.estsh.i3plus.ext.mes.pcn.pojo.bean.MesThirdPartyDbCollectDataRecord;
import cn.estsh.i3plus.ext.mes.pcn.pojo.repository.MesThirdPartyDbCollectDataRecordRepository;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtConstWords;
import cn.estsh.i3plus.ext.mes.pcn.pojo.util.MesPcnExtEnumUtil;
import cn.estsh.i3plus.platform.common.convert.ConvertBean;
import cn.estsh.i3plus.pojo.base.bean.DdlPackBean;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.base.tool.DdlPreparedPack;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Slf4j
@Service
public class SxThirdPartyDbCollectDataRecordService implements ISxThirdPartyDbCollectDataRecordService {

    @Autowired
    private MesThirdPartyDbCollectDataRecordRepository thirdPartyDbCollectDataRecordRepository;

    @Override
    public void exec(String organizeCode, String userInfo, MesThirdPartyDbCollectDataRecord record) {

        if (repeatCheck(organizeCode, record)) return;

        record.setOrganizeCode(organizeCode);
        record.setSystemSyncStatus(MesPcnExtEnumUtil.IF_SYNC_STATUS.NO_SYNC.getValue());
        ConvertBean.serviceModelInitialize(record, userInfo);
        thirdPartyDbCollectDataRecordRepository.insert(record);
    }

    private Boolean repeatCheck(String organizeCode, MesThirdPartyDbCollectDataRecord record) {
        if (CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue() == record.getResult()) return false;
        if (StringUtils.isEmpty(record.getMessage())) return true;
        DdlPackBean packBean = DdlPackBean.getDdlPackBean(organizeCode);
        DdlPreparedPack.getStringEqualPack(record.getCfgCode(), MesPcnExtConstWords.CFG_CODE, packBean);
        DdlPreparedPack.getStringEqualPack(record.getObjectCode(), MesPcnExtConstWords.OBJECT_CODE, packBean);
        DdlPreparedPack.getOrderByPack(new Object[]{CommonEnumUtil.ASC_OR_DESC.DESC.getValue()}, new String[]{MesPcnExtConstWords.CREATE_DATE_TIME}, packBean);
        MesThirdPartyDbCollectDataRecord recordDb = thirdPartyDbCollectDataRecordRepository.getByProperty(packBean);
        if (null == recordDb || (StringUtils.isEmpty(recordDb.getMessage()) || !recordDb.getMessage().equals(record.getMessage()))) return false;
        return true;
    }
}
