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


import com.sw.mes.base.erp.service.ReportSapRecordService;
import com.sw.mes.base.factory.inspect.entity.ProductAssemblyRule;
import com.sw.mes.base.factory.inspect.service.ProductAssemblyRuleService;
import com.sw.mes.base.global.GlobalSwitch;
import com.sw.mes.base.global.SwitchConfig;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.base.system.service.DictionaryItemService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
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.utils.DateUtil;
import com.sw.mes.core.utils.DynamicSpecifications;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.fb.turnstore.dao.FbTurnstoreTrayItemDao;
import com.sw.mes.fb.turnstore.dto.FbTurnstoreTrayPostDto;
import com.sw.mes.fb.turnstore.entity.FbTurnstoreTray;
import com.sw.mes.fb.turnstore.entity.FbTurnstoreTrayItem;
import com.sw.mes.fb.turnstore.service.FbTurnstoreTrayItemService;
import com.sw.mes.fb.turnstore.service.FbTurnstoreTrayService;
import com.sw.mes.base.workinprocess.entity.PlanProcessingOrder;
import com.sw.mes.base.workinprocess.service.PlanProcessingOrderService;
import com.sw.mes.wms.dto.ReturnAndCancelDto;
import com.sw.mes.wms.service.WmsToMesService;
import com.sw.mes.wms.utils.ResultWmsDto;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.sw.mes.base.global.GlobalSwitchNamespace.CODE_SWITCH;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Service
@Transactional
public class FbTurnstoreTrayItemServiceImpl extends BaseServiceImpl<FbTurnstoreTrayItem> implements FbTurnstoreTrayItemService {
    FbTurnstoreTrayItemDao dao;

    @Autowired
    private FbTurnstoreTrayService fbTurnstoreTrayService;

    @Autowired
    private FbTurnstoreTrayItemService fbTurnstoreTrayItemService;

    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private ProductAssemblyRuleService productAssemblyRuleService;

    @Autowired
    private DictionaryItemService dictionaryItemService;

    @Autowired
    private WmsToMesService wmsToMesService;

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

    @Override
    public List<FbTurnstoreTrayItem> getItemsByTrayId(Integer trayId) {
        return dao.getItemsByTrayId(trayId);
    }


    @Override
    public List<FbTurnstoreTrayItem> getItemsByTrayIdByOrder(Integer trayId) {
        return dao.getItemsByTrayIdByOrder(trayId);
    }

    @Override
    public List<FbTurnstoreTrayItem> getItemsByAllTrayId(List<Integer> trayIdList) {
        return dao.getItemsByAllTrayId(trayIdList);
    }

    @Override
    public FbTurnstoreTrayItem findBySectionNo(String crystalNo) {
        List<FbTurnstoreTrayItem> fbTurnstoreTrayItemList = dao.findBySectionNo(crystalNo);
        if (null != fbTurnstoreTrayItemList && !fbTurnstoreTrayItemList.isEmpty()) {
            return fbTurnstoreTrayItemList.get(0);
        }
        return null;
    }


    @Override
    public FbTurnstoreTrayItem findBySectionNo1(String crystalNo) {
        List<FbTurnstoreTrayItem> fbTurnstoreTrayItemList = dao.findBySectionNo1(crystalNo);
        if (null != fbTurnstoreTrayItemList && !fbTurnstoreTrayItemList.isEmpty()) {
            return fbTurnstoreTrayItemList.get(0);
        }
        return null;
    }

    @Override
    public FbTurnstoreTrayItem findBySectionNo2(String crystalNo) {
        List<FbTurnstoreTrayItem> fbTurnstoreTrayItemList = dao.findBySectionNo2(crystalNo);
        if (null != fbTurnstoreTrayItemList && !fbTurnstoreTrayItemList.isEmpty()) {
            return fbTurnstoreTrayItemList.get(0);
        }
        return null;
    }

