package com.sw.mes.sap.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.sw.mes.base.erp.entity.ErpOrder;
import com.sw.mes.base.erp.service.ErpOrderService;
import com.sw.mes.base.factory.material.entity.MaterialModel;
import com.sw.mes.base.factory.material.service.MaterialCleanModelService;
import com.sw.mes.base.factory.material.service.MaterialModelService;
import com.sw.mes.core.api.system.StoreFeignClients;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.erp.ErpAddResultDto;
import com.sw.mes.core.dto.erp.ErpRequestDto;
import com.sw.mes.core.entity.MesToErpCkdDetailEntity;
import com.sw.mes.core.entity.MesToErpCkdEntity;
import com.sw.mes.core.enums.ErpEnum;
import com.sw.mes.core.enums.ErpPypeEnum;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.core.utils.DateUtil;
import com.sw.mes.sap.dao.ReportErpInputRecordDao;
import com.sw.mes.sap.entity.ReportErpInputRecord;
import com.sw.mes.sap.entity.ReportErpInputRecordDetail;
import com.sw.mes.sap.service.ReportErpInputRecordDetailService;
import com.sw.mes.sap.service.ReportErpInputRecordService;
import com.sw.mes.third.utils.ErpRequestUtil;
import com.sw.mes.yb.plan.entity.ProductionOrder;
import com.sw.mes.yb.plan.service.ProductionOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@Service
@Transactional
public class ReportErpInputRecordServiceImpl extends BaseServiceImpl<ReportErpInputRecord> implements ReportErpInputRecordService {


    @Autowired
    private ReportErpInputRecordDetailService reportErpInputRecordDetailService;


    @Autowired
    private ProductionOrderService productionOrderService;

    @Autowired
    private MaterialModelService materialModelService;

    @Autowired
    private ErpOrderService erpOrderService;

    @Autowired
    private ErpRequestUtil erpRequestUtil;

    @Autowired
    private StoreFeignClients storeFeignClients;


    @Autowired
    private MaterialCleanModelService materialCleanModelService;


    @Value("${spring.erpServiceUrl}")
    private String erpServiceUrl;



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

    @Override
    public void pushToErp(ReportErpInputRecord dto) {
        //上报erp，将表里的状态改成已上报
        ErpRequestDto erpRequestDto = packageData(dto);
        ErpAddResultDto erpAddResultDto = erpRequestUtil.postToErp(erpRequestDto);
        if (null != erpAddResultDto) {
            if (null != erpAddResultDto.getErrcode() && erpAddResultDto.getErrcode().equals(String.valueOf(ResultCode.SUCCESS.getCode()))) {
                dto.setPushed(1);
                dto.setPushTime(new Date());
                dto.setPushUser(BaseContextHandler.getUsername());
                String cCode = erpAddResultDto.getCcode();
                dto.setCode(cCode);
                saveOrUpdate(dto);
                reportErpInputRecordDetailService.updateAll(dto.getId());
            } else {
                throw new BusinessException(erpAddResultDto.getErrmsg());
            }
        }
    }

