package com.sw.mes.yb.scheduled;

import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.core.enums.SectionIndexRangeEnum;
import com.sw.mes.yb.check.entity.PieceCheck;
import com.sw.mes.yb.check.entity.ZhxxOperatePieceCheck;
import com.sw.mes.yb.check.entity.vo.PieceCheckLife;
import com.sw.mes.yb.check.service.PieceCheckService;
import com.sw.mes.yb.check.service.UpdateService;
import com.sw.mes.yb.check.service.ZhxxOperatePieceCheckService;
import com.sw.mes.yb.pad.dao.PieceDetailDao;
import com.sw.mes.yb.pad.entity.PieceDetail;
import com.sw.mes.yb.production.dao.LongCrystalDao;
import com.sw.mes.yb.production.entity.LongCrystal;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @zhaoyayun
 * @20231101
 * @v1.0.0
 **/
@Slf4j
@Component
public class PieceCheckAutoGetScheduling {

    @Autowired
    ZhxxOperatePieceCheckService zhxxOperatePieceCheckService;

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @Autowired
    private PieceDetailDao pieceDetailDao;

    @Autowired
    private PieceCheckService pieceCheckService;

    @Autowired
    LongCrystalDao longCrystalDao;

    @Autowired
    private UpdateService updateService;


    /**
     * 定时从中间表拉取样片检验数据
     */
    @XxlJob("autoCheckYbPiece")
    public void autoGetYbPieceCheck(){

        log.info("样片自动拉取");

        //先从样片数据中间表拉取没有拉取过的记录
        List<ZhxxOperatePieceCheck> zhxxOperatePieceChecks = zhxxOperatePieceCheckService.pullAllNewRecord();
        List<ZhxxOperatePieceCheck> zhxxOperatePieceChecksGroup = zhxxOperatePieceCheckService.pullAllNewRecordGroupByPieceNo();
        if (null != zhxxOperatePieceChecksGroup && !CollectionUtils.isEmpty(zhxxOperatePieceChecksGroup)){
            createLifeTime(zhxxOperatePieceChecksGroup);
        }
        if (null != zhxxOperatePieceChecks && !CollectionUtils.isEmpty(zhxxOperatePieceChecks)){
            List<Long> ids = zhxxOperatePieceChecks.stream().map(t -> t.getId()).collect(Collectors.toList());
            //将中间表状态回写为已拉取
            zhxxOperatePieceCheckService.updateStateForPieceBatch(ids);
            log.info("更新中间表的ids:"+ids.toString());
        }
    }


    private void createLifeTime(List<ZhxxOperatePieceCheck> zhxxOperatePieceChecks){

        try {
            //组装批量插入样片数据的集合
//            List<Long> ids = new ArrayList<>();
            List<PieceCheck> pieceChecks = new ArrayList<>();

            for (ZhxxOperatePieceCheck zhxxOperatePieceCheck : zhxxOperatePieceChecks) {
                PieceCheckLife pieceCheckLife = modelMapper.map(zhxxOperatePieceCheck, PieceCheckLife.class);
                pieceCheckLife.setRemark2(zhxxOperatePieceCheck.getRemark());
                pieceCheckLife.setUserName2(zhxxOperatePieceCheck.getUserName());

                List<PieceDetail> pieceMaterialDetails = this.pieceDetailDao.findByPieceNo(pieceCheckLife.getPieceNo());
                if (pieceMaterialDetails == null || pieceMaterialDetails.size() <= 0) {
//                    throw new RuntimeException("样片编号不存在:"+pieceCheckLife.getPieceNo());
                    continue;
                }

                PieceCheck pieceCheck = pieceCheckService.getByPieceNo(pieceCheckLife.getPieceNo());
                if (pieceCheck == null) {
                    pieceCheck = new PieceCheck();
                    pieceCheck.setPieceNo(pieceCheckLife.getPieceNo());
                    LongCrystal sectionDetail = this.longCrystalDao.findByPieceNo(pieceCheckLife.getPieceNo());
                    if (sectionDetail != null) {
                        pieceCheck.setDeviceNo(sectionDetail.getEquipmentCode());
                        pieceCheck.setLotNo(sectionDetail.getLotNo());
                        pieceCheck.setMotherCrystalNo(sectionDetail.getCrystalNo());
                    }
                }
                if (pieceCheck.getcContents() != null || pieceCheck.getoContents() != null) {
//                    throw new RuntimeException("此样片碳氧含量已经录入，不可重复录入！:"+pieceCheckLife.getPieceNo());
                    continue;
                }
                pieceCheck.setcContents(pieceCheckLife.getcContents());
                pieceCheck.setoContents(pieceCheckLife.getoContents());
                pieceCheck.setUserName2(pieceCheckLife.getUserName2());
                pieceCheck.setRemark2(pieceCheckLife.getRemark2());
                pieceCheck.setThickness(pieceCheckLife.getThickness());
                pieceCheck.setCheckTime2(new Date());
                pieceCheck.setWorkshop(pieceCheckLife.getWorkshop());
                pieceChecks.add(pieceCheck);
            }

            List<String> pieceNos = new ArrayList<>();
            if (pieceChecks.size() > 0) {
                pieceCheckService.saveOrUpdateInBatch(pieceChecks, "样片检验-新增");
                for (PieceCheck pieceCheck : pieceChecks) {
                    // 同步更新晶段检验样片信息
                    pieceCheckService.saveInspectDataBaseInfo(pieceCheck.getPieceNo());
                    String fromMark = pieceCheck.getPieceNo().substring(SectionIndexRangeEnum.追溯标识.getBeginIndex(), SectionIndexRangeEnum.追溯标识.getEndIndex());
                    if (fromMark.matches("[A-Z]+")) {
                        pieceNos.add(pieceCheck.getPieceNo().substring(SectionIndexRangeEnum.毛棒范围.getBeginIndex(),SectionIndexRangeEnum.毛棒范围.getEndIndex()));
                    }else {
                        pieceNos.add(pieceCheck.getPieceNo().substring(0, 11));
                    }
                }
            }
            updateService.updates(pieceNos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
