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


import com.sw.mes.core.dto.TurnstoreTrayDto;
import com.sw.mes.core.dto.TurnstoreTrayPostDto;
import com.sw.mes.core.entity.FbCheckOutData;
import com.sw.mes.core.entity.TurnstoreTrayItem;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.BeanUtil;
import com.sw.mes.fb.checkout.service.FbCheckOutDataService;
import com.sw.mes.fb.turnstore.dao.RawMaterialReceivingDao;
import com.sw.mes.fb.turnstore.dto.FbTurnstoreTrayPostDto;
import com.sw.mes.fb.turnstore.entity.*;
import com.sw.mes.fb.turnstore.service.FbTurnstoreTrayItemService;
import com.sw.mes.fb.turnstore.service.FbTurnstoreTrayService;
import com.sw.mes.fb.turnstore.service.RawMaterialReceivingDetailService;
import com.sw.mes.fb.turnstore.service.RawMaterialReceivingService;
import com.sw.mes.base.workinprocess.entity.PlanProcessingOrder;
import com.sw.mes.base.workinprocess.service.PlanProcessingOrderService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Service
@Transactional
public class RawMaterialReceivingServiceImpl extends BaseServiceImpl<RawMaterialReceiving> implements RawMaterialReceivingService {
    RawMaterialReceivingDao dao;

    @Autowired
    private RawMaterialReceivingDetailService receivingDetailService;

    @Autowired
    private FbTurnstoreTrayService fbTurnstoreTrayService;