    private ErpRequestDto packageData(ReportErpInputRecord dto) {
        ErpRequestDto erpRequestDto = new ErpRequestDto();
        erpRequestDto.setUrl(erpServiceUrl);

        List<ReportErpInputRecordDetail> list = reportErpInputRecordDetailService.findRecordDetail(dto.getId());

        MesToErpCkdEntity mesToErpCkdEntity = new MesToErpCkdEntity();
        String orderNo = dto.getOrderNo();
        ProductionOrder byeErpOrderNo = productionOrderService.findByeErpOrderNo(orderNo);
        if(byeErpOrderNo != null){
            String batchNo = "(" + ErpEnum.WorkShop.valueOf(byeErpOrderNo.getWorkShop()).getValue() + ")" + DateUtil.getFormatTime1(new Date()) + "/" + orderNo;

            //todo 批次号按样单拼接数据   目前拼接存在问题
            mesToErpCkdEntity.setCbatch(batchNo);
            //需根据方棒订单查到物料编号
            mesToErpCkdEntity.setCinvcode(byeErpOrderNo.getMatnr());
            //todo 订单id暂时不对
            mesToErpCkdEntity.setIproorderid(byeErpOrderNo.getTid());
            //部门编号  无问题（数据库已填充该数据）

            //mesToErpCkdEntity.setCdepcode(byeErpOrderNo.getDeptCode());
            //部门名称
            mesToErpCkdEntity.setCdepname(byeErpOrderNo.getWorkShop());
            mesToErpCkdEntity.setImquantity(String.valueOf(byeErpOrderNo.getMenge()));
            mesToErpCkdEntity.setCpspcode(byeErpOrderNo.getMatnr());

        }
        if(("一车间").equals(byeErpOrderNo.getWorkShop())){
            mesToErpCkdEntity.setCdepcode("1201");
            mesToErpCkdEntity.setCwhcode("014");
        } else if (("二车间").equals(byeErpOrderNo.getWorkShop())){
            mesToErpCkdEntity.setCdepcode("1206");
            mesToErpCkdEntity.setCwhcode("014");
        }else{
            mesToErpCkdEntity.setCdepcode("18");
            mesToErpCkdEntity.setCwhcode("014");
        }
        mesToErpCkdEntity.setCmpocode(orderNo);
        mesToErpCkdEntity.setErpType(ErpPypeEnum.单晶投入.getKey());
        mesToErpCkdEntity.setCrdcode("20108");
        // mesToErpCkdEntity.setCwhcode(dto.getWarehouseCode());

        mesToErpCkdEntity.setCwhname(String.valueOf(ErpEnum.WarehouseName.单晶原料库.getValue()));
        mesToErpCkdEntity.setIquantity(dto.getQuantity().toString());
        MaterialModel byCode = materialModelService.findByCode(byeErpOrderNo.getMatnr());
        mesToErpCkdEntity.setInvname(byCode.getName());
        mesToErpCkdEntity.setCinvstd(byCode.getSpecification());
        mesToErpCkdEntity.setImoseq(byCode.getUnit().getCode());
        mesToErpCkdEntity.setDocTime(dto.getCreateTime());

        //子件详情
        List<MesToErpCkdDetailEntity> mesToErpCkdDetailEntitys = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(list)){
            for(ReportErpInputRecordDetail detail:list){
                MesToErpCkdDetailEntity mesToErpCkdDetailEntity = new MesToErpCkdDetailEntity();
                String batchNo = detail.getErpBatchNo();
                mesToErpCkdDetailEntity.setInvname(byCode.getName());
                mesToErpCkdDetailEntity.setInvstd(byCode.getSpecification());
                MaterialModel byCode1 = materialModelService.findByCode(detail.getMaterialCode());
                if(null != byCode1.getMaterialType()){
                    mesToErpCkdDetailEntity.setCinvccode(byCode1.getMaterialType().getName());
                }
                //通过提供的表用料号 批次号 去查对应的关系
                String code = detail.getMaterialCode();
//                Result<StoreInputApplyDetailDto> result =  storeFeignClients.findStoreInputApplyDetail(detail.getBatchNo());
//                if(result.getCode().equals(ResultCode.SUCCESS.getCode())){
//                    StoreInputApplyDetailDto dto1 = result.getData();
//                    String batch = dto1.getErpBatchNo();
//                    if(StringUtils.isBlank(batch)){
//                        //截取删除最后四位再去查
//                        String batch1 = batchNo.substring(0, batchNo.length() - 4);
//                        PullErpWarehouseData data = pullErpWarehouseDataService.findData(batch1);
//                        if(data == null || !data.getCwhcode().equals("320")){
//                            continue;
//                        }
//                        mesToErpCkdDetailEntity.setCinvcode(data.getCinvcode());
//                        mesToErpCkdDetailEntity.setCbatch(data.getCbatch());
//
//                    }else{
//                        PullErpWarehouseData data = pullErpWarehouseDataService.findData(batch);
//                        if(data == null || !data.getCwhcode().equals("320")){
//                            continue;
//                        }
//                        mesToErpCkdDetailEntity.setCinvcode(data.getCinvcode());
//                        mesToErpCkdDetailEntity.setCbatch(data.getCbatch());
//                    }
//                }else{
//                    //截取删除最后四位再去查
//                    String batch1 = batchNo.substring(0, batchNo.length() - 4);
//                    PullErpWarehouseData data = pullErpWarehouseDataService.findData(batch1);
//                    if(data == null || !data.getCwhcode().equals("320")){
//                        continue;
//                    }
//                    mesToErpCkdDetailEntity.setCinvcode(data.getCinvcode());
//                    mesToErpCkdDetailEntity.setCbatch(data.getCbatch());
//                }
//                mesToErpCkdDetailEntity.setCinvcode(detail.getMaterialCode());
//                 mesToErpCkdDetailEntity.setCbatch(detail.getBatchNo());
//                String batch = "";
//                if(result.getCode().equals(ResultCode.SUCCESS.getCode())){
//                    StoreInputApplyDetailDto dto1 = result.getData();
//                     batch = dto1.getErpBatchNo();
//                    if(StringUtils.isBlank(batch)){
//                       batch =  batchNo.substring(0, batchNo.length() - 4);
//                    }
//                }else{
//                     batch = batchNo.substring(0, batchNo.length() - 4);
//
//                }
//                MaterialCleanModel materialCleanModel = materialCleanModelService.findByNameAndCode(detail.getMaterialName(),detail.getMaterialCode());
//                if(materialCleanModel == null){
//                    mesToErpCkdDetailEntity.setCinvcode(detail.getMaterialCode());
//                }else{
//                    mesToErpCkdDetailEntity.setCinvcode(materialCleanModel.getFinishedCode());
//                }
//                mesToErpCkdDetailEntity.setCinvcode(detail.getMaterialCode());
                mesToErpCkdDetailEntity.setCinvcode(code);
                mesToErpCkdDetailEntity.setCbatch(batchNo);
                mesToErpCkdDetailEntity.setCinvm_unit(byCode1.getUnit().getName());
                mesToErpCkdDetailEntity.setCinvname(byCode1.getName());
                mesToErpCkdDetailEntity.setCinvstd(byCode1.getSpecification());
                mesToErpCkdDetailEntity.setImoseq("1");
                ErpOrder erpOrder = new ErpOrder();
                List<ErpOrder> byModIdAndInCode1 = erpOrderService.findByModIdAndInvCode1(byeErpOrderNo.getModid(), byCode1.getMatnr());
                if(!CollectionUtils.isEmpty(byModIdAndInCode1)){
                    erpOrder = byModIdAndInCode1.get(0);
                }
                mesToErpCkdDetailEntity.setImpoids(String.valueOf(erpOrder.getComponentId()));
                mesToErpCkdDetailEntity.setInquantity(String.valueOf(erpOrder.getIssQty()));
                mesToErpCkdDetailEntity.setIquantity(detail.getWeight().toString());
                //默认0
                mesToErpCkdDetailEntity.setIorderdid(String.valueOf(erpOrder.getIorderdid()));
                //默认1
                mesToErpCkdDetailEntity.setIrowno(String.valueOf(erpOrder.getIrowno()));
                //默认1
                mesToErpCkdDetailEntity.setIpesoseq(String.valueOf(erpOrder.getIpesoseq()));
//                mesToErpCkdDetailEntity.setIpesodid();
//                mesToErpCkdDetailEntity.setBcanreplace();

//                mesToErpCkdDetailEntity.setCbatchproperty9();

                mesToErpCkdDetailEntitys.add(mesToErpCkdDetailEntity);
            }

        }

        mesToErpCkdEntity.setMesToErpCkdDetailEntitys(mesToErpCkdDetailEntitys);

        erpRequestDto.setMesToErpCkdEntity(mesToErpCkdEntity);
        return erpRequestDto;
    }

}