    @Override
    public FbTurnstoreTrayItem findBySectionNoAndState(String crystalNo, int state) {
        List<FbTurnstoreTrayItem> fbTurnstoreTrayItemList = dao.findBySectionNoAndState(crystalNo, state);
        if (null != fbTurnstoreTrayItemList && !fbTurnstoreTrayItemList.isEmpty()) {
            return fbTurnstoreTrayItemList.get(fbTurnstoreTrayItemList.size() - 1);
        }
        return null;
    }

    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse resp) {
        //根据托号查询组托主表
        Specification<FbTurnstoreTrayItem> specification = DynamicSpecifications.bySearchFilter(request, FbTurnstoreTrayItem.class);
        List<FbTurnstoreTrayItem> turnstoreTrayItemList = findByExampleSort(specification, null);
        String search_eq_trayNo = request.getParameter("search_EQ_trayNo");
        FbTurnstoreTray byTrayNo = fbTurnstoreTrayService.findByTrayNo(search_eq_trayNo);
        if ((!turnstoreTrayItemList.isEmpty()) && (byTrayNo != null)) {
            try {
                getExportExcel(turnstoreTrayItemList, byTrayNo, request, resp);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void exportExcel1(HttpServletRequest request, HttpServletResponse resp) {
        //根据托号查询组托主表
        Specification<FbTurnstoreTray> specification = DynamicSpecifications.bySearchFilter(request, FbTurnstoreTray.class);
        List<FbTurnstoreTray> turnstoreTrays = fbTurnstoreTrayService.findByExampleSort(specification, null);
        if ((!turnstoreTrays.isEmpty())) {
            try {
                getExportExcel1(turnstoreTrays, request, resp);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void getExportExcel1(List<FbTurnstoreTray> turnstoreTrays, HttpServletRequest request, HttpServletResponse resp) throws IOException {
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet("方棒出库到WMS");
        XSSFRow row;
        row = sheet.createRow(0);
        row.createCell(0).setCellValue("序号");
        row.createCell(1).setCellValue("托号");
        row.createCell(2).setCellValue("打托类型");
        row.createCell(3).setCellValue("厂区");
        row.createCell(4).setCellValue("方棒产品等级");
        row.createCell(5).setCellValue("单晶总数");
        row.createCell(6).setCellValue("状态");
        row.createCell(7).setCellValue("打托工位");
        //增加一列：识别码
        row.createCell(8).setCellValue("识别码");
        row.createCell(9).setCellValue("规格");
        row.createCell(10).setCellValue("实验等级");
        row.createCell(11).setCellValue("客户");
        row.createCell(12).setCellValue("产品类别");
        row.createCell(13).setCellValue("去向");
        row.createCell(14).setCellValue("创建操作人");
        row.createCell(15).setCellValue("更新操作人");
        row.createCell(16).setCellValue("操作时间");
        row.createCell(17).setCellValue("打印时间");
        row.createCell(18).setCellValue("组托时间");
        row.createCell(19).setCellValue("报工时间");
        row.createCell(20).setCellValue("入库操作人");
        row.createCell(21).setCellValue("入库时间");

        List<DictionaryItem> packDetailState = dictionaryItemService.findItemByThemeValue("PackDetailState", true);
        Map<String, String> collect1 = packDetailState.stream().collect(Collectors.toMap(DictionaryItem::getValue, DictionaryItem::getName));
        List<DictionaryItem> product_category = dictionaryItemService.findByThemeValueAndEnable("product_category", true);
        Map<String, String> collect2 = product_category.stream().collect(Collectors.toMap(DictionaryItem::getValue, DictionaryItem::getName));

        //减少查询量，提速
        List<Integer> trayIdList = new ArrayList<>();
        for (FbTurnstoreTray turnstoreTray : turnstoreTrays) {
            trayIdList.add(turnstoreTray.getId());
        }
        List<FbTurnstoreTrayItem> itemsByTrayId = fbTurnstoreTrayItemService.getItemsByAllTrayId(trayIdList);
        Map<Integer, String> trayIdProductTypeMap = itemsByTrayId.stream().collect(Collectors.toMap(FbTurnstoreTrayItem::getTrayId, FbTurnstoreTrayItem::getProductType));
        String productType = null;
        if (!CollectionUtils.isEmpty(itemsByTrayId)) {
            productType = itemsByTrayId.get(0).getProductType();
        }

        for (int i = 0; i < turnstoreTrays.size(); i++) {
            row = sheet.createRow(i + 1);
            FbTurnstoreTray byTrayNo = turnstoreTrays.get(i);

            if (trayIdProductTypeMap.containsKey(byTrayNo.getId())) {
                productType = trayIdProductTypeMap.get(byTrayNo.getId());
            }
            row.createCell(0).setCellValue(i + 1);
            if (byTrayNo.getTrayNo() != null) {
                row.createCell(1).setCellValue(byTrayNo.getTrayNo());
            }
            if (byTrayNo.getPalletType() != null) {
                row.createCell(2).setCellValue(byTrayNo.getPalletType());
            }
            if (byTrayNo.getFactoryName() != null) {
                row.createCell(3).setCellValue(byTrayNo.getFactoryName());
            }
            if (byTrayNo.getProductLevelSecond() != null) {
                row.createCell(4).setCellValue(byTrayNo.getProductLevelSecond());
            }
            if (byTrayNo.getCount() != null) {
                row.createCell(5).setCellValue(byTrayNo.getCount());
            }


            if (byTrayNo.getState() != null) {
                row.createCell(6).setCellValue(collect1.get(byTrayNo.getState().toString()));
            }
            if (byTrayNo.getStation() != null) {
                row.createCell(7).setCellValue(byTrayNo.getStation());
            }
            //增加一列：识别码
            if (byTrayNo.getStation() != null) {
                row.createCell(8).setCellValue(byTrayNo.getIdentifyingCode());
            }

            if (byTrayNo.getSpecs() != null) {
                row.createCell(9).setCellValue(byTrayNo.getSpecs());
            }

            if (byTrayNo.getTestZt() != null) {
                row.createCell(10).setCellValue(byTrayNo.getTestZt());
            }
            if (byTrayNo.getCustomer() != null) {
                row.createCell(11).setCellValue(byTrayNo.getCustomer());
            }
            if (!StringUtils.isEmpty(productType)) {
                row.createCell(12).setCellValue(collect2.get(productType));
            }
            if (byTrayNo.getHasGone() != null) {
                row.createCell(13).setCellValue(byTrayNo.getHasGone());
            }

            //存货编码
            if (byTrayNo.getUser() != null) {
                row.createCell(14).setCellValue(byTrayNo.getUser());
            }
            //规格型号
            if (byTrayNo.getUpdateUser() != null) {
                row.createCell(15).setCellValue(byTrayNo.getUpdateUser());
            }
            //等级
            if (byTrayNo.getOperationTime() != null) {
                row.createCell(16).setCellValue(DateUtil.formatDate(byTrayNo.getOperationTime(), DateUtil.longFormat));
            }
            //长度
            if (byTrayNo.getPrintTime() != null) {
                row.createCell(17).setCellValue(DateUtil.formatDate(byTrayNo.getPrintTime(), DateUtil.longFormat));
            }
            //重量
            if (byTrayNo.getTime() != null) {
                row.createCell(18).setCellValue(DateUtil.formatDate(byTrayNo.getTime(), DateUtil.longFormat));
            }
            //重量
            if (byTrayNo.getReportingTime() != null) {
                row.createCell(19).setCellValue(DateUtil.formatDate(byTrayNo.getReportingTime(), DateUtil.longFormat));
            }
            //边距MAX
            if (byTrayNo.getConfirmUser() != null) {
                row.createCell(20).setCellValue(byTrayNo.getConfirmUser());
            }
            //边距MIN
            if (byTrayNo.getConfirmTime() != null) {
                row.createCell(21).setCellValue(DateUtil.formatDate(byTrayNo.getConfirmTime(), DateUtil.longFormat));
            }
        }
        sheet.setDefaultRowHeight((short) (20 * 20));
        //列宽自适应
        int num = 30;
        for (int i = 0; i <= num; i++) {
            sheet.autoSizeColumn(i);
        }
        String fileName = "方棒组托信息导出.xls";
        //乱码解决
        String userAgent = request.getHeader("user-agent").toLowerCase();
        if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
            // win10 ie edge 浏览器 和其他系统的ie
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            // fe
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        //输出Excel文件
        OutputStream output = resp.getOutputStream();
        resp.reset();
        resp.setHeader("Content-disposition", "attachment; filename=" + fileName);
        resp.setContentType("application/msexcel");
        wb.write(output);
        output.flush();
        output.close();
    }

    private void getExportExcel(List<FbTurnstoreTrayItem> turnstoreTrayItemList, FbTurnstoreTray byTrayNo, HttpServletRequest request, HttpServletResponse resp) throws IOException {
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("方棒出库到WMS");
        HSSFRow row;
        row = sheet.createRow(0);
        row.createCell(0).setCellValue("序号");
        row.createCell(1).setCellValue("托号");
        row.createCell(2).setCellValue("打托类型");
        row.createCell(3).setCellValue("厂区");
        row.createCell(4).setCellValue("单晶编号");
        row.createCell(5).setCellValue("订单号");
        row.createCell(6).setCellValue("组号");
        row.createCell(7).setCellValue("生产日期");
        row.createCell(8).setCellValue("班次");
        row.createCell(9).setCellValue("规则");
        row.createCell(10).setCellValue("试验");
        row.createCell(11).setCellValue("存货编码");
        row.createCell(12).setCellValue("规格型号");
        row.createCell(13).setCellValue("等级");
        row.createCell(14).setCellValue("长度");
        row.createCell(15).setCellValue("实测重量");
        row.createCell(16).setCellValue("理论重量");
        row.createCell(17).setCellValue("边距MAX");
        row.createCell(18).setCellValue("边距MIN");
        row.createCell(19).setCellValue("直径MAX");
        row.createCell(20).setCellValue("直径MIN");
        row.createCell(21).setCellValue("崩边扣减上");
        row.createCell(22).setCellValue("崩边扣减中");
        row.createCell(23).setCellValue("崩边扣减下");
        row.createCell(24).setCellValue("扣减崩缺长度");
        row.createCell(25).setCellValue("有效切片长度");
        row.createCell(26).setCellValue("头部少子");
        row.createCell(27).setCellValue("合格品尾部合格少子");
        row.createCell(28).setCellValue("头部氧含量");
        row.createCell(29).setCellValue("尾部碳含量");
        row.createCell(30).setCellValue("掺杂类型");
        row.createCell(31).setCellValue("产品类型");
        row.createCell(32).setCellValue("电阻类型");
        row.createCell(33).setCellValue("去向");
        row.createCell(34).setCellValue("操作人");
        row.createCell(35).setCellValue("操作时间");
        row.createCell(36).setCellValue("发货日期");
        row.createCell(37).setCellValue("方棒备注");

        for (int i = 0; i < turnstoreTrayItemList.size(); i++) {
            row = sheet.createRow(i + 1);
            FbTurnstoreTrayItem trayItem = turnstoreTrayItemList.get(i);
            row.createCell(0).setCellValue(i + 1);
            if (trayItem.getTrayNo() != null) {
                row.createCell(1).setCellValue(trayItem.getTrayNo());
            }
            if (byTrayNo.getPalletType() != null) {
                row.createCell(2).setCellValue(byTrayNo.getPalletType());
            }
            if (byTrayNo.getFactoryName() != null) {
                row.createCell(3).setCellValue(byTrayNo.getFactoryName());
            }
            if (trayItem.getSectionNo() != null) {
                row.createCell(4).setCellValue(trayItem.getSectionNo());
            }
            if (trayItem.getOrderNo() != null) {
                row.createCell(5).setCellValue(trayItem.getOrderNo());
            }
            if (trayItem.getSectionCompose() != null) {
                row.createCell(6).setCellValue(trayItem.getSectionCompose());
            }
            if (trayItem.getCheckTime() != null) {
                row.createCell(7).setCellValue(DateUtil.formatDate(trayItem.getCheckTime(), DateUtil.longFormat));
            }

            if (byTrayNo.getClassName() != null) {
                row.createCell(8).setCellValue(byTrayNo.getClassName());
            }

            if (byTrayNo.getStation() != null) {
                row.createCell(9).setCellValue(byTrayNo.getStation());
            }
            if (byTrayNo.getTestZt() != null) {
                row.createCell(10).setCellValue(byTrayNo.getTestZt());
            }

            //存货编码
            if (trayItem.getMaterialNumber() != null) {
                row.createCell(11).setCellValue(trayItem.getMaterialNumber());
            }
            //规格型号
            if (trayItem.getSpecification() != null) {
                row.createCell(12).setCellValue(trayItem.getSpecification());
            }
            //等级
            if (trayItem.getProductLevel() != null) {
                row.createCell(13).setCellValue(trayItem.getProductLevel());
            }
            //长度
            if (trayItem.getLength() != null) {
                row.createCell(14).setCellValue(trayItem.getLength().doubleValue());
            }
            //重量
            if (trayItem.getWeight() != null) {
                row.createCell(15).setCellValue(trayItem.getWeight().doubleValue());
            }
            //重量
            if (trayItem.getTheoryWeightFb() != null) {
                row.createCell(16).setCellValue(trayItem.getTheoryWeightFb().doubleValue());
            }
            //边距MAX
            if (trayItem.getSideLengthMax() != null) {
                row.createCell(17).setCellValue(trayItem.getSideLengthMax().doubleValue());
            }
            //边距MIN
            if (trayItem.getSideLengthMin() != null) {
                row.createCell(18).setCellValue(trayItem.getSideLengthMin().doubleValue());
            }

            //直径MAX
            if (trayItem.getDiameterMax() != null) {
                row.createCell(19).setCellValue(trayItem.getDiameterMax().doubleValue());
            }
            //直径MIN
            if (trayItem.getDiameterMin() != null) {
                row.createCell(20).setCellValue(trayItem.getDiameterMin().doubleValue());
            }
            //崩边扣减上
            if (trayItem.getCollapseLossSh() != null) {
                row.createCell(21).setCellValue(trayItem.getCollapseLossSh().doubleValue());
            }
            //崩边扣减中
            if (trayItem.getCollapseLossZh() != null) {
                row.createCell(22).setCellValue(trayItem.getCollapseLossZh().doubleValue());
            }
            //崩边扣减下
            if (trayItem.getCollapseLossXia() != null) {
                row.createCell(23).setCellValue(trayItem.getCollapseLossXia().doubleValue());
            }
            //扣减崩缺长度
            if (trayItem.getCollapseLoss() != null) {
                row.createCell(24).setCellValue(trayItem.getCollapseLoss().doubleValue());
            }
            //有效切片长度
            if (trayItem.getEffectiveLength() != null) {
                row.createCell(25).setCellValue(trayItem.getEffectiveLength().doubleValue());
            }
            //头部少子
            if (trayItem.getLife() != null) {
                row.createCell(26).setCellValue(trayItem.getLife().doubleValue());
            }
            //合格品尾部合格少子
            if (trayItem.getWLifeMin() != null) {
                row.createCell(27).setCellValue(trayItem.getWLifeMin().doubleValue());
            }
            //头部氧含量
            if (trayItem.getOxygenContentHead() != null) {
                row.createCell(28).setCellValue(trayItem.getOxygenContentHead().doubleValue());
            }
            //尾部碳含量
            if (trayItem.getCarbonContentTail() != null) {
                row.createCell(29).setCellValue(trayItem.getCarbonContentTail().doubleValue());
            }
            //掺杂类型
            if (trayItem.getDopant() != null) {
                row.createCell(30).setCellValue(trayItem.getDopant());
            }
            //产品类型
            if (trayItem.getProductType() != null) {
                row.createCell(31).setCellValue(trayItem.getProductType());
            }
            //电阻类型
            if (trayItem.getResistanceType() != null) {
                row.createCell(32).setCellValue(trayItem.getResistanceType());
            }

            //去向
            if (trayItem.getHasGone() != null) {
                row.createCell(33).setCellValue(trayItem.getHasGone());
            }
            //操作人
            if (trayItem.getUser() != null) {
                row.createCell(34).setCellValue(trayItem.getUser());
            }
            //操作时间
            if (trayItem.getOperationTime() != null) {
                row.createCell(35).setCellValue(DateUtil.formatDate(trayItem.getOperationTime(), DateUtil.longFormat));
            }
            //发货日期
            if (trayItem.getToWmsTime() != null) {
                row.createCell(36).setCellValue(DateUtil.formatDate(trayItem.getToWmsTime(), DateUtil.longFormat));
            }
            //方棒备注
            if (trayItem.getSquareRodRemark() != null) {
                row.createCell(37).setCellValue(trayItem.getSquareRodRemark());
            }
        }
        sheet.setDefaultRowHeight((short) (20 * 20));
        //列宽自适应
        int num = 30;
        for (int i = 0; i <= num; i++) {
            sheet.autoSizeColumn(i);
        }
        String fileName = turnstoreTrayItemList.get(0).getTrayNo() + "_方棒WMS导出.xls";
        //乱码解决
        String userAgent = request.getHeader("user-agent").toLowerCase();
        if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
            // win10 ie edge 浏览器 和其他系统的ie
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            // fe
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        //输出Excel文件
        OutputStream output = resp.getOutputStream();
        resp.reset();
        resp.setHeader("Content-disposition", "attachment; filename=" + fileName);
        resp.setContentType("application/msexcel");
        wb.write(output);
        output.flush();
        output.close();
    }

    @Override
    public void deleteByTrayId(Integer id) {
        List<FbTurnstoreTrayItem> itemsByTrayId = dao.findItemsByTrayId(id);
        if (null != itemsByTrayId && !itemsByTrayId.isEmpty()) {
            SwitchConfig config = GlobalSwitch.switchConfig(CODE_SWITCH, "deleteTurnStoreTray", false);
            if(config.isEnable()){
                fbTurnstoreTrayService.fbWriteOffAccounts(itemsByTrayId);
            }
            for (FbTurnstoreTrayItem trayItem : itemsByTrayId) {
                //解锁组托状态
                PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCode(trayItem.getSectionNo());
                if (null != planProcessingOrder) {
                    planProcessingOrder.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey());
                    planProcessingOrderService.saveOrUpdate(planProcessingOrder);
                }
            }
            dao.deleteByTrayId(id);
        }
    }

    @Override
    public FbTurnstoreTrayPostDto cancelStock(Integer id) {
        FbTurnstoreTrayPostDto postDto = new FbTurnstoreTrayPostDto();
        FbTurnstoreTray fbTurnstoreTray = fbTurnstoreTrayService.get(id);
        ReturnAndCancelDto returnAndCancelDto = new ReturnAndCancelDto();
        returnAndCancelDto.setTrayNo(fbTurnstoreTray.getTrayNo());
        returnAndCancelDto.setCancelFlag(1);
        ResultWmsDto resultWmsDto = wmsToMesService.ReturnAndCancel(returnAndCancelDto);
        if (1 != resultWmsDto.getCode()) {
            throw new BusinessException("请求WMS失败,请稍后重新请求退库");
        }
        if (!"false".equalsIgnoreCase(resultWmsDto.getMsg())) {
            throw new BusinessException("该托盘物料已入库WMS，MES中不允许退库，请联系WMS同事发起退库！");
        }
        postDto.setFbTray(fbTurnstoreTray);
        fbTurnstoreTrayService.delete(id);
        //查询组托规则
        if (null != fbTurnstoreTray.getStation()) {
            ProductAssemblyRule ruleByStation = productAssemblyRuleService.findRuleByStation(fbTurnstoreTray.getStation());
            postDto.setProductRule(ruleByStation);
        }
        //查询详情列表
        List<FbTurnstoreTrayItem> fbTurnstoreTrayItemList = getItemsByTrayId(id);
       // deleteByTrayId(id);
        //退站
        for (FbTurnstoreTrayItem fbTurnstoreTrayItem : fbTurnstoreTrayItemList) {
            wipStorageService.exitStation(fbTurnstoreTrayItem.getSectionNo());
        }
        postDto.setTrayItems(fbTurnstoreTrayItemList);
        return postDto;
    }

    @Override
    public void updateTrayItemState(List<String> sectionNoList) {
        //更新组托明细状态
        String lastTrayNo = "";
        String trayNo = "";
        for (String sectionNo : sectionNoList) {
            FbTurnstoreTrayItem bySectionNo = findBySectionNo(sectionNo);
            if (null != bySectionNo) {
                bySectionNo.setState(3);
                trayNo = bySectionNo.getTrayNo();
                saveOrUpdate(bySectionNo);
            }
            //更新组托主表状态
            if (!lastTrayNo.equals(trayNo)) {
                FbTurnstoreTray byTrayNo = fbTurnstoreTrayService.findByTrayNo(trayNo);
                byTrayNo.setState(2);
                fbTurnstoreTrayService.saveOrUpdate(byTrayNo);
            }
            lastTrayNo = trayNo;
        }
    }

    @Override
    public FbTurnstoreTrayItem findByTrayNoAndSectionNo(String trayNo, String sectionNo) {
        List<FbTurnstoreTrayItem> fbTurnstoreTrayItemList = dao.findByTrayNoAndSectionNo(trayNo, sectionNo);
        if (null != fbTurnstoreTrayItemList && !fbTurnstoreTrayItemList.isEmpty()) {
            return fbTurnstoreTrayItemList.get(0);
        }
        return null;
    }

    @Override
    public List<FbTurnstoreTrayItem> findBySectionNoValidate(String sectionNo) {
        return dao.findBySectionNoValidate(sectionNo);
    }

    @Override
    public List<FbTurnstoreTrayItem> findBySectionNoValidateAll(String sectionNo) {
        return dao.findBySectionNoValidateAll(sectionNo);
    }

    @Override
    public List<FbTurnstoreTrayItem> getData(String trayNos) {
        return dao.getData(trayNos);
    }

    @Override
    public List<FbTurnstoreTrayItem> findByTrayId(Integer id) {
        return dao.findItemsByTrayId(id);
    }

    /**
     * 同步数据
     *
     * @param sectionNo
     * @return
     */
    @Override
    public int syncCheckData(String sectionNo) {
        //查到对应的数据
        FbTurnstoreTrayItem item = findBySectionNo(sectionNo);
        

        return 0;
    }

    @Override
    public FbTurnstoreTrayItem findBySectionNo3(String crystalNo) {
        return dao.findBySectionNo3(crystalNo);
    }

    @Override
    public FbTurnstoreTrayItem findBySectionNoAndReturnInspectionStatus(String sectionNo, int returnInspectionStatus) {
        return dao.findBySectionNoAndReturnInspectionStatus(sectionNo, returnInspectionStatus);
    }
}
