package com.sw.mes.fb.aio.service.impl;


import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.utils.DateUtil;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.core.utils.ThreadManager;
import com.sw.mes.fb.aio.dao.EapGrindingMachineDao;
import com.sw.mes.fb.aio.dto.ProcessingMachineDto;
import com.sw.mes.fb.aio.entity.EapEvolutionBlanking;
import com.sw.mes.fb.aio.entity.EapEvolutionRecord;
import com.sw.mes.fb.aio.entity.EapGrindingMachine;
import com.sw.mes.fb.aio.entity.GrindingBlanking;
import com.sw.mes.fb.aio.service.EapEvolutionBlankingService;
import com.sw.mes.fb.aio.service.EapEvolutionRecordService;
import com.sw.mes.fb.aio.service.EapGrindingMachineService;
import com.sw.mes.fb.aio.service.GrindingBlankingService;
import com.sw.mes.base.workinprocess.dto.PlanProcessingOrderWipStorageDto;
import com.sw.mes.base.workinprocess.service.PlanProcessingOrderService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Service
@Transactional
public class EapGrindingMachineServiceImpl extends BaseServiceImpl<EapGrindingMachine> implements EapGrindingMachineService {
    EapGrindingMachineDao dao;

    @Autowired
    private EapEvolutionRecordService eapEvolutionRecordService;

    @Autowired
    private EapEvolutionBlankingService eapEvolutionBlankingService;

    @Autowired
    private GrindingBlankingService grindingBlankingService;

    @Autowired
    public void setDao(EapGrindingMachineDao dao) {
        super.setBaseDao(dao);
        this.dao = dao;
    }

    @Autowired
    private WipStorageService wipStorageService;
    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;

    @Override
    public void save(EapGrindingMachine eapGrindingMachine) {

        //异步执行站点变更
        ThreadManager.getThreadPollProxy().execute(() -> {
            // 查询加工工单信息，判断是否是本站点的加工品
            PlanProcessingOrderWipStorageDto planProcessingOrderWipStorageDto = wipStorageService.selectWipStorage(eapGrindingMachine.getSn(), EnumValuesFactory.WipStorageCode.开方.getKey(), false);
            planProcessingOrderWipStorageDto.getPlanProcessingOrder().setMaterialType(EnumValuesFactory.MaterialType.方棒.getKey());
            planProcessingOrderService.createPlanProcessingOrder(planProcessingOrderWipStorageDto.getPlanProcessingOrder(), null, null);
            wipStorageService.outStation(eapGrindingMachine.getSn(), null, EnumValuesFactory.WipStorageStatus.已进站.getKey());
        });
        eapGrindingMachine.setCreatedTime(new Date());
        saveOrUpdate(eapGrindingMachine);
    }

    @Override
    public String createOneBodyMachineCode(EapGrindingMachine eapGrindingMachine) {
        String oneBodyMachineCode = "";
        try{
            if (StringUtils.isNotEmpty(eapGrindingMachine.getSn())){
                //开方加工记录
                EapEvolutionRecord eapEvolutionRecord = eapEvolutionRecordService.findTopBySnOrderByIdDesc(eapGrindingMachine.getSn());
                if (eapEvolutionRecord != null){
                    Date date = eapEvolutionRecord.getEndTrimming() == null ? eapEvolutionRecord.getCreatedTime() : eapEvolutionRecord.getEndTrimming();
                    //方棒加工年月日
                    oneBodyMachineCode += DateUtil.formatDate(DateUtil.addHour(date,-9) ,"yyyyMMdd");
                    //切方加工班次
//                    String classNo = "";
//                    if (StringUtils.isNotBlank(eapEvolutionRecord.getClassNoName())){
//                        if("白班".equals(eapEvolutionRecord.getClassNoName()))
//                            classNo = "B";
//                        else if("夜班".equals(eapEvolutionRecord.getClassNoName()))
//                            classNo = "Y";
//                    }
//                    oneBodyMachineCode += "".equals(classNo) ? getClassNo(date) : classNo;
                    oneBodyMachineCode += getClassNo(date);
                    //切方操作工号
                    //oneBodyMachineCode += StringUtils.isEmpty(eapEvolutionRecord.getTrimmingMan()) || eapGrindingMachine.getGrindingMan().length() < 3 ? "000" :  eapEvolutionRecord.getTrimmingMan().substring(eapEvolutionRecord.getTrimmingMan().length()-3);
                    oneBodyMachineCode += StringUtils.isEmpty(eapEvolutionRecord.getTrimmingManCode()) ? "000" : eapEvolutionRecord.getTrimmingManCode();
                    //切方机台号
                    if (eapEvolutionRecord.getEquipNo() != null && eapEvolutionRecord.getEquipNo().length() >= 2) {
                        oneBodyMachineCode += eapEvolutionRecord.getEquipNo().substring(2);
                    }else{
                        oneBodyMachineCode += "000";
                    }
                    //开方下料记录
                    EapEvolutionBlanking eapEvolutionBlanking = eapEvolutionBlankingService.findTopBySnOrderByIdDesc(eapGrindingMachine.getSn());
                    if (eapEvolutionBlanking != null && eapEvolutionBlanking.getTrimmingOrder() != null ){
                        //切方当班加工第几颗
                        oneBodyMachineCode += String.format("%02d", Integer.parseInt(eapEvolutionBlanking.getTrimmingOrder()));
                    }else{
                        oneBodyMachineCode += "00";
                    }
                }else{
                    oneBodyMachineCode += "00000000000000000";
                }

                //磨削加工班次
//                String classNoMX = "";
//                if (StringUtils.isNotBlank(eapGrindingMachine.getClassNoName())){
//                    if("白班".equals(eapGrindingMachine.getClassNoName()))
//                        classNoMX = "B";
//                    else if("夜班".equals(eapGrindingMachine.getClassNoName()))
//                        classNoMX = "Y";
//                }
//                oneBodyMachineCode += "".equals(classNoMX) ? getClassNo(eapGrindingMachine.getEndGrinding() == null ? eapGrindingMachine.getCreatedTime() : eapGrindingMachine.getEndGrinding()) : classNoMX;
                oneBodyMachineCode += getClassNo(eapGrindingMachine.getEndGrinding() == null ? eapGrindingMachine.getCreatedTime() : eapGrindingMachine.getEndGrinding());
                //磨削操作工号
                //oneBodyMachineCode += StringUtils.isEmpty(eapGrindingMachine.getGrindingMan()) || eapGrindingMachine.getGrindingMan().length() < 3 ? "000" :  eapGrindingMachine.getGrindingMan().substring(eapGrindingMachine.getGrindingMan().length()-3);
                oneBodyMachineCode += StringUtils.isEmpty(eapGrindingMachine.getGrindingManCode()) ? "000" : eapGrindingMachine.getGrindingManCode();
                //磨削机台号
                if (eapGrindingMachine.getEquipNo() != null && eapGrindingMachine.getEquipNo().length() >= 2) {
                    oneBodyMachineCode += eapGrindingMachine.getEquipNo().substring(2);
                }else{
                    oneBodyMachineCode += "000";
                }
                //磨削下料记录
                GrindingBlanking grindingBlanking = grindingBlankingService.findTopByFbSectionNoOrderByIdDesc(eapGrindingMachine.getSn());
                if (grindingBlanking != null && grindingBlanking.getGrindingOrder() != null){
                    //磨削当班加工颗数
                    oneBodyMachineCode += String.format("%02d", Integer.parseInt(grindingBlanking.getGrindingOrder()));
                }else{
                    oneBodyMachineCode += "00";
                }
            }
            eapGrindingMachine.setOneBodyMachineCode(oneBodyMachineCode);
        }catch(Exception e){

        }
        return oneBodyMachineCode;
    }

