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

import cn.estsh.i3plus.ext.mes.api.busi.ISxDeleteTravelDataService;
import cn.estsh.i3plus.ext.mes.api.busi.IWorkOrderLogExtService;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtConstWords;
import cn.estsh.i3plus.ext.mes.pojo.util.MesExtEnumUtil;
import cn.estsh.i3plus.platform.common.tool.TimeTool;
import cn.estsh.i3plus.pojo.base.enumutil.CommonEnumUtil;
import cn.estsh.i3plus.pojo.mes.bean.MesConfig;
import cn.estsh.i3plus.pojo.mes.repository.MesConfigRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @PROJECT_NAME: i3plus-mes-panasonic-bu
 * @DESCRIPTION: 删除履历数据记录JOB
 * @USER: xinwang.yi
 * @DATE: 2022-11-11 9:45
 */
@Slf4j
@Service
public class SxDeleteTravelDataService implements ISxDeleteTravelDataService {

    @Autowired
    private IWorkOrderLogExtService workOrderLogExtService;

    @Autowired
    private MesConfigRepository configRepository;

    //MES_CONFIG 表中配置时间点，删除从该时间节点往前推移两个月的数据（仅删除已完成和已删除的工单关联日志）
    public static final String DELETE_TIME_POINT = "DELETE_TIME_POINT";

    @Override
    public void doDeleteTravelData(String organizeCode) {

        String nowTime = getDeleteTime(organizeCode);
        //删除小于指定时间的数据
        String modifyDatetime = TimeTool.timeCalc(TimeTool.stringParseToDate(nowTime, MesExtConstWords.DATETIME_FORMAT), Calendar.MONTH, -2, MesExtConstWords.DATETIME_FORMAT);

        log.info(" doDeleteTravelData modifyDatetime :{}", modifyDatetime);

        //删除工单日志
        workOrderLogExtService.doDeleteWorkOrderLogExt(organizeCode, Stream.of(MesExtEnumUtil.WORK_ORDER_STATUS.CLOSE.getValue(), MesExtEnumUtil.WORK_ORDER_STATUS.REMOVE.getValue()).collect(Collectors.toList()), modifyDatetime);
    }

    private String getDeleteTime(String organizeCode){
        MesConfig timeConfig = configRepository.getByProperty(
                new String[]{MesExtConstWords.ORGANIZE_CODE, MesExtConstWords.CFG_CODE ,MesExtConstWords.IS_VALID, MesExtConstWords.IS_DELETED},
                new Object[]{organizeCode, DELETE_TIME_POINT, CommonEnumUtil.TRUE_OR_FALSE.TRUE.getValue(), CommonEnumUtil.TRUE_OR_FALSE.FALSE.getValue()});

        if((timeConfig != null) && (!StringUtils.isEmpty(timeConfig.getCfgValue()))){
            log.info("getDeleteTime --- MesConfig ---{}" ,timeConfig);
            if(!TimeTool.checkDateFormat(timeConfig.getCfgValue(), MesExtConstWords.DATETIME_FORMAT)) {
                log.info("删除履历数据记录 --- getDeleteTime --- 时间点格式无效");
                return "2020-01-01 00:00:00";
            }
            return timeConfig.getCfgValue();
        }
        return TimeTool.getNowTime(MesExtConstWords.DATETIME_FORMAT);
    }

}
