package com.fizz.business.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.fizz.business.constants.enums.ExitCutTypeEnum;
import com.fizz.business.dto.ExitCoilInfoDTO;
import com.fizz.business.dto.MatmapDTO;
import com.fizz.business.dto.PdoExCoilDTO;
import com.fizz.business.service.CrmPdiPlanService;
import com.fizz.business.service.CrmPdoExcoilService;
import com.fizz.business.service.PdoExCoilService;
import com.fizz.business.service.PdoStripValueService;
import com.fizz.business.utils.CalcUtil;
import com.fizz.business.vo.CrmPdiPlanVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Objects;

import static com.fizz.business.constants.CommonConstants.SYSTEM_MODULE;
import static com.fizz.business.constants.enums.ExitCutTypeEnum.SPLIT_CUT;
import static com.fizz.business.constants.enums.ExitCutTypeEnum.WELDER_CUT;


/**
 * @author chenhao
 * @date 2023/05/30
 */
@Slf4j
@Service
public class PdoExCoilServiceImpl implements PdoExCoilService {

    @Autowired
    private CrmPdoExcoilService crmPdoExcoilService;
    @Autowired
    private CrmPdiPlanService crmPdiPlanService;
    @Autowired
    private PdoStripValueService pdoStripValueService;


    @Override
    @Transactional
    public PdoExCoilDTO saveExCoil(ExitCoilInfoDTO exitCoil) {

        PdoExCoilDTO pdoExCoilDTO = new PdoExCoilDTO();
        CrmPdiPlanVO plan = crmPdiPlanService.getByCoilIdAndOperId(exitCoil.getEntryMatId());

        double aimWeightTop = 1;
        double aimWeightBottom = 1;

        pdoExCoilDTO.setPlanOrigin(plan.getUnitCode());
        pdoExCoilDTO.setUnitCode(plan.getUnitCode());
        pdoExCoilDTO.setProcessCode(SYSTEM_MODULE);
        pdoExCoilDTO.setExitMatId(exitCoil.getExitMatId());
        pdoExCoilDTO.setEntryMatId(exitCoil.getEntryMatId());
        pdoExCoilDTO.setSubId(exitCoil.getSubNum());
        pdoExCoilDTO.setStartPosition(exitCoil.getStartPos());
        pdoExCoilDTO.setEndPosition(exitCoil.getEndPos());
        pdoExCoilDTO.setPlanId(plan.getId());
        pdoExCoilDTO.setSteelGrade(plan.getSteelGrade());

        pdoExCoilDTO.setEntryThick(plan.getEntryThick().doubleValue());
        pdoExCoilDTO.setEntryWidth(plan.getEntryWidth().doubleValue());
        pdoExCoilDTO.setEntryLength(plan.getEntryLength().doubleValue());
        pdoExCoilDTO.setEntryWeight(plan.getEntryWeight().doubleValue());
        pdoExCoilDTO.setWeightTop(aimWeightTop);
        pdoExCoilDTO.setWeightBottom(aimWeightBottom);
        pdoExCoilDTO.setExitLength(exitCoil.getExitCutLength());
        log.info("==========================钢卷出口剪切长度{}，厚度{}，宽度{}===================",exitCoil.getExitCutLength(),plan.getExitThickTar(),plan.getExitWidthTar());
        double exitWeight = CalcUtil.calcCoilWeight(exitCoil.getExitCutLength(), plan.getExitThickTar(), plan.getExitWidthTar());
        pdoExCoilDTO.setExitNetWeight(exitWeight);
        pdoExCoilDTO.setActualWeight(exitWeight);
        pdoExCoilDTO.setTheoryWeight(exitWeight);
        double exitOuterDiameter = CalcUtil.calcOuterDiameter(exitWeight, exitWeight, plan.getEntryInnerDiameter().doubleValue());
        pdoExCoilDTO.setExitOuterDiameter(exitOuterDiameter);
        pdoExCoilDTO.setExitThickness(plan.getExitThickTar().doubleValue());
        pdoExCoilDTO.setExitWidth(plan.getExitWidthTar().doubleValue());
        pdoExCoilDTO.setLastFlag(exitCoil.isLastFlag());
        pdoExCoilDTO.setSeparateFlag(exitCoil.isSeparateFlag());
        // 计划有子卷需要记录，通知L3

        pdoExCoilDTO.setOnlineTime(plan.getOnlineDate());
        pdoExCoilDTO.setStartTime(plan.getStartDate());
        LocalDateTime now = LocalDateTime.now();
        pdoExCoilDTO.setEndTime(now);

        // 获取班组信息
        pdoExCoilDTO.setGroupNo("1");
        pdoExCoilDTO.setShiftNo("A");
        pdoExCoilDTO.setStatus("UNWEIGHT");

        log.info("save pdo exit coil:{}", JSONUtil.toJsonStr(pdoExCoilDTO));

        // 产出实际入库
        crmPdoExcoilService.addCrmPdoExcoil(pdoExCoilDTO);
        // 打包segment
//        pdoStripValueService.treatStripValues(exitCoil);
        return pdoExCoilDTO;
    }

    /**
     * 通过计划的halfReturnType字段判断当前卷是回退的头部卷还是尾部卷
     * 1. 头部卷: entryMatId=A01
     * 2. 尾部卷: entryMatId=A01-2, returnMatId=A01。（由于计划号+钢卷号唯一，所以回退的尾部卷生成新计划时，将entryMatId设置为A01-2，真实的原料卷号保存在returnMatId中）
     * 半卷回退上报产出
     * 1. 头部卷产出时，原料卷号：A01, 产出卷号: A01-1, 分卷标识: true, 尾卷标识: false
     * 2. 尾部卷产出时：原料卷号：A01，产出卷号: A01-2
     *
     * @param trMatmap
     * @param cutType
     * @return ExitCoilInfoDTO
     */
    @Override
    public ExitCoilInfoDTO genExitCoilInfo(MatmapDTO trMatmap, ExitCutTypeEnum cutType) {
        log.info("触发出口分卷信号:{}，剪切类型为:{}",trMatmap,cutType);
        String trCoilId = trMatmap.getMatId();
        //准备的成品子卷号
        //考虑依据数据库记录分卷，避免因为平台重启导致分卷丢失或错误
        Long subNum = crmPdoExcoilService.getNumber(trCoilId
                , trMatmap.getPlanId(),
                0);

        CrmPdiPlanVO plan = crmPdiPlanService.getByCoilIdAndOperId(trMatmap.getMatId());

        String entryMatId = trCoilId;
        String exitMatId = entryMatId;
        boolean separateFlag = false;
        boolean lastFlag = Objects.equals(cutType, WELDER_CUT);

        if (subNum != 0 || Objects.equals(cutType, SPLIT_CUT)) {
            subNum = subNum + 1;
            separateFlag = true;
            exitMatId = exitMatId + "-" + subNum;
        }
        ExitCoilInfoDTO exitCoil = ExitCoilInfoDTO.builder()
                .planId(plan.getPlanid())
                .entryMatId(entryMatId)
                .exitMatId(exitMatId)
                .separateFlag(separateFlag)
                .lastFlag(lastFlag)
                .subNum(Integer.parseInt(subNum.toString()))
                .build();
        log.info("I: generate exit cut coil info:{}", JSON.toJSONString(exitCoil));
        return exitCoil;
    }

    @Override
    public void deleteExistPdo(String coilId, String planId) {
        crmPdoExcoilService.deleteCrmPdoExcoil(coilId, planId);
    }
}
