package com.sw.mes.itemclean.clean.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sw.mes.core.api.system.YbFeignClients;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.erp.ErpAddResultDto;
import com.sw.mes.core.dto.ErpOrderDto;
import com.sw.mes.core.dto.erp.ErpRequestDto;
import com.sw.mes.core.dto.materialCleanDto.MaterialCleanModelDto;
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.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.core.utils.DateUtil;
import com.sw.mes.itemclean.clean.domain.MaterialPlanOrder;
import com.sw.mes.itemclean.clean.domain.ReportErpXlInputRecord;
import com.sw.mes.itemclean.clean.domain.ReportErpXlInputRecordDetail;
import com.sw.mes.itemclean.clean.mapper.ReportErpXlInputRecordMapper;
import com.sw.mes.itemclean.clean.service.MaterialPlanOrderService;
import com.sw.mes.itemclean.clean.service.ReportErpXlInputRecordDetailService;
import com.sw.mes.itemclean.clean.service.ReportErpXlInputRecordService;
import feign.Request;
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 java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@Service
public class ReportErpXlInputRecordServiceImpl extends ServiceImpl<ReportErpXlInputRecordMapper, ReportErpXlInputRecord> implements ReportErpXlInputRecordService {

    @Autowired
    private ReportErpXlInputRecordDetailService reportErpXlInputRecordDetailService;


    @Autowired
    private MaterialPlanOrderService materialPlanOrderService;

    @Autowired
    private YbFeignClients ybFeignClients;


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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pushToErp(ReportErpXlInputRecord dto) {
        //上报erp，将表里的状态改成已上报
        ErpRequestDto erpRequestDto = packageData(dto);
        Request.Options options = new Request.Options(60L, TimeUnit.SECONDS, 60L, TimeUnit.SECONDS, true);
        Result<ErpAddResultDto> result = ybFeignClients.postToErp(options,erpRequestDto);

        if(null == result || ResultCode.SUCCESS.getCode() != result.getCode()){
            throw new RuntimeException("循环料领料上报失败：" + JSONObject.toJSONString(result));
        }
        ErpAddResultDto erpAddResultDto = result.getData();
        if(null == erpAddResultDto || !erpAddResultDto.getErrcode().equals(String.valueOf(ResultCode.SUCCESS.getCode()))){
            log.error(erpAddResultDto.getErrmsg());
            throw new RuntimeException("循环料领料上报失败：" + JSONObject.toJSONString(erpAddResultDto.getErrmsg()));
        }

        dto.setPushed(1);
        dto.setPushTime(new Date());
        dto.setPushUser(BaseContextHandler.getUsername());
        dto.setErpCode(erpAddResultDto.getCcode());
        this.saveOrUpdate(dto);
        List<ReportErpXlInputRecordDetail> reportErpXlInputRecordDetails = reportErpXlInputRecordDetailService.findList(dto.getId());
        reportErpXlInputRecordDetails.stream().forEach(temp->temp.setPushed(1));
        reportErpXlInputRecordDetailService.saveOrUpdateBatch(reportErpXlInputRecordDetails);


    }

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

