package com.sifang.modules.htySap.service;

import com.google.gson.Gson;
import com.sifang.modules.htySap.utils.SapOrderUtils;
import com.sifang.modules.htySap.vo.*;
import com.sifang.modules.platform.utils.PlantformUtils;
import com.sifang.modules.sunshine.SystemSetting.dao.TraderDao;
import com.sifang.modules.supply.order.constant.DeliverOrderConstants;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrder;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrderDetail;
import com.sifang.modules.supply.setting.dao.CrmSupplyWarehouseDao;
import com.sifang.modules.supply.setting.entity.CrmSupplyWarehouse;
import com.sifang.modules.sys.common.utils.DateUtils;
import com.sifang.modules.sys.common.utils.IdGen;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * SAP采购申请Service  暂不使用
 */
@Service
public class SapProcureApplyService {

    Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private TraderDao traderDao;

    @Autowired
    private CrmSupplyWarehouseDao supplyWarehouseDao;



    /**
     * 新增采购申请--13 OA-SAP新增采购申请同步接口
    */
    public void addProcureApplyList(List<ProcureApplyOrderVo> list){
     /*   req.setBSART(ProcureConstant.TYPE_BSART);
        req.setEKGRP(ProcureConstant.EKGRP);
        req.setMEINS(ProcureConstant.MEINS);
        req.setZZSQBM(ProcureConstant.ZZSQBM);
        req.setMATKL(ProcureConstant.MATKL);
        req.setWERKS(ProcureConstant.WERKS);
        req.setKNTTP(ProcureConstant.KNTTP);
        req.setZZZJLY(ProcureConstant.ZZZJLY);
        req.setPS_PSP_PNR(ProcureConstant.PS_PSP_PNR);
        req.setPREIS("0.01");//评估价格
        //  req.setMATNR("1212000004686");
        // req.setTXZ01("LCPV-900HFPOL偏贴后自动除泡机（反）");
        // req.setEKORG("ORG1");
        //req.setZZXMMC("LCPV-900HFPOL偏贴后自动除泡机（反）");
        List<ProcureApplyOrderVo> list = Lists.newArrayList();
        list.add(req);*/

        Gson gson=new Gson();
        String gsonStr=gson.toJson(list);
        System.out.println(gsonStr);
        try {
            SapOrderUtils.clientPostSap(gsonStr,"/cgsqtb","");
        }catch (Exception e){
            throw new RuntimeException("接口同步失败");
        }

    }


    /**
     * 采购申请同步接口 -- 5 SAP-SRM采购申请同步接口
    */
    public void ProcureApplyTb(CgsqcsReq req){
        Gson gson=new Gson();
        String gsonStr=gson.toJson(req);
        System.out.println(gsonStr);
        try {
            Map<String,String> reqmap= SapOrderUtils.clientPostSap(gsonStr,"/cgsqcs","");
            //
            if("S".equals(reqmap.get("EV_TYPE"))){
                //数据查询成功


            }


        }catch (Exception e){
            throw new RuntimeException("接口同步失败");
        }
    }

    /**
     *  15 OA-SAP发货申请单接口(备货申请)
    */
    public void sendOutGoodsApplyOrder(FhsqReq req){
        Gson gson=new Gson();
        String gsonStr=gson.toJson(req);
        System.out.println(gsonStr);
        try {
            SapOrderUtils.clientPostSap(gsonStr,"/cgsqtb","");
        }catch (Exception e){
            throw new RuntimeException("接口同步失败");
        }
    }

    /**
     * WMS->SAP货物移动同步接口 27-----------发货/入库
     * type="out" 出库
     * type="in"  入库
     */
    public void outInWarehouse(String type,CrmSupplyMaterialDeliverOrder order, List<CrmSupplyMaterialDeliverOrderDetail> details){
        logger.info(">>>货物移动同步接口 sap outInWarehouse orderId:{},type:{}",order.getId(),type);
        HwydReq req=new HwydReq();
        HwydReq.Head head=new HwydReq.Head();
        head.setBudat(DateUtils.getDate("yyyyMMdd"));
        head.setBldat(DateUtils.getDate("yyyyMMdd"));
        String remarks="越秀户用项目"+DateUtils.getDate("MM");
        String moveType="";
        CrmSupplyWarehouse warehouse;
        if("out".equals(type)){ //出库
            warehouse=supplyWarehouseDao.get(order.getOutWarehouseId());
            remarks=remarks+"发货";
            moveType="221";
        }else if("in".equals(type)){
            warehouse=supplyWarehouseDao.get(order.getInWarehouseId());
            remarks=remarks+"收货";
            moveType="101";
        }
        head.setBktxt(remarks);

        List<HwydReq.Line> lines=new ArrayList<>();
        for(CrmSupplyMaterialDeliverOrderDetail detail:details){
            HwydReq.Line line=new HwydReq.Line();
            line.setMatnr18(detail.getMaterialCode());
            line.setWerksD(""); //工厂
            line.setLgortD(""); //存储地点
            if ("out".equals(type)){
               line.setErfmg(String.valueOf(detail.getOutAmount()));
            }else{
                line.setErfmg(String.valueOf(detail.getInAmount()));
            }
            line.setBwart(moveType);
            line.setErfme(detail.getUnitCode());  //物料单位
//            line.setChargD(detail.getPcCode());//批次编号
            line.setBstnr(""); //采购订单号
            line.setEbelp("");//采购凭证的项目编号
            lines.add(line);
        }

        List<HwydReq.Head> heads=new ArrayList<>();
        heads.add(head);
        req.setHead(heads);
        req.setLine(lines);
        Gson gson=new Gson();
        String gsonStr=gson.toJson(req);
        logger.info(">>>货物移动同步接口 sap outInWarehouse json:{}",gsonStr);
        try {
            SapOrderUtils.clientPostSap(gsonStr,"/hwyd",order.getNumber());
        }catch (Exception e){
            logger.error(">>>>>货物移动同步接口 outInWarehouse  e:{}",e);
        }

    }

