package com.sifang.modules.kingdee.service;

import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.kingdee.bos.webapi.entity.RepoResult;
import com.kingdee.bos.webapi.entity.SuccessEntity;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.sifang.modules.kingdee.constants.KingDeeConstants;
import com.sifang.modules.kingdee.util.KingDeeUtil;
import com.sifang.modules.kingdee.vo.FNumberVo;
import com.sifang.modules.kingdee.vo.KingDeeResponseVo;
import com.sifang.modules.sunshine.SystemSetting.utils.BusinessException;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrder;
import com.sifang.modules.supply.order.entity.CrmSupplyMaterialDeliverOrderDetail;
import com.sifang.modules.supply.setting.entity.CrmSupplySupplier;
import com.sifang.modules.supply.setting.entity.CrmSupplyWarehouse;
import com.sifang.modules.sys.common.service.BaseService;
import com.sifang.modules.sys.common.utils.DateUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class KingDeePurchaseInWarehouseService extends BaseService {


    //入库
   public String inWarehouse(CrmSupplyMaterialDeliverOrder order, List<CrmSupplyMaterialDeliverOrderDetail> details, CrmSupplySupplier supplier, CrmSupplyWarehouse inWarehous)  {
       try {
           K3CloudApi client = new K3CloudApi();
           Gson gson = new Gson();
        //先调用采购单下推
           logger.info("开始......");
           long begin = System.currentTimeMillis();

           Map<String,Object> mapxia = Maps.newHashMap();
           mapxia.put("Ids", order.getKingDeeId());
           mapxia.put("IsEnableDefaultRule",true);
           mapxia.put("TargetFormId",KingDeeConstants.IN_WAREHOUSE_ID);
           mapxia.put("IsDraftWhenSaveFail",true);
           ArrayList<SuccessEntity>  repons= KingDeeUtil.kingDeeClitPush(gson.toJson(mapxia),KingDeeConstants.PURCHASE_FORM_ID,gson,client);
           long end = System.currentTimeMillis();
           logger.info("下推结束，共耗时：[" + (end-begin) / 1000 + "]秒");
            if(repons== null){
                throw new BusinessException("同步金蝶数据失败，请刷新再试");
            }
            String xiatuiId = repons.get(0).getId();

            //获取入库单ID
           Map<String, Object> datad = new HashMap<>();
           datad.put("Id", xiatuiId);
           String jsond = gson.toJson(datad);
           JsonArray array =KingDeeUtil.kingDeeClitDetail(jsond,KingDeeConstants.IN_WAREHOUSE_ID,gson,client);
           if(array.size()<1){
               throw new BusinessException("获取金蝶数据失败，请刷新再试");
           }
           long endd = System.currentTimeMillis();
           logger.info("获取详情，共耗时：[" + (endd-end) / 1000 + "]秒");
           logger.info(">>>>>>>>>>>inWarehouse 推入金蝶系统 orderId:{}",order.getId());
           Map<String,Object> data=new HashMap<>();

           data.put("ValidateFlag", false);  //是否验证数据合法性标志
           data.put("NumberSearch",false);  //是否用编码搜索基础资料
           data.put("IsDeleteEntry",false);

           Map<String,Object> model=new HashMap<>();
           Map<String,Object> masss = Maps.newHashMap();
           masss.put("FNUMBER","RKD01_SYS");
           model.put("FBillTypeID", masss);  //单据类型
           model.put("FID", xiatuiId);
           model.put("FBillNo", order.getNumber());  //单据编号
           model.put("FDate", DateUtils.formatDate(order.getReceiveTime(), "yyyy-MM-dd"));   //入库日期
           model.put("FStockOrgId", new FNumberVo("R001"));//收料组织
           model.put("FPurchaseOrgId", new FNumberVo("R001"));//采购组织
           model.put("FSupplierId", new FNumberVo(supplier.getKingDeeNumber()));//供应商
           model.put("FOwnerTypeIdHead", "BD_OwnerOrg");//货主类型--业务组织
          // model.put("FSupplierId", new FNumberVo("R001"));//供应商

           List<Object> FInStockEntry= new ArrayList<>();

           Map<String,Object> base=new HashMap<>();
           base.put("FNUMBER","XM0001");
           int i=0;
           for(CrmSupplyMaterialDeliverOrderDetail detail:details){
               Map<String,Object> fInStockEntry=new HashMap<>();
               if(i<array.size()){
                   JsonObject json4= array.get(i).getAsJsonObject();
                   fInStockEntry.put("FEntryID",json4.get("Id").getAsString());
               }
               fInStockEntry.put("F_QSVH_Base",base);
               fInStockEntry.put("FMaterialId", new FNumberVo(detail.getMaterialCode()));  //物料编码
               fInStockEntry.put("FRealQty", detail.getInAmount());   // 实收数量
               fInStockEntry.put("FPrice",detail.getPurchasePrice());// 单价
               fInStockEntry.put("FTAXPRICE",detail.getPurchasePrice());// 单价
           fInStockEntry.put("FOWNERID", new FNumberVo("R001"));  //货主
           fInStockEntry.put("FUnitID",  new FNumberVo(detail.getUnitCode()));   // 库存单位
           fInStockEntry.put("FPriceUnitID", new FNumberVo(detail.getUnitCode()));   //计价单位
           fInStockEntry.put("FOWNERTYPEID", "BD_OwnerOrg");   //货主类型
           fInStockEntry.put("FRemainInStockUnitId", new FNumberVo(detail.getUnitCode())); //采购单位
           fInStockEntry.put("FStockId", new FNumberVo(inWarehous.getNumber()));
           FInStockEntry.add(fInStockEntry);
           i++;
       }

           model.put("FInStockEntry",FInStockEntry);
           data.put("Model",model);


           String json = gson.toJson(data);


           //保存
           KingDeeResponseVo result = KingDeeUtil.kingDeeClitSave(json, KingDeeConstants.IN_WAREHOUSE_ID,gson,client);
           String id=result.getId();
           long endsa = System.currentTimeMillis();
           logger.info("保存，共耗时：[" + (endsa-endd) / 1000 + "]秒");
           Map<String, Object> data2 = new HashMap<>();
           data2.put("Ids", id);
           String json2 = gson.toJson(data2);
           //提交
           KingDeeUtil.kingDeeClitSubmit(json2, KingDeeConstants.IN_WAREHOUSE_ID,gson,client);
           long endtj = System.currentTimeMillis();
           logger.info("提交，共耗时：[" + (endtj-endsa) / 1000 + "]秒");
           //审核
           KingDeeUtil.kingDeeClitAudit(json2, KingDeeConstants.IN_WAREHOUSE_ID,gson,client);
           long endsh = System.currentTimeMillis();
           logger.info("保存，共耗时：[" + (endsh-endtj) / 1000 + "]秒");
           return id;

       }catch (Exception e){
           logger.error("采购入库单同步数据金蝶失败 : {}",e);
            throw new BusinessException("采购入库单同步数据金蝶失败！");
       }
   }

   public static void main(String[] arr) throws Exception {
       Gson gson = new Gson();
       K3CloudApi client = new K3CloudApi();

       Map<String,Object> data=new HashMap<>();
       data.put("ValidateFlag", false);  //是否验证数据合法性标志
       data.put("NumberSearch",false);  //是否用编码搜索基础资料

       Map<String,Object> model=new HashMap<>();
       model.put("FBillNo", "111");  //单据编号
       model.put("FDate", "2023-05-31");   //入库日期

       List<Object> FInStockEntry= new ArrayList<>();

       Map<String,Object> fInStockEntry=new HashMap<>();

       fInStockEntry.put("FMaterialId", new FNumberVo("222"));  //物料编码
       fInStockEntry.put("FRealQty",14);   // 实收数量
       fInStockEntry.put("FPrice", 22);  // 单价

       fInStockEntry.put("FOWNERID", new FNumberVo("111"));  //货主
       fInStockEntry.put("FUnitID",  new FNumberVo("11"));
       fInStockEntry.put("FPriceUnitID", new FNumberVo("11"));
       fInStockEntry.put("FOWNERTYPEID", "0");   //货主类型
       fInStockEntry.put("FRemainInStockUnitId", new FNumberVo("")); //采购单位

      /* fInStockEntry.put("FRemainInStockQty", 14);
       fInStockEntry.put("FStockId", new FNumberVo("11"));*/


       FInStockEntry.add(fInStockEntry);

       model.put("FInStockEntry",FInStockEntry);
       data.put("Model",model);

       /*String json = gson.toJson(data);

*/
       String json="{\"ValidateFlag\":false,\"Model\":{\"FBillNo\":\"CG23071710324053\",\"FPurchaseOrgId\":{\"FNumber\":\"R001\"},\"FSupplierId\":{\"FNumber\":\"VEN00001\"}," +
               "\"FBILLTYPEID\":{\"FNumber\":\"RKD01_SYS\"},\"FInStockEntry\":[{\"FMaterialId\":{\"FNumber\":\"ZJ_008\"},\"FRealQty\":10.00,\"FPriceUnitID\":{\"FNumber\":\"ZJ028\"}," +
               "\"FRemainInStockUnitId\":{\"FNumber\":\"ZJ028\"},\"FOWNERID\":{\"FNumber\":\"R001\"},\"FUnitID\":{\"FNumber\":\"ZJ028\"},\"FOWNERTYPEID\":\"BD_OwnerOrg\",\"FPrice\":20.00," +
               "\"FStockId\":{\"FNumber\":\"CK001\"}}],\"FStockOrgId\":{\"FNumber\":\"R001\"},\"FOwnerTypeIdHead\":\"BD_OwnerOrg\",\"FDate\":\"2023-07-17\"},\"NumberSearch\":false}";
       //保存
       KingDeeResponseVo result = KingDeeUtil.kingDeeClitSave(json, KingDeeConstants.IN_WAREHOUSE_ID,gson,client);
       String id=result.getId();

       Map<String, Object> data2 = new HashMap<>();
       data2.put("Ids", id);
       String json2 = gson.toJson(data2);
       //提交
       KingDeeUtil.kingDeeClitSubmit(json2, KingDeeConstants.IN_WAREHOUSE_ID,gson,client);
       //审核
       KingDeeUtil.kingDeeClitAudit(json2, KingDeeConstants.IN_WAREHOUSE_ID,gson,client);
   }

}