    @Override
    public ProcessingMachineDto getProcessingMachineCode(String sn) {
        ProcessingMachineDto processingMachineDto = new ProcessingMachineDto();
        processingMachineDto.setSn(sn);
        //磨削加工记录
        EapGrindingMachine eapGrindingMachine = this.findTopByFbSectionNoOrderByIdDesc(sn);
        if (eapGrindingMachine != null){
            processingMachineDto.setEquipNo(eapGrindingMachine.getEquipNo());
            processingMachineDto.setEndGrinding(eapGrindingMachine.getEndGrinding());
        }
        //磨削下料记录
        GrindingBlanking grindingBlanking = grindingBlankingService.findTopByFbSectionNoOrderByIdDesc(sn);
        if (grindingBlanking != null){
            processingMachineDto.setGrindingOrder(grindingBlanking.getGrindingOrder());
        }

        //开方加工记录
        EapEvolutionRecord eapEvolutionRecord = eapEvolutionRecordService.findTopBySnOrderByIdDesc(sn);
        if(eapEvolutionRecord != null){
            processingMachineDto.setKfEquipNo(eapEvolutionRecord.getEquipNo());
            processingMachineDto.setEndTrimming(eapEvolutionRecord.getEndTrimming());
        }
        EapEvolutionBlanking eapEvolutionBlanking = eapEvolutionBlankingService.findTopBySnOrderByIdDesc(sn);
        if (eapEvolutionBlanking != null && eapEvolutionBlanking.getTrimmingOrder() != null ){
            processingMachineDto.setTrimmingOrder(eapEvolutionBlanking.getTrimmingOrder());
        }

        return processingMachineDto;
    }

    public boolean timeCalendar(Date nowTime, Date dayTimeStart, Date dayTimeEnd) {
        //设置当前时间
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);
        //设置开始时间
        Calendar timeStart = Calendar.getInstance();
        timeStart.setTime(dayTimeStart);
        //设置结束时间
        Calendar timeEnd = Calendar.getInstance();
        timeEnd.setTime(dayTimeEnd);
        if (date.after(timeStart) && date.before(timeEnd)) {
            return true;
        } else {
            return false;
        }
    }

    public String getClassNo(Date date){
        String classNo = "";
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
        try {
            if (date != null) {
                Date nowTime = df.parse(df.format(date));
                Date dayTimeStart = df.parse("09:00:00");
                Date dayTimeEnd = df.parse("21:00:00");
                if (timeCalendar(nowTime, dayTimeStart, dayTimeEnd)) {
                    classNo = "B";
                } else {
                    classNo = "Y";
                }
            }
        }catch (Exception e){

        }
        return classNo;
    }
    @Override
    public EapGrindingMachine findTopByFbSectionNoOrderByIdDesc(String fbSectionNo) {
        return dao.findTopByFbSectionNoOrderByIdDesc(fbSectionNo);
    }
}
