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


import com.alibaba.fastjson.JSONObject;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.utils.HttpUtil;
import com.sw.mes.third.service.SapGiService;
import com.sw.mes.third.service.SapGrService;
import com.sw.mes.third.service.SendWebService;
import com.sw.mes.yb.turnstore.dao.TurnstoreDao;
import com.sw.mes.yb.turnstore.dao.TurnstoreInItemDao;
import com.sw.mes.yb.turnstore.dao.TurnstoreOutDao;
import com.sw.mes.yb.turnstore.dao.TurnstoreOutItemDao;
import com.sw.mes.yb.turnstore.entity.Turnstore;
import com.sw.mes.yb.turnstore.entity.TurnstoreInItem;
import com.sw.mes.yb.turnstore.entity.TurnstoreOut;
import com.sw.mes.yb.turnstore.entity.TurnstoreOutItem;
import com.sw.mes.yb.turnstore.service.TurnstoreOutService;
import com.sw.mes.yb.turnstore.statics.EnumValues;
import com.sw.mes.yb.turnstore.statics.Utlis;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Service
@Transactional
@Slf4j
public class TurnstoreOutServiceImpl extends BaseServiceImpl<TurnstoreOut> implements TurnstoreOutService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    TurnstoreOutDao dao;

    @Autowired
    TurnstoreOutItemDao itemDao;

    @Autowired
    TurnstoreDao turnstoreDao;

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    SendWebService sendWebService;

   /* @Autowired
    SapSectionMaterialNumberDao sapSectionMaterialNumberDao;

    @Autowired
    TurnstoreTrayItemDao turnstoreTrayItemDao;*/

   // @Autowired
    //SapProductionScheduleDao sapProductionScheduleDao;

    @Autowired
    private SapGiService sapGiService;

  /*  @Autowired
    private TurnstoreTrayService turnstoreTrayService;*/

    @Autowired
    private SapGrService sapGrService;

    @Autowired
    private TurnstoreInItemDao turnstoreInItemDao;

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

    //检查list是否有重复 判断是否在周转库
    public void checkSectionNosOut(List<TurnstoreOutItem> items) {
        if (items == null || items.size() == 0) {
            throw new RuntimeException("出库明细错误");
        }
        for (TurnstoreOutItem turnstoreOutItem : items) {
            if (StringUtils.isBlank(turnstoreOutItem.getSectionNo())) {
                throw new RuntimeException("错误，晶段编号不能为空");
            }
        }
        //判断是否在周转库
        List<String> sectionItems = items.stream().map(TurnstoreOutItem::getSectionNo).collect(Collectors.toList());
        //判断是否传入的list是否有重复晶段编号
        if (sectionItems.size() != new HashSet<String>(sectionItems).size()) {
            throw new RuntimeException("晶段编号不能重复");
        }
        List<Turnstore> checkList = turnstoreDao.getStoreInfoBySectionNos(sectionItems);
        if (checkList == null) {
            throw new RuntimeException("单晶未入周转库，不能出库，请先入库");
        }
        if (items.size() != checkList.size()) {
            List<String> checkStrList = checkList.stream().map(Turnstore::getSectionNo).collect(Collectors.toList());
            List<String> unContailList = new ArrayList<>();
            for (String sectionNo : sectionItems) {
                if (!checkStrList.contains(sectionNo)) {
                    unContailList.add(sectionNo);
                }
            }
            throw new RuntimeException(String.join(",", unContailList) + "等单晶不在周转库，不能出库");
        }
    }

    @Override
    public void createOut(TurnstoreOut turnstoreOut, List<TurnstoreOutItem> items) {
        checkSectionNosOut(items);
        //查询上次单号顺序
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String nowDateStr = dateFormat.format(now);
        Integer lastSort = dao.getMaxSortByDate(nowDateStr);
        turnstoreOut.setTime(now);
        turnstoreOut.setDate(now);
        //turnstoreOut.setState(EnumValues.OutState.待出库.getValue());
        if (turnstoreOut.getType().equals(EnumValues.OutType.出库到综计.getValue())) {
            turnstoreOut.setState(EnumValues.OutState.已出库.getValue());
        } else {
            turnstoreOut.setState(EnumValues.OutState.待出库.getValue());
        }
        turnstoreOut.setSort(lastSort + 1);
        turnstoreOut.setCount(items.size());
        //生成单号
        String orderNo = Utlis.getOrderNoByType(turnstoreOut.getType(), lastSort + 1);
        if (StringUtils.isBlank(orderNo)) {
            throw new RuntimeException("单号生成失败");
        }
        turnstoreOut.setOrderNo(orderNo);
        dao.save(turnstoreOut);
        //从检验表查询检验人、复检类型信息
        List<String> sectionItems = items.stream().map(TurnstoreOutItem::getSectionNo).collect(Collectors.toList());
        List<Map<String,Object>> inspectInfoMap = dao.getInspectBySectionNos(sectionItems);
        //set冗余字段
        for (TurnstoreOutItem turnstoreOutItem : items) {
            turnstoreOutItem.setId(null);
            //主表ID
            turnstoreOutItem.setOutId(turnstoreOut.getId());
            turnstoreOutItem.setType(turnstoreOut.getType());
            turnstoreOutItem.setState(turnstoreOut.getState());
            turnstoreOutItem.setOrderNo(orderNo);
            turnstoreOutItem.setUser(turnstoreOut.getUser());
            turnstoreOutItem.setTime(now);
            turnstoreOutItem.setHasGone(turnstoreOut.getHasGone());
            turnstoreOutItem.setLocationName("周转库");
            TurnstoreOutItem toi = itemDao.getItems2SectionNoAndType(turnstoreOutItem.getSectionNo(), turnstoreOutItem.getType());
            if (Objects.nonNull(toi)) {
                turnstoreOutItem.setTimes(toi.getTimes() + 1);
            }
            //出库记录增加检验人 、复检信息
            for(Map<String,Object> map:inspectInfoMap){
                if(map.get("sectionNo")!=null&&StringUtils.isNotBlank(map.get("sectionNo").toString())){
                    String sectionNo = map.get("sectionNo").toString();
                    if(turnstoreOutItem.getSectionNo().trim().equalsIgnoreCase(sectionNo)){
                        turnstoreOutItem.setInspectUser(map.get("inspector")==null?"":map.get("inspector").toString());
                        turnstoreOutItem.setReCheckType(map.get("reCheckType")==null?"":map.get("reCheckType").toString());
                        continue;
                    }
                }
            }
        }
        itemDao.saveAll(items);
        //更新周转库状态
        //List<Turnstore> turnstoreList = fromDto(items);
        //List<String> sectionItems = turnstoreList.stream().map(Turnstore::getSectionNo).collect(Collectors.toList());
        if (turnstoreOut.getType().equals(EnumValues.OutType.出库到综计.getValue())) {
            //turnstoreDao.updateStoreTrayStatus(sectionItems,EnumValues.OutState.已出库.getValue());
            turnstoreDao.deleteBySectionNo(sectionItems);
           /* if (sectionItems != null && sectionItems.size() > 0) {
                //更改检验工序的在制状态,出库到WMS,status=2
                turnstoreTrayItemDao.updateBySectionNos(sectionItems);
                //复检单晶 记产单晶 入WMS触发GI接口
                List<SapSectionMaterialNumber> sapSectionMaterialNumberList = sapSectionMaterialNumberDao.getListBySectionListAndType(sectionItems, EnumValues.SapSectionType.记产复检单晶.getValue());
                Date nowTime = new Date();
                if (sapSectionMaterialNumberList != null && sapSectionMaterialNumberList.size() > 0) {
                    //List<Gi> giToSapList =new ArrayList<>();
                    List<SapGi> sapGiList = new ArrayList();
                    for (SapSectionMaterialNumber sapSectionMaterialNumber : sapSectionMaterialNumberList) {
                        sapSectionMaterialNumber.setType(EnumValues.SapSectionType.正常单晶.getValue());
                        if (StringUtils.isNotBlank(sapSectionMaterialNumber.getSapOrderNo()) && sapSectionMaterialNumber.getOrgWeight() != null
                                && sapSectionMaterialNumber.getWeight().compareTo(new BigDecimal(0)) > 0) {
                            SapGi sapGi = new SapGi();
                            sapGi.setZmesid(UUID.randomUUID().toString());
                            sapGi.setWerks(SapStaticEnum.SapFactoryId.三期工厂ID.getValue());
                            sapGi.setAufnr(sapSectionMaterialNumber.getSapOrderNo());
                            sapGi.setBty("1");//新增
                            sapGi.setCharg(SapStaticEnum.SapStaticValue.GI固定批次号.getValue());//批次号 虚拟
                            sapGi.setLgort(SapStaticEnum.SapStaticValue.圆棒GI固定库存地点.getValue());//固定库存地点 虚拟
                            sapGi.setIssuedate(WbServiceUtils.getSapDate(nowTime));//日期 yyyymmdd
                            sapGi.setIssuetime(WbServiceUtils.getSapTime(nowTime));//时间 HHmmss
                            sapGi.setMatnr(sapSectionMaterialNumber.getNewMaterialNumber());//新物料号
                            sapGi.setMatnrmat(sapSectionMaterialNumber.getOrgMaterialNumber());//旧物料号
                            sapGi.setMeins("KG");//单位
                            sapGi.setMenge(sapSectionMaterialNumber.getOrgWeight());//数量
                            sapGi.setSource("");
                            sapGi.setSectionno(sapSectionMaterialNumber.getSectionNo());
                            sapGiList.add(sapGi);
                        }
                    }
                    sapSectionMaterialNumberDao.saveAll(sapSectionMaterialNumberList);
                    if (sapGiList != null && sapGiList.size() > 0) {
                        sapGiService.saveBatch(sapGiList);
                    }
                }
            }*/
            //region 调用WMS入库接口
            //调用WMS入库接口
            //炉次号列表
//        List<String> lotNos = new ArrayList<>();
//        for(String sectionNo:sectionItems){
//            String lotNo= null;
//            if(sectionNo.length()>=18){
//                //炉次号
//                lotNo = sectionNo.substring(7,16);
//            }
//            if(StringUtils.isNotBlank(lotNo)){
//                lotNos.add(lotNo);
//            }
//        }
//            try {
//                List<MesToWmsDto> list  = new ArrayList();
//                //从打拖记录表里查询拖号
//                List<Map<String,Object>> turnstoreTrayItemMaps = turnstoreTrayItemDao.getBySectionNos(sectionItems);
//                //从料号评级表查询料号
//                List<SapSectionMaterialNumber>  sapSectionMaterialNumberList =  sapSectionMaterialNumberDao.getListBySectionList(sectionItems);
//                //从检验表查询检验信息
//                List<Map<String,Object>> inspectMaps = turnstoreTrayItemDao.getInspectDataBySectionNos(sectionItems);
//                //根据炉次号列表查询排程信息
//                List<SapProductionSchedule> sapProductionSchedules= sapProductionScheduleDao.getByLotNoList(lotNos);
//                for(TurnstoreOutItem turnstoreOutItem:items){
//                    MesToWmsDto entity = new MesToWmsDto();
//                    for(SapSectionMaterialNumber sapSectionMaterialNumber:sapSectionMaterialNumberList){
//                        if(sapSectionMaterialNumber.getSectionNo().equals(turnstoreOutItem.getSectionNo())){
//                            entity.setMaterialCode(sapSectionMaterialNumber.getNewMaterialNumber());//料号
//                            break;
//                        }
//                    }
//                    if(entity.getMaterialCode()==null){
//                        entity.setMaterialCode(SapStaticEnum.SapStaticValue.无法确定的料号.getValue());//料号
//                    }
//                    entity.setSectionNo(turnstoreOutItem.getSectionNo());//晶段编号
//                    for(Map<String,Object> trayMap:turnstoreTrayItemMaps){
//                        if(trayMap.get("section_no").equals(turnstoreOutItem.getSectionNo())){
//                            if(trayMap.get("tray_no")!=null){
//                                entity.setTrayNo(trayMap.get("tray_no").toString());//托盘号
//                                break;
//                            }
//                        }
//                    }
//                    if(entity.getTrayNo()==null){
//                        entity.setTrayNo(SapStaticEnum.WmsStaticValue.无法确定的托盘号.getValue());//托盘号
//                    }
//                    if(turnstoreOutItem.getProductTypeSecond()!=null&&turnstoreOutItem.getProductTypeSecond().length()>=4){
//                        entity.setConductiveType(turnstoreOutItem.getProductTypeSecond().substring(0,1));//导电型号
//                        entity.setSpecification(turnstoreOutItem.getProductTypeSecond().substring(2));//产品规格
//                    }else{
//                        entity.setConductiveType("P");//导电型号
//                        entity.setSpecification("");//产品规格
//                    }
//                    entity.setFactory(SapStaticEnum.WmsStaticValue.WMS工厂字段.getValue());//工厂
//                    entity.setStore(SapStaticEnum.WmsStaticValue.WMS库存地点字段.getValue());//库存地点
//                    //实际称重
//                    entity.setActualWeight(turnstoreOutItem.getActualWeight()==null?"0":turnstoreOutItem.getActualWeight().toString());
//                    //理论重量
//                    entity.setTheoryWeight(turnstoreOutItem.getInstoreWeight()==null?"0.000":turnstoreOutItem.getInstoreWeight().toString());
//                    //入库长度
//                    entity.setWareHouseLength(turnstoreOutItem.getInstoreLength()==null?"0":turnstoreOutItem.getInstoreLength().toString());
//                    //硅棒总长
//                    entity.setLength(turnstoreOutItem.getActualLength()==null?"0":turnstoreOutItem.getActualLength().toString());
//                    //客户类别（产品等级）
//                    entity.setCustomer(turnstoreOutItem.getProductLevelSecond());
//                    //备注（圆棒检验表外观检验备注） 崩边长度
//                    for(Map<String,Object> inspectMap:inspectMaps){
//                        if(inspectMap.get("section_no").equals(turnstoreOutItem.getSectionNo())){
//                            //备注
//                            entity.setRemark(inspectMap.get("remark")==null?"":inspectMap.get("remark").toString());
//                            //崩边长度
//                            entity.setEdgeBark(inspectMap.get("edge_bark")==null?"":inspectMap.get("edge_bark").toString());
//                            //崩晶线
//                            entity.setCollapseLine(inspectMap.get("collapse_line")==null?"":inspectMap.get("collapse_line").toString());
//                            //斜
//                            String xie = "";
//                            if(inspectMap.get("slopet")!=null){
//                                if(new BigDecimal(inspectMap.get("slopet").toString()).compareTo(new BigDecimal(0))>0){
//                                    xie +="T"+inspectMap.get("slopet").toString()+" ";
//                                }
//
//                            }
//                            if(inspectMap.get("slopew")!=null){
//                                if(new BigDecimal(inspectMap.get("slopew").toString()).compareTo(new BigDecimal(0))>0){
//                                    xie +=" W"+inspectMap.get("slopew").toString();
//                                }
//                            }
//                            entity.setSlope(xie);
//                            //细总长
//                            entity.setFineDiameter(inspectMap.get("fine_diameter")==null?"":inspectMap.get("fine_diameter").toString());
//                            //细减长
//                            entity.setFineCutLength(inspectMap.get("fine_cut_length")==null?"":inspectMap.get("fine_cut_length").toString());
//                            //扭
//                            String distortionBig = "否";
//                            if(inspectMap.get("distortion_big")!=null&&inspectMap.get("distortion_big").equals(true)){
//                                distortionBig= "是";
//                            }
//                            entity.setDistortion(distortionBig);
//                            //棒寿命分档(少子寿命最大最小值)
//                            List<BigDecimal> arr = new ArrayList<>();
//                            if(inspectMap.get("sinton_head1")!=null){
//                                arr.add(new BigDecimal(inspectMap.get("sinton_head1").toString()));
//                            }
//                            if(inspectMap.get("sinton_head2")!=null){
//                                arr.add(new BigDecimal(inspectMap.get("sinton_head2").toString()));
//                            }
//                            if(inspectMap.get("sinton_tail1")!=null){
//                                arr.add(new BigDecimal(inspectMap.get("sinton_tail1").toString()));
//                            }
//                            if(inspectMap.get("sinton_tail2")!=null){
//                                arr.add(new BigDecimal(inspectMap.get("sinton_tail2").toString()));
//                            }
//                            Collections.sort(arr);
//                            String sintonLife ="";
//                            if(arr.size()==1){
//                                sintonLife = arr.get(0).toString()+"-"+arr.get(0).toString();
//                            }else if(arr.size()>1){
//                                sintonLife = arr.get(0).toString()+"-"+arr.get(arr.size()-1).toString();
//                            }
//                            entity.setSintonLife(sintonLife);
//                            //异常
//                            entity.setException(inspectMap.get("remark")==null?"":inspectMap.get("remark").toString());
//                            break;
//                        }
//                    }
//                    if(entity.getRemark()==null){
//                        entity.setRemark("");
//                    }
//                    if(entity.getEdgeBark()==null){
//                        entity.setEdgeBark("");
//                    }
//                    if(entity.getCollapseLine()==null){
//                        entity.setCollapseLine("");
//                    }
//
//                    if(entity.getSlope()==null){
//                        entity.setSlope("");
//                    }
//
//                    if(entity.getFineDiameter()==null){
//                        entity.setFineDiameter("");
//                    }
//
//                    if(entity.getFineCutLength()==null){
//                        entity.setFineCutLength("");
//                    }
//
//                    if(entity.getDistortion()==null){
//                        entity.setDistortion("否");
//                    }
//
//                    if(entity.getSintonLife()==null){
//                        entity.setSintonLife("");
//                    }
//
//                    if(entity.getException()==null){
//                        entity.setException("");
//                    }
//
//                    //炉次号
//                    String lotNo = null;
//                    if(turnstoreOutItem.getSectionNo().length()>=17){
//                        //炉次号
//                        lotNo = turnstoreOutItem.getSectionNo().substring(7,16);
//                    }
//                    //根据炉次号匹配订单客户与订单号中的料号
//                    for(SapProductionSchedule sapProductionScheduleEntity:sapProductionSchedules){
//                        if(lotNo!=null&&lotNo.equals(sapProductionScheduleEntity.getLotNo())){
//                            //客户
//                            //entity.setCustomer(sapProductionScheduleEntity.getCustomer()==null?"":sapProductionScheduleEntity.getCustomer());
//                            //SAP订单号
//                            entity.setOrderNO(sapProductionScheduleEntity.getOrderNo()==null?"":sapProductionScheduleEntity.getOrderNo());
//                            break;
//                        }
//                    }
//                    if(entity.getCustomer()==null){
//                        entity.setRemark("");
//                    }
//                    if(entity.getOrderNO()==null){
//                        entity.setOrderNO("");
//                    }
//                    //entity.setBatchNo(orderNo);//批次信息
//                    entity.setOldSectionNo("");//旧编号
//                    entity.setOldMaterialCode("");//旧物料编码
//                    entity.setOldBatchNo("");//旧批次信息
//                    entity.setOldTrayNo("");//旧托盘信息
//                    entity.setSectionType("1");//圆棒信息
//                    list.add(entity);
//                }
//                if(list.size()>0){
//                    //更改检验工序的在制状态,出库到WMS,status=2
//                    turnstoreTrayItemDao.updateBySectionNos(sectionItems);
//                    PostToZWYWMS.post(list);
//                }
//
//            }catch (Exception e){
//                logger.error(e.getMessage());
//                throw new RuntimeException(e.getMessage());
//            }
            //endregion
        } else {
            //退料到圆棒等待确认,出库到方棒等待确认
            turnstoreDao.updateStoreTrayStatus(sectionItems, EnumValues.OutState.待出库.getValue());
        }
        //turnstoreDao.deleteBySectionNo(sectionItems);
    }

    @Override
    public void updateOut(TurnstoreOut turnstoreOut, List<TurnstoreOutItem> items) {
        checkSectionNosOut(items);
        Date now = new Date();
        turnstoreOut.setTime(now);
        turnstoreOut.setCount(items.size());
        turnstoreOut.setState(EnumValues.OutState.待出库.getValue());
        dao.save(turnstoreOut);
        //获取原来的出库明细
        List<TurnstoreOutItem> orgList = itemDao.getItemsByOutId(turnstoreOut.getId());
        //编辑之前的出库单晶编号列表
        List<String> orgSectionNoList = orgList.stream().map(TurnstoreOutItem::getSectionNo).collect(Collectors.toList());
        //更新库存表 原来的单晶状态为 未组拖
        turnstoreDao.updateStoreTrayStatus(orgSectionNoList, EnumValues.OutState.未组拖.getValue());
        //删除原来的出库记录
        itemDao.deleteByOutId(turnstoreOut.getId());
        //从检验表查询检验人、复检类型信息
        List<String> sectionItems = items.stream().map(TurnstoreOutItem::getSectionNo).collect(Collectors.toList());
        List<Map<String,Object>> inspectInfoMap = dao.getInspectBySectionNos(sectionItems);
        //set冗余字段
        for (TurnstoreOutItem turnstoreOutItem : items) {
            turnstoreOutItem.setId(null);
            //主表ID
            turnstoreOutItem.setOutId(turnstoreOut.getId());
            turnstoreOutItem.setType(turnstoreOut.getType());
            turnstoreOutItem.setState(turnstoreOut.getState());
            turnstoreOutItem.setOrderNo(turnstoreOut.getOrderNo());
            turnstoreOutItem.setUser(turnstoreOut.getUser());
            turnstoreOutItem.setTime(now);
            turnstoreOutItem.setLocationName("周转库");
            turnstoreOutItem.setHasGone(turnstoreOut.getHasGone());
            //出库记录增加检验人 、复检信息
            for(Map<String,Object> map:inspectInfoMap){
                if(map.get("sectionNo")!=null&&StringUtils.isNotBlank(map.get("sectionNo").toString())){
                    String sectionNo = map.get("sectionNo").toString();
                    if(turnstoreOutItem.getSectionNo().trim().equalsIgnoreCase(sectionNo)){
                        turnstoreOutItem.setInspectUser(map.get("inspector")==null?"":map.get("inspector").toString());
                        turnstoreOutItem.setReCheckType(map.get("reCheckType")==null?"":map.get("reCheckType").toString());
                        continue;
                    }
                }
            }
        }
        itemDao.saveAll(items);
        //更新周转库状态为待出库
        //List<Turnstore> turnstoreList = fromDto(items);
        //List<String> sectionItems = turnstoreList.stream().map(Turnstore::getSectionNo).collect(Collectors.toList());
        turnstoreDao.updateStoreTrayStatus(sectionItems, EnumValues.OutState.待出库.getValue());

    }

    @Override
    public void deleteOut(Integer id) {
        TurnstoreOut entity = dao.getOne(id);
        if (entity == null) {
            throw new RuntimeException("此出库申请单不存在");
        }
        if (entity.getState().equals(EnumValues.OutState.已出库.getValue())) {
            throw new RuntimeException("已出库申请单不能删除");
        }
        //更新周转库状态为未组拖
        List<TurnstoreOutItem> outItems = itemDao.getItemsByOutId(id);
        List<Turnstore> turnstoreList = fromDto(outItems);
        List<String> sectionItems = turnstoreList.stream().map(Turnstore::getSectionNo).collect(Collectors.toList());
        turnstoreDao.updateStoreTrayStatus(sectionItems, EnumValues.OutState.未组拖.getValue());
        itemDao.deleteByOutId(id);
        dao.delete(entity);

    }

    @Override
    public void backOut(Integer id, String userName) {
        TurnstoreOut entity = dao.getOne(id);
        if (entity == null) {
            throw new RuntimeException("此出库申请单不存在");
        }
        if (entity.getState().equals(EnumValues.OutState.已出库.getValue())) {
            throw new RuntimeException("已出库申请单不能退回");
        }
        entity.setState(EnumValues.InState.退回.getValue());
        entity.setConfirmUser(userName);
        dao.save(entity);
        //更新周转库状态为未组拖
        List<TurnstoreOutItem> outItems = itemDao.getItemsByOutId(id);
        List<Turnstore> turnstoreList = fromDto(outItems);
        List<String> sectionItems = turnstoreList.stream().map(Turnstore::getSectionNo).collect(Collectors.toList());
        turnstoreDao.updateStoreTrayStatus(sectionItems, EnumValues.OutState.未组拖.getValue());
        //更新明细为未组拖
        for (TurnstoreOutItem turnstoreOutItem : outItems) {
            turnstoreOutItem.setState(EnumValues.OutState.未组拖.getValue());
            turnstoreOutItem.setConfirmUser(userName);
        }
        itemDao.saveAll(outItems);
    }

    @Override
    public void confirmOut(Integer id, String userName) {
        TurnstoreOut entity = dao.getOne(id);
        if (entity == null) {
            throw new RuntimeException("此出库申请单不存在");
        }
        if (!entity.getState().equals(EnumValues.OutState.待出库.getValue())) {
            throw new RuntimeException("只有待出库的申请单可以确认");
        }
        List<TurnstoreOutItem> outItems = itemDao.getItemsByOutId(id);
        if (outItems == null || outItems.size() == 0) {
            throw new RuntimeException("此出库申请单明细错误");
        }
        checkSectionNosOut(outItems);
        entity.setState(EnumValues.OutState.已出库.getValue());
        entity.setConfirmUser(userName);
        dao.save(entity);

        List<String> sectionItems = outItems.stream().map(TurnstoreOutItem::getSectionNo).collect(Collectors.toList());
        List<Map<String,Object>> inspectInfoMap = dao.getInfoBySectionNos(sectionItems);
        for (TurnstoreOutItem turnstoreOutItem : outItems) {
            turnstoreOutItem.setTime(new Date());
            turnstoreOutItem.setConfirmUser(userName);
            turnstoreOutItem.setState(EnumValues.OutState.已出库.getValue());
            //出库记录增加检验人 、复检信息
            for(Map<String,Object> map:inspectInfoMap){
                if(map.get("sectionNo")!=null&&StringUtils.isNotBlank(map.get("sectionNo").toString())){
                    String sectionNo = map.get("sectionNo").toString();
                    if(turnstoreOutItem.getSectionNo().trim().equalsIgnoreCase(sectionNo)){
                        turnstoreOutItem.setRemark(map.get("remark")==null?null:map.get("remark").toString());
                        turnstoreOutItem.setFineDiameter(map.get("fineDiameter")==null?null:new BigDecimal(map.get("fineDiameter").toString()));
                        break;
                    }
                }
            }

        }
        itemDao.saveAll(outItems);
        //周转库删除单晶
        turnstoreDao.deleteBySectionNo(sectionItems);
        //退料到圆棒 标记为复检单晶
        if (entity.getType().equals(EnumValues.OutType.退料到圆棒.getValue())) {
            List<TurnstoreInItem> checkList = turnstoreInItemDao.getWmsBackBySectionNoAndType(sectionItems);
            if (checkList != null && checkList.size() > 0) {
                List<String> updateSectionNoList = new ArrayList<>();
                for (TurnstoreInItem turnstoreInItem : checkList) {
                    if (StringUtils.isNotBlank(turnstoreInItem.getSectionNo())) {
                        updateSectionNoList.add(turnstoreInItem.getSectionNo());
                    }
                }
                if (updateSectionNoList.size() > 0) {
                    turnstoreDao.updateReCheckTypeBySectionNos(updateSectionNoList);


                }
            }
            turnstoreDao.updateWipStateBySnIn(sectionItems, "WIP_Y");
            //turnstoreDao.updateReCheckTypeBySectionNos(sectionItems);
        }

      /*  //出库到方棒 写入圆棒GR表
        if (entity.getType().equals(EnumValues.OutType.出库到方棒.getKey())) {
            if (sectionItems != null && sectionItems.size() > 0) {
                setGr(sectionItems, outItems);
            }
        }
        //出库到方棒或者综计 写入复检Gi表
        if (entity.getType().equals(EnumValues.OutType.出库到方棒.getKey())||
                entity.getType().equals(EnumValues.OutType.出库到综计.getKey())) {
            if (sectionItems != null && sectionItems.size() > 0) {
                setReCheckGi(sectionItems,outItems);
            }
        }*/

      /*  //出库到方棒，将单晶信息存入方棒系统结存表
        if (entity.getType().equals(EnumValues.OutType.出库到方棒.getKey())) {
            List<CrystalBalance> crystalBalanceList = new ArrayList<>();
            for (TurnstoreOutItem outItem : outItems) {
                if (StringUtils.isNotBlank(outItem.getSectionNo())) {
                    CrystalBalance crystalBalance = new CrystalBalance();
                    crystalBalance.setNo(null);
                    crystalBalance.setGetTime(new Date());
                    crystalBalance.setGetBatchNo(outItem.getOrderNo());
                    crystalBalance.setCrystalNo(outItem.getSectionNo());//单晶条码编号
                    crystalBalance.setProductType(outItem.getProductTypeSecond());//产品类型
                    crystalBalance.setProductGrade(outItem.getProductLevelSecond());//产品等级
                    String electricType = "";
                    String crystalDiameter = "0.00";
                    if (StringUtils.isNotBlank(outItem.getProductTypeSecond())) {
                        if (outItem.getProductTypeSecond().contains("-")) {
                            String[] strings = outItem.getProductTypeSecond().split("-");
                            if (strings.length > 0) electricType = strings[0];
                            if (strings.length > 1) crystalDiameter = strings[1];
                        }
                    }
                    crystalBalance.setElectricType(electricType);//导电型号
                    crystalBalance.setCrystalDiameter(new BigDecimal(crystalDiameter));//单晶直径
                    crystalBalance.setLength(outItem.getInstoreLength());//圆棒入库长度（mm）
                    crystalBalance.setWeight(outItem.getActualWeight());//称重(kg)"
                    crystalBalance.setTheoreticalWeight(outItem.getInstoreWeight());//理论重量(kg)
                    crystalBalance.setSegmentType(outItem.getSectionType());//晶段类型
                    crystalBalance.setWhereabouts(outItem.getHasGone());//去向
                    crystalBalance.setFineDiameter(null);//细总长
                    crystalBalance.setFineCutLength(outItem.getFineCutLength());//细减长
                    crystalBalanceList.add(crystalBalance);
                }
            }
            crystalBalanceService.saveAll(crystalBalanceList);
        }*/
    }

    private void saveCrystalContence(List<TurnstoreOutItem> outItems, String orderNo) {
        try {
            List<JSONObject> jsonObjectList = new ArrayList<>();
            for (TurnstoreOutItem outItem : outItems) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("getBatchNo", outItem.getOrderNo());
                jsonObject.put("crystalNo", outItem.getSectionNo());//单晶条码编号
                jsonObject.put("productType", outItem.getProductTypeSecond());//产品类型
                jsonObject.put("productGrade", outItem.getProductLevelSecond());//产品等级
                String electricType = "";
                String crystalDiameter = "";
                if (StringUtils.isNotBlank(outItem.getProductTypeSecond())) {
                    if (outItem.getProductTypeSecond().contains("-")) {
                        String[] strings = outItem.getProductTypeSecond().split("-");
                        if (strings.length > 0) {
                            electricType = strings[0];
                        }
                        if (strings.length > 1) {
                            crystalDiameter = strings[1];
                        }
                    }
                }
                jsonObject.put("electricType", electricType);//导电型号
                jsonObject.put("crystalDiameter", crystalDiameter);//单晶直径
                jsonObject.put("length", outItem.getInstoreLength());//圆棒入库长度（mm）
                jsonObject.put("weight", outItem.getActualWeight());//称重(kg)"
                jsonObject.put("theoreticalWeight", outItem.getInstoreWeight());//理论重量(kg)
                jsonObject.put("segmentType", outItem.getSectionType());//晶段类型
                jsonObject.put("whereabouts", outItem.getHasGone());//去向
                jsonObject.put("fineDiameter", "");//细总长
                jsonObject.put("fineCutLength", outItem.getFineCutLength());//细减长

                jsonObject.put("collapseLine", outItem.getCollapseLine());//崩晶线
                jsonObjectList.add(jsonObject);
            }
            String params = JSONObject.toJSONString(jsonObjectList);
//                                 HTTPRequestUtil.post("http://192.168.10.208:8780/CrystalBalance/saveCrystalBalance",params);
//        String post = HTTPRequestUtil.post("http://47.99.105.168:4040/CrystalBalance/saveCrystalBalance", params);
            String post = HttpUtil.post("http://10.190.212.4:81/CrystalBalance/saveCrystalBalance", params);
            System.out.println(post);

        } catch (Exception e) {
            logger.error("将单晶数据存储到方棒结存表失败：出库单【" + orderNo + "】");
            e.printStackTrace();
        }
    }

    @Override
    public void outBySectionNos(List<String> list) {
        try {
            //获取库存信息
            List<Turnstore> checkList = turnstoreDao.getStoreInfoBySectionNos(list);

            //不在周转库 直接返回
            if (checkList == null || checkList.size() == 0) {
                return;
            }
            //删除待出库的记录
            for (String str : list) {
                itemDao.deleteBySectionNo(str);
            }
            List<TurnstoreOutItem> outItems = toDto(checkList);
            //新增出库记录
            for (TurnstoreOutItem turnstoreOutItem : outItems) {
                turnstoreOutItem.setId(null);
                turnstoreOutItem.setState(EnumValues.OutState.已出库.getValue());
                turnstoreOutItem.setType(EnumValues.OutType.出库到方棒.getValue());
                turnstoreOutItem.setUser("方棒AGV");
                turnstoreOutItem.setConfirmUser("方棒AGV");
                turnstoreOutItem.setTime(new Date());
                turnstoreOutItem.setOrderNo(null);
                TurnstoreOutItem toi = itemDao.getItems2SectionNoAndType(turnstoreOutItem.getSectionNo(), turnstoreOutItem.getType());
                if (Objects.nonNull(toi)) {
                    turnstoreOutItem.setTimes(toi.getTimes() + 1);
                }
            }
            itemDao.saveAll(outItems);
            //清除库存
            turnstoreDao.deleteBySectionNo(list);

            //出库到方棒，将单晶信息存如方棒系统结存表
            Thread thread = new Thread(() -> {
                saveCrystalContence(outItems, "");
            });
            thread.start();

        } catch (RuntimeException ex) {
            throw new RuntimeException("周转库出库失败");
        }
    }

    public List<Turnstore> fromDto(List<TurnstoreOutItem> dto) {
        //ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setFullTypeMatchingRequired(true);
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        List<Turnstore> listEntity = dto.stream().map(turnstore -> modelMapper.map(turnstore, Turnstore.class)).collect(Collectors.toList());
        return listEntity;
    }

    public List<TurnstoreOutItem> toDto(List<Turnstore> dto) {
        //ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setFullTypeMatchingRequired(true);
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
        List<TurnstoreOutItem> listEntity = dto.stream().map(turnstore -> modelMapper.map(turnstore, TurnstoreOutItem.class)).collect(Collectors.toList());
        return listEntity;
    }

   /* private void setGr(List<String> sectionItems, List<TurnstoreOutItem> outItems) {
        //turnstoreTrayService.reGetSapOrderNoNotRechcek(sectionItems);
        turnstoreTrayService.reGetSapOrderNo(sectionItems);
        List<Map<String, Object>> inspectList = sapGrService.getInspectBySectionNos(sectionItems);
        List<SapGr> sapGrCheckList = sapGrService.findBySectionnoIn(sectionItems);
        Date nowTime = new Date();
        List<SapSectionMaterialNumber> sapSectionMaterialNumberList = sapSectionMaterialNumberDao.getListBySectionList(sectionItems);
        List<SapGr> sapGrList = new ArrayList<>();
        for (TurnstoreOutItem turnstoreOutItem : outItems) {
            SapSectionMaterialNumber sapSectionMaterialNumber = sapSectionMaterialNumberList.stream().filter(o -> o.getSectionNo().trim().equalsIgnoreCase(turnstoreOutItem.getSectionNo().trim())).findAny().orElse(null);
//            if (sapSectionMaterialNumber != null && sapSectionMaterialNumber.getType() != null && sapSectionMaterialNumber.getType().equals(1)) {
                if (sapSectionMaterialNumber != null && sapSectionMaterialNumber.getType() != null) {
//                SapGr sapGrCheck = sapGrCheckList.stream().filter(o -> o.getSectionno().trim().equalsIgnoreCase(sapSectionMaterialNumber.getSectionNo().trim())).findAny().orElse(null);
                //未记产单晶报GR  //ZCC 2021-10-26 修改，全部都直接报GR
//                if (sapGrCheck == null) {
//                    String reCheckType = "";
//                    for (Map<String, Object> map : inspectList) {
//                        if (map.get("sectionNo").equals(turnstoreOutItem.getSectionNo())) {
//                            reCheckType = map.get("reCheckType") == null ? "" : map.get("reCheckType").toString();
//                            break;
//                        }
//                    }
//                    if (!reCheckType.equals("复检单晶")) {
                        SapGr sapGr = new SapGr();
                        sapGr.setZmesid(UUID.randomUUID().toString());
                        sapGr.setAufnr(sapSectionMaterialNumber.getSapOrderNo());//订单号
                        sapGr.setMatnr(sapSectionMaterialNumber.getNewMaterialNumber());//成品物料号
                        sapGr.setWerks(SapStaticEnum.SapFactoryId.三期工厂ID.getValue());
                        sapGr.setMeins("KG");//基本单位
                        sapGr.setMenge(turnstoreOutItem.getInstoreWeight());//入库重量 GR收货重量
                        sapGr.setCharg(SapStaticEnum.SapStaticValue.GI固定批次号.getValue());//批次号 虚拟
                        sapGr.setLgort(SapStaticEnum.SapStaticValue.圆棒GR固定库存地点.getValue());//固定库存地点 虚拟
                        sapGr.setBty("1");
                        sapGr.setCreatetime(nowTime);
                        sapGr.setIssend(0);
                        sapGr.setSectionno(turnstoreOutItem.getSectionNo());
                        sapGr.setGrdate(WbServiceUtils.getSapDate(nowTime));//日期 yyyymmdd
                        sapGr.setGrtime(WbServiceUtils.getSapTime(nowTime));//时间 HHmmss
                        sapGrList.add(sapGr);
//                    }
//                }
            }
        }
        if (sapGrList != null && sapGrList.size() > 0) {
            sapGrService.saveBatch(sapGrList);
        }
    }*/

    /*private void setReCheckGi(List<String> sectionItems, List<TurnstoreOutItem> outItems){
        Date nowTime = new Date();
//        List<SapReCheckGi> reCheckGis=new ArrayList<>();
        List<String> type=new ArrayList<>();
        type.add(EnumValues.InType.方棒退料.getKey());
        type.add(EnumValues.InType.综计退料.getKey());

        List<SapSectionMaterialNumber> sapSectionMaterialNumberList = sapSectionMaterialNumberDao.getListBySectionList(sectionItems);

        List<Map<String,Object>>itemCount= turnstoreInItemDao.groupCountBySectionNosAndTypeAndState(sectionItems,type,"已入库");
        for(TurnstoreOutItem item:outItems){
            for(Map<String,Object> map:itemCount){
                if(map.get("sectionNo")!=null&&StringUtils.isNotBlank(map.get("sectionNo").toString())){
                    String sectionNo = map.get("sectionNo").toString();
                    if(item.getSectionNo().trim().equalsIgnoreCase(sectionNo)&&Integer.valueOf(map.get("count").toString())>=1){
                        SapSectionMaterialNumber sapSectionMaterialNumber = sapSectionMaterialNumberList.stream().filter(o -> o.getSectionNo().trim().equalsIgnoreCase(item.getSectionNo().trim())).findAny().orElse(null);

                        *//*if(sapSectionMaterialNumber!=null){
                            String lastSecond = sectionNo.substring(sectionNo.length()-2,sectionNo.length()-1);

                            SapReCheckGi sapReCheckGi=new SapReCheckGi();
                            sapReCheckGi.setZmesid(UUID.randomUUID().toString());
                            sapReCheckGi.setSectionno(sectionNo);
                            sapReCheckGi.setFenduan(lastSecond.toUpperCase().equals("F")?1:0);
                            sapReCheckGi.setAufnr(sapSectionMaterialNumber.getSapOrderNo());//ZH04订单编号
                            sapReCheckGi.setBty("1");//新增
                            sapReCheckGi.setCharg(SapStaticEnum.SapStaticValue.GI固定批次号.getValue());//批次号 虚拟
                            sapReCheckGi.setIssuedate(WbServiceUtils.getSapDate(nowTime));//日期 yyyymmdd
                            sapReCheckGi.setIssuetime(WbServiceUtils.getSapTime(nowTime));//时间 HHmmss
                            sapReCheckGi.setMatnr(sapSectionMaterialNumber.getNewMaterialNumber());//新物料号
                            sapReCheckGi.setMeins("KG");//单位
                            sapReCheckGi.setMenge(sapSectionMaterialNumber.getWeight());
                            sapReCheckGi.setMatnrmat(sapSectionMaterialNumber.getOrgMaterialNumber());//旧物料号
                            sapReCheckGi.setSource("");
                            sapReCheckGi.setCreatetime(nowTime);
                            sapReCheckGi.setIssend(0);


                            sapReCheckGi.setWerks(SapStaticEnum.SapFactoryId.三期工厂ID.getValue());
                            sapReCheckGi.setLgort(SapStaticEnum.SapLgort.三期库位.getValue());
                            reCheckGis.add(sapReCheckGi);
                            break;
                        }*//*
                    }
                }
            }
        }
      *//*  if(!reCheckGis.isEmpty()){
           sapReCheckGiDao.saveAll(reCheckGis);
        }*//*
    }*/
}
