package com.sw.mes.yb.scheduled;

import com.sw.mes.base.factory.init.service.EquipmentHistoryService;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.core.utils.DateUtil;
import com.sw.mes.yb.fls.dto.BracketNoToFlsDto;
import com.sw.mes.yb.fls.dto.SectionRecycledResultDto;
import com.sw.mes.yb.fls.dto.SectionRequestDto;
import com.sw.mes.yb.fls.entity.RecycledWaitRecord;
import com.sw.mes.yb.fls.service.MesToFlsService;
import com.sw.mes.yb.fls.utils.FlsResultDto;
import com.sw.mes.yb.pad.service.RecycledWaitRecordService;
import com.sw.mes.yb.pc.service.EstimatedRecordService;
import com.sw.mes.yb.pc.service.HeadTailMaterialRuleService;
import com.sw.mes.yb.plan.service.ProductionScheduleService;
import com.sw.mes.yb.seed.entity.SeedRequireTask;
import com.sw.mes.yb.seed.service.SeedRequireTaskService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;

@Slf4j
@Component("YbAutoScheduling")
//@Configuration
//@EnableScheduling
//@ConditionalOnProperty(prefix = "scheduling", name = "enabled", havingValue = "true")
public class YbAutoScheduling {

    @Autowired
    private ProductionScheduleService productionScheduleService;
    @Autowired
    private MesToFlsService mesToFlsService;
    @Autowired
    private RecycledWaitRecordService recycledWaitRecordService;
    @Autowired
    private HeadTailMaterialRuleService headTailMaterialRuleService;

    @Autowired
    EstimatedRecordService estimatedRecordService;

    @Autowired
    private EquipmentHistoryService equipmentHistoryService;

    @Autowired
    private SeedRequireTaskService seedRequireTaskService;
    @Value("${spring.profiles.active}")
    private String active;

    /**
     * 定时调用消费数据方法
     */
//    @Scheduled(cron = "*/10 * * * * ?")
    @XxlJob("demoJobHandler")
    public void consumptionCutData() {
        String dateStr = DateUtil.formatDate(new Date(), "yyyyMMddHHmmss");
        log.info("【开始自动排程】QF" + dateStr + " * * * * * * * * * * *");
        Long start = System.currentTimeMillis();
        productionScheduleService.autoScheduling();
        Long end = System.currentTimeMillis();
        log.info("【本次自动排程耗时（" + (end - start) + "）毫秒】QF" + dateStr + " * * * * * * * * * * *");
    }

    /**
     * 头尾料自动匹配点位发送fls
     */
    @XxlJob("bracketNoJobHandler")
    public void synBracketNoJobHandler() {
        log.info("准备发送回收料点位到fls！");
        if (!active.equals("prod")) {
            log.info("非生产环境!回收料点位不与fls交互!");
        } else {

            List<RecycledWaitRecord> list = recycledWaitRecordService.getListByStatusAndMaterialType(1, "回收料");
            for (RecycledWaitRecord record : list
            ) {
                BracketNoToFlsDto bracketNoToFlsDto = new BracketNoToFlsDto();
                bracketNoToFlsDto.setMode("HeadTailInfoDownLoad");
                bracketNoToFlsDto.setSectionNo(record.getSectionNo());

                //查询圆棒检验数据库
                SectionRequestDto sectionRequestDto = new SectionRequestDto();
                sectionRequestDto.setSectionNo(record.getSectionNo());
                sectionRequestDto.setLine("1");
                sectionRequestDto.setRegionCode("1");
                //T/W结尾的头尾回收料需要重新定位相近的晶段数据
                if (record.getSectionNo().endsWith("T") || record.getSectionNo().endsWith("W")) {
                    String likeSectionNo = "";
                    // String likeSectionNo = headTailMaterialRuleService.findHeadTailMaterialByRecoveryNo(record.getSectionNo());
                    if (record.getSectionNo().endsWith("T")) {
                        likeSectionNo = record.getSectionNo().substring(0, record.getSectionNo().length() - 1) + "1Y";
                    } else if (record.getSectionNo().endsWith("W")) {
                        likeSectionNo = record.getSectionNo() + "Y";
                    }
                    sectionRequestDto.setSectionNo(likeSectionNo);
                }
                SectionRecycledResultDto headTailMaterialRuleBySection = null;
                try {
                    List<SectionRecycledResultDto> recycledResultDtoList = headTailMaterialRuleService.findHeadTailMaterialRuleBySection(sectionRequestDto);
                    if (!CollectionUtils.isEmpty(recycledResultDtoList)) {
                        headTailMaterialRuleBySection = recycledResultDtoList.get(0);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                if (null != headTailMaterialRuleBySection) {
                    bracketNoToFlsDto.setBracketNo(headTailMaterialRuleBySection.getBracketNo());
                    bracketNoToFlsDto.setRecoveryName("回收料" + headTailMaterialRuleBySection.getRecoveryName());
                    FlsResultDto resultDto = mesToFlsService.sendSectionForInfo(bracketNoToFlsDto);
                    if (resultDto == null || resultDto.getCode() == null || resultDto.getCode() != 0) {
                        throw new RuntimeException("发送回收料点位到fls失败:" + resultDto.getMessage());
                    } else {
                        //更新晶棒检验后数据已发送点位到fls的状态
                        record.setStatus(2);
                        recycledWaitRecordService.update(record);
                    }
                }
            }
        }

    }

    @XxlJob("estimatedJobHandler")
    public void deleteEstimated() {
        String dateStr = DateUtil.formatDate(new Date(), "yyyyMMddHHmmss");
        log.info("【开始处理预取棒数据时间】" + dateStr + " * * * * * * * * * * *");
        Long start = System.currentTimeMillis();
        Date halfHour = DateUtil.addMinute(new Date(), -30);
        estimatedRecordService.deleteBeforeHalfHourEstimatedRecord(halfHour,new Date());
        Long end = System.currentTimeMillis();
        log.info("【本次处理预取棒数据耗时（" + (end - start) + "）毫秒】" + dateStr + " * * * * * * * * * * *");
    }
    @XxlJob("insertEquipmentHistoryJobHandler")
    public void insertEquipmentHistory(){
        equipmentHistoryService.insertEquipmentHistory();
    }

    @XxlJob("updateSeedRequireTaskJobHandler")
    public void updateSeedRequireTaskJobHandler(){
        List<SeedRequireTask> seedRequireTasks = seedRequireTaskService.findSeedRequireTask();
        if (!CollectionUtils.isEmpty(seedRequireTasks)) {
            seedRequireTasks.forEach(entity->{
                entity.setDel(true);
                seedRequireTaskService.saveOrUpdate(entity);
            });
        }
    }
}