    /**
     * 采购订单同步---32 SAP->WMS采购订单信息同步接口
     * 当SAP生成采购订单或者采购订单信息发生修改后，将SAP采购订单信息同步至WMS.
    */
    public void procureApplyOrderTb(CgddtbReq req){
        Gson gson=new Gson();
        String gsonStr=gson.toJson(req);
        System.out.println(gsonStr);
        try {
            Map<String,String> reqmap= SapOrderUtils.clientPostSap(gsonStr,"/cgsqcs","");
            //


        }catch (Exception e){
            throw new RuntimeException("接口同步失败");
        }
    }


    /**
     * 待签收订单同步
    */
    public void signForOrder(DbwlbzReq req){
        Gson gson=new Gson();
        String gsonStr=gson.toJson(req);
        System.out.println(gsonStr);
        try {
            Map<String,String> reqmap= SapOrderUtils.clientPostSap(gsonStr,"/cgsqcs","");
            //插入待签收订单
            CrmSupplyMaterialDeliverOrder deliverOrder = new CrmSupplyMaterialDeliverOrder();
            deliverOrder.setId(IdGen.uuid());
            deliverOrder.setType("5");//SAP同步订单
            deliverOrder.setNumber(PlantformUtils.findOrderNumber("SAP"));
            deliverOrder.setRelateNo(reqmap.get("ZSDT0020"));
            deliverOrder.setApplyOrderId("");
            deliverOrder.setProjectCode(reqmap.get("PRPS"));
            //发货工厂
            deliverOrder.setOutWarehouseId("");
            //收货工厂
            deliverOrder.setInWarehouseId("");
            deliverOrder.setRemarks("");
            deliverOrder.setDeliverId("a");
            deliverOrder.setDeliverName("供应链");

            deliverOrder.setPlaceBy("a");
            deliverOrder.setPlaceName("供应链");

            deliverOrder.setPlaceTime(new Date());

            BigDecimal totalAmount = new BigDecimal(reqmap.get("ERFMG"));
          /*  for (AddSupplierOrderDetailReq detailReq : req.getDetails()) {
                totalAmount = totalAmount.add(detailReq.getAmount());
            }*/
            deliverOrder.setMaterialTypeAmount(BigDecimal.valueOf(1));
            deliverOrder.setTotalApplyAmount(totalAmount);
            deliverOrder.setTotalDeliverAmount(BigDecimal.ZERO);

            deliverOrder.setCreateBy("a");
            deliverOrder.setCreator("定时任务");
            deliverOrder.setCreateTime(new Date());
            deliverOrder.setStatus(DeliverOrderConstants.STATUS_WAIT_SIGN_IN);
            deliverOrder.setSendStatus("2");
          //  deliverDao.save(deliverOrder);

            List<CrmSupplyMaterialDeliverOrderDetail> details = new ArrayList<>();
            int i = 0;
            Set<String> materialSet = new HashSet<>();
          //  for (AddSupplierOrderDetailReq detailReq : detailReqs) {
             //   if (detailReq.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
              //      throw new BusinessException("申请数量需大于0");
              //  }
              //  if (!materialSet.add(detailReq.getMaterialId())) {
               //     throw new BusinessException("申请物料不能重复");
              //  }
                CrmSupplyMaterialDeliverOrderDetail orderDetail = new CrmSupplyMaterialDeliverOrderDetail();
                orderDetail.setMainId(deliverOrder.getId());
             //   orderDetail.setMaterialId(detailReq.getMaterialId());
              //  orderDetail.setApplyAmount(detailReq.getAmount());
                orderDetail.setOutAmount(BigDecimal.ZERO);
                orderDetail.setInAmount(BigDecimal.ZERO);
                orderDetail.setSort(i++);
                details.add(orderDetail);
          //  }
          //  deliverDetailDao.save(details);

           // deliverOrderMsgDao.saveOptMsg(deliverOrder.getId(), DeliverOrderConstants.OPT_CREATE, "", operator);


        }catch (Exception e){
            throw new RuntimeException("接口同步失败");
        }
    }


    public static void main(String[] args) {
        ProcureApplyOrderVo req = new ProcureApplyOrderVo();

    }

}