        List<ReportErpXlInputRecordDetail> list = reportErpXlInputRecordDetailService.findList(dto.getId());
        MesToErpCkdEntity mesToErpCkdEntity = new MesToErpCkdEntity();
        String code = dto.getCode();
        MaterialPlanOrder byeErpOrderNo = materialPlanOrderService.findByAufnr(code);
        if(byeErpOrderNo != null){
            String batchNo = "(" + ErpEnum.WorkShop.valueOf(byeErpOrderNo.getProductDepartment()).getValue() + ")" + DateUtil.getFormatTime1(new Date()) + "/" + code;

            //todo 批次号按样单拼接数据   目前拼接存在问题
            mesToErpCkdEntity.setCbatch(dto.getOrderNo());
            //需根据方棒订单查到物料编号
            mesToErpCkdEntity.setCinvcode(byeErpOrderNo.getMatnr());
            //todo 订单id暂时不对
            mesToErpCkdEntity.setIproorderid(byeErpOrderNo.getMoid());
            //部门编号  无问题（数据库已填充该数据）
            mesToErpCkdEntity.setCdepcode("1203");
            //部门名称
            mesToErpCkdEntity.setCdepname(byeErpOrderNo.getProductDepartment());
            mesToErpCkdEntity.setImquantity(String.valueOf(byeErpOrderNo.getPlanMenge()));
            mesToErpCkdEntity.setCpspcode(byeErpOrderNo.getMatnr());

        }
        mesToErpCkdEntity.setCmpocode(code);
        mesToErpCkdEntity.setErpType(ErpPypeEnum.料理投入.getKey());
        mesToErpCkdEntity.setCrdcode("20108");
        mesToErpCkdEntity.setCwhcode("013");
        mesToErpCkdEntity.setCwhname(String.valueOf(ErpEnum.WarehouseName.原料二车间.getValue()));
        mesToErpCkdEntity.setIquantity(dto.getQuantity().toString());
        mesToErpCkdEntity.setDocTime(dto.getCreateTime());
        Result<MaterialCleanModelDto> result = ybFeignClients.findMaterialCleanByCode(dto.getMaterialCode());
        MaterialCleanModelDto byCode = new MaterialCleanModelDto();
        if(result.getCode().equals(ResultCode.SUCCESS.getCode())){
             byCode= result.getData();
            mesToErpCkdEntity.setInvname(byCode.getName());
            mesToErpCkdEntity.setCinvstd(byCode.getSiliconType());
           // mesToErpCkdEntity.setImoseq();
        }



        //子件详情
        List<MesToErpCkdDetailEntity> mesToErpCkdDetailEntitys = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(list)) {
            for (ReportErpXlInputRecordDetail detail : list) {
                MesToErpCkdDetailEntity mesToErpCkdDetailEntity = new MesToErpCkdDetailEntity();
                mesToErpCkdDetailEntity.setInvname(byCode.getName());
                mesToErpCkdDetailEntity.setInvstd(byCode.getSiliconType());
                Result<MaterialCleanModelDto> result1 = ybFeignClients.findMaterialCleanByCode(detail.getMaterialCode());
                MaterialCleanModelDto byCode1 = new MaterialCleanModelDto();
                if(result1.getCode().equals(ResultCode.SUCCESS.getCode())){
                    byCode1 = result1.getData();
                }
                mesToErpCkdDetailEntity.setCinvccode(byCode1.getSiliconType());

                mesToErpCkdDetailEntity.setCinvcode(byCode1.getCode());
              //  mesToErpCkdDetailEntity.setCinvm_unit(byCode1.getUnit().getName());
                mesToErpCkdDetailEntity.setCinvname(byCode1.getName());
                mesToErpCkdDetailEntity.setCinvstd(byCode1.getSiliconType());
                mesToErpCkdDetailEntity.setImoseq("1");
                ErpOrderDto erpOrder = new ErpOrderDto();
                Result<List<ErpOrderDto>> result2 = ybFeignClients.findOrderByModIdAndInvCode(byeErpOrderNo.getModid(),byCode1.getCode());
               // List<ErpOrder> byModIdAndInCode1 = erpOrderService.findByModIdAndInvCode1(byeErpOrderNo.getModid(), byCode1.getMatnr());
                if(result2.getCode().equals(ResultCode.SUCCESS)){
                    List<ErpOrderDto> dtos = result2.getData();
                    erpOrder = dtos.get(0);
                }
                mesToErpCkdDetailEntity.setImpoids(String.valueOf(erpOrder.getComponentId()));
                mesToErpCkdDetailEntity.setInquantity(String.valueOf(erpOrder.getIssQty()));
                mesToErpCkdDetailEntity.setIquantity(detail.getWeight().toString());
                //mesToErpCkdDetailEntity.setIquantity(String.valueOf(erpOrder.getAuxQty()));
                //默认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.setCbatch(detail.getBatchNo());
//                mesToErpCkdDetailEntity.setCbatchproperty9();
                mesToErpCkdDetailEntitys.add(mesToErpCkdDetailEntity);

            }
        }

        mesToErpCkdEntity.setMesToErpCkdDetailEntitys(mesToErpCkdDetailEntitys);
        erpRequestDto.setMesToErpCkdEntity(mesToErpCkdEntity);
        return erpRequestDto;
    }
}