    @Autowired
    private FbTurnstoreTrayItemService fbTurnstoreTrayItemService;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private FbCheckOutDataService fbCheckOutDataService;

    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRawMaterial(TurnstoreTrayPostDto trayPostDto) {
        //保存原料接收主表
        TurnstoreTrayDto trayDto = trayPostDto.getTrayDto();
        RawMaterialReceiving rawMaterialReceiving = new RawMaterialReceiving();
        BeanUtils.copyProperties(trayDto, rawMaterialReceiving, BeanUtil.getIgnoreProperties(trayDto, null, null));
        rawMaterialReceiving.setId(null);
        //  2022/2/22 修改：增加是否自动接收判断，用于自动化流程
        if (trayPostDto.getAutoReceive() != null && trayPostDto.getAutoReceive()) {
            rawMaterialReceiving.setState(1);
            rawMaterialReceiving.setConfirmTime(new Date());
            rawMaterialReceiving.setConfirmUser("自动确认");
            rawMaterialReceiving.setUser("自动");
        } else {
            rawMaterialReceiving.setState(0);
        }
        rawMaterialReceiving.setCrystalNum(trayDto.getCount());
        rawMaterialReceiving.setUser(trayDto.getUpdateUser());
        //来源转换
        rawMaterialReceiving.setSource("圆棒检验");
        RawMaterialReceiving receiving = dao.save(rawMaterialReceiving);
        //保存原料接收明细表
        List<TurnstoreTrayItem> trayItems = trayPostDto.getTrayItems();
        for (TurnstoreTrayItem trayItem : trayItems) {
            RawMaterialReceivingDetail receivingDetail = new RawMaterialReceivingDetail();
            BeanUtils.copyProperties(trayItem, receivingDetail, BeanUtil.getIgnoreProperties(trayItem, null, null));
            receivingDetail.setId(null);
            //  2022/2/22 修改：增加是否自动接收判断，用于自动化流程
            if (trayPostDto.getAutoReceive() != null && trayPostDto.getAutoReceive()) {
                receivingDetail.setState(1);
            } else {
                receivingDetail.setState(0);
            }
            receivingDetail.setTrayId(receiving.getId());
            receivingDetail.setSpecification(trayItem.getProductTypeSecond());
            //保存详情
            receivingDetailService.saveOrUpdate(receivingDetail);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveFbRawMaterial(FbTurnstoreTrayPostDto trayPostDto) {
        //保存原料接收主表
        FbTurnstoreTray trayDto = trayPostDto.getFbTray();
        RawMaterialReceiving rawMaterialReceiving = new RawMaterialReceiving();
        BeanUtils.copyProperties(trayDto, rawMaterialReceiving, BeanUtil.getIgnoreProperties(trayDto, null, null));
        rawMaterialReceiving.setId(null);
        rawMaterialReceiving.setState(0);
        rawMaterialReceiving.setUser(trayDto.getUpdateUser());
        rawMaterialReceiving.setCrystalNum(trayDto.getCount());
        //来源转换
        rawMaterialReceiving.setSource("方棒检验");
        rawMaterialReceiving.setProductLevel(trayDto.getProductLevelSecond());
        RawMaterialReceiving receiving = dao.save(rawMaterialReceiving);
        //保存原料接收明细表
        List<FbTurnstoreTrayItem> trayItems = trayPostDto.getTrayItems();
        for (FbTurnstoreTrayItem trayItem : trayItems) {
            RawMaterialReceivingDetail receivingDetail = new RawMaterialReceivingDetail();
            BeanUtils.copyProperties(trayItem, receivingDetail, BeanUtil.getIgnoreProperties(trayItem, null, null));
            receivingDetail.setId(null);
            receivingDetail.setState(0);
            receivingDetail.setTrayId(receiving.getId());
            receivingDetail.setActualLength(trayItem.getLength());
            receivingDetail.setActualWeight(trayItem.getWeight());
            receivingDetail.setProductLevel(trayItem.getProductLevel());
            receivingDetail.setProductLevelExperiment(trayItem.getFbExperiLevel());
            receivingDetail.setCollapseLine(trayItem.getCollapseLoss());
            receivingDetail.setConductiveType(trayItem.getConductionType());
            receivingDetail.setSectionType(trayItem.getCheckoutName());
            receivingDetail.setWareHouseLength(trayItem.getInstoreLengthFb());
            receivingDetail.setFineCutLength(trayItem.getAbnormalLength());
            //保存详情
            receivingDetailService.saveOrUpdate(receivingDetail);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveDetailDto(List<RawMaterialReceivingDetail> receivingDetailList, String hasGone) {
        Result result;
        for (RawMaterialReceivingDetail receivingDetail : receivingDetailList) {
            //解锁组托状态
            PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCode(receivingDetail.getSectionNo());
            if (null == planProcessingOrder) {
                throw new BusinessException(receivingDetail.getSectionNo() + "工单号不存在");
            }
            planProcessingOrder.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey());
            planProcessingOrderService.saveOrUpdate(planProcessingOrder);
            //更新站点
            if (1 == receivingDetail.getState()) {
                //确认状态进行进站
                if ("方棒加工".equals(hasGone)) {
                    result = wipStorageService.inStation(receivingDetail.getSectionNo(), "开方", false);
                } else if ("方棒返修".equals(hasGone)) {
                    result = wipStorageService.inStation(receivingDetail.getSectionNo(), "磨削", false);
                    //更新检验数据库
                    FbCheckOutData dataByFbSectionNo = fbCheckOutDataService.findDataByFbSectionNo(receivingDetail.getSectionNo());
                    if (null != dataByFbSectionNo) {
                        dataByFbSectionNo.setCheckType("返修检验");
                        fbCheckOutDataService.saveOrUpdate(dataByFbSectionNo);
                    }
                } else {
                    result = wipStorageService.inStation(receivingDetail.getSectionNo(), null, false);
                }
                if (null != result.getCode() && result.getCode() == ResultCode.SUCCESS.code) {
                    receivingDetailService.saveOrUpdate(receivingDetail);
                }
            } else if (3 == receivingDetail.getState()) {
                //拒收状态进行退站
                wipStorageService.exitStation(receivingDetail.getSectionNo());
                receivingDetailService.saveOrUpdate(receivingDetail);
            }
        }
    }

    @Override
    public TurnstoreTrayPostDto initTurnstoreTrayPostDto(RawMaterialReceiving
                                                                 rawMaterialReceiving, List<RawMaterialReceivingDetail> receivingDetailList) {
        TurnstoreTrayPostDto trayPostDto = new TurnstoreTrayPostDto();
        //封装主表
        TurnstoreTrayDto trayDto = new TurnstoreTrayDto();
        BeanUtils.copyProperties(rawMaterialReceiving, trayDto, BeanUtil.getIgnoreProperties(rawMaterialReceiving, null, null));
        //封装详情表
        List<TurnstoreTrayItem> trayItemList = new ArrayList<>();
        for (RawMaterialReceivingDetail receivingDetail : receivingDetailList) {
            TurnstoreTrayItem turnstoreTrayItem = new TurnstoreTrayItem();
            BeanUtils.copyProperties(receivingDetail, turnstoreTrayItem, BeanUtil.getIgnoreProperties(receivingDetail, null, null));
            trayItemList.add(turnstoreTrayItem);
        }
        trayPostDto.setTrayDto(trayDto);
        trayPostDto.setTrayItems(trayItemList);
        return trayPostDto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateFbTrayState(RawMaterialReceiving
                                          entity, List<RawMaterialReceivingDetail> receivingDetailList) {
        //更新组托主表
        FbTurnstoreTray tray = fbTurnstoreTrayService.findByTrayNo(entity.getTrayNo());
        tray.setIsToWms(0);
        tray.setConfirmTime(new Date());
        tray.setConfirmUser(entity.getConfirmUser());
        tray.setState(entity.getState());
        fbTurnstoreTrayService.saveOrUpdate(tray);
        //更新组托明细
        for (RawMaterialReceivingDetail receivingDetail : receivingDetailList) {
            //查询原数据
            FbTurnstoreTrayItem turnstoreTrayItem = fbTurnstoreTrayItemService.findByTrayNoAndSectionNo(tray.getTrayNo(), receivingDetail.getSectionNo());
            if (null != turnstoreTrayItem) {
                turnstoreTrayItem.setIsToWms(0);
                turnstoreTrayItem.setConfirmTime(new Date());
                turnstoreTrayItem.setConfirmUser(entity.getConfirmUser());
                turnstoreTrayItem.setState(receivingDetail.getState());
                fbTurnstoreTrayItemService.saveOrUpdate(turnstoreTrayItem);
            }
        }
    }

    @Override
    public Result<String> cancelState(String trayNo, String user) {
        //更新原料接收主表
        RawMaterialReceiving materialReceiving = findByTrayNoAndState(trayNo, 0);
        if (null == materialReceiving) {
            return ResultGenerator.fail("该托数据不存在或者已被处理,请确认后再操作");
        }
        materialReceiving.setState(4);
        materialReceiving.setConfirmUser(user);
        materialReceiving.setConfirmTime(new Date());
        saveOrUpdate(materialReceiving);
        //保存原料接收明细表
        List<RawMaterialReceivingDetail> receivingDetailList = receivingDetailService.findByTrayNoAndState(trayNo, 0);
        for (RawMaterialReceivingDetail receivingDetail : receivingDetailList) {
            receivingDetail.setState(4);
            //保存详情
            receivingDetailService.saveOrUpdate(receivingDetail);
        }
        return ResultGenerator.success();
    }

    @Override
    public RawMaterialReceiving findByTrayNo(String trayNo) {
        List<RawMaterialReceiving> rawMaterialReceivingList = dao.findByTrayNo(trayNo);
        if (null != rawMaterialReceivingList && !rawMaterialReceivingList.isEmpty()) {
            return rawMaterialReceivingList.get(rawMaterialReceivingList.size() - 1);
        }
        return null;
    }

    @Override
    public RawMaterialReceiving findByTrayNoAndState(String trayNo, int state) {
        List<RawMaterialReceiving> rawMaterialReceivingList = dao.findByTrayNoAndState(trayNo, state);
        if (null != rawMaterialReceivingList && !rawMaterialReceivingList.isEmpty()) {
            return rawMaterialReceivingList.get(0);
        }
        return null;
    }
}
