package com.sifang.modules.q7link.utils;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.opensdk.BaseRequest;
import com.amazonaws.opensdk.SdkRequestConfig;
import com.amazonaws.opensdk.config.ConnectionConfiguration;
import com.amazonaws.opensdk.config.TimeoutConfiguration;
import com.google.gson.Gson;
import com.jfinal.plugin.activerecord.Db;
import com.q7link.openapi.Openapi;
import com.q7link.openapi.model.*;
import com.sifang.modules.q7link.entity.WuziOrder;
import com.sifang.modules.q7link.entity.WuziOrderDetail;
import com.sifang.modules.supply.order.vo.OrderTbQqVO;
import com.sifang.modules.supply.order.vo.OrderTbQqDetailsVO;
import com.sifang.modules.sys.common.utils.IdGen;
import com.sifang.modules.sys.common.utils.StringUtil;
import com.sifang.modules.sys.util.GuardUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;


/**
 * openapi sdk request example
 *
 * @author yankunjie
 */
public class OpenapiTemplate {
  private static Openapi openapi;

  private static Logger logger = LoggerFactory.getLogger(OpenapiTemplate.class);


  public static void updateTradeToQQ(String name,String id) {
    PutUpdateRequest request = new PutUpdateRequest();
    ApiParams apiParams = new ApiParams();
    apiParams.setJson("{" +
            "\"objectType\":\"Customer\"," +
            "\"data\":{" +
            "\"externalSystemCode\": \"110212001\",\n" +   //外部系统
            "\"externalObjectType\": \"Payment\",\n" +   //外部系统对象类型
            "\"code\": \""+id+"\",\n" +   //id
            "\"usedOrgId.name\": \"上海能辉科技股份有限公司\",\n" +   //使用组织
            "\"abbrName\":\""+name+"\"," +  //简称
            "\"name\":\""+name+"\"" +  //供应商分类
            "}}");
    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setApiParams(apiParams);
    PutUpdateResult result = openapi().putUpdate(request);
    ApiResponse apiResponse = result.getApiResponse();
    logger.info("修改供应商吗名称得到的结果-------"+apiResponse.getJson());
  }




  public static String addTradeToQQ(String gyName,String traderId) {
    logger.info("新增代理商信息推送到企企----");
    PostAddRequest request = new PostAddRequest();
    ApiParams apiParams = new ApiParams();
    apiParams.setJson("{" +
            "\"objectType\":\"Customer\"," +
            "\"data\":{" +
            "\"externalSystemCode\": \"110212001\",\n" +   //外部系统
            "\"externalObjectType\": \"Payment\",\n" +   //外部系统对象类型
            "\"externalObjectId\": \""+traderId+"\",\n" +   //外部系统唯一标识
            "\"customerTypeId\":\"CustomerType.externalCustomer\"," +  //客户类型
            "\"abbrName\":\""+gyName+"\"," +  //简称
            "\"firstDealTime\":\""+DateUtil.today()+"\"," +  //供应商发展日期
            "\"createdOrgId.name\":\"上海能辉科技股份有限公司\"," +  //创建组织
            "\"categoryId.name\":\"合作伙伴\"," +  //客户分类
            "\"name\":\""+gyName+"\"" +  //供应商分类
            "}}");
    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setApiParams(apiParams);
    PostAddResult postAddResult = openapi().postAdd(request);
    ApiResponse apiResponse = postAddResult.getApiResponse();
    Map map=(Map) JSONObject.parseObject(apiResponse.getJson());
    logger.info("新增代理商信息推送到企企返回的数据----"+apiResponse.getJson());
    if(map.containsKey("code")){
      if(map.get("code") != null){
        String code=String.valueOf(map.get("code")); // 记录企企系统的客户编码
        String id=String.valueOf(map.get("id")); // 记录企企系统的客户id
        String insertSql="INSERT INTO crm_supply_material_project_qq(`id`, `code`, `qid`, `bid`) VALUES (?,?,?,?)";
        Db.update(insertSql, IdGen.uuid(),code,id, traderId);
//        String updateSql2="update crm_trader set qq_company_code=? where id=?";
//        Db.update(updateSql2,code,traderId);
        return code;
      }
    }
    return null;
  }

  /**
   * 新增领用出库单
   * 备注：推送数据的时候用户需要有使用仓库的权限,企企系统会自动校验库存数量  无权限 库存数量不足 则不能成功推送
   */
  public static String addOutStorehouseToQQ(OrderTbQqVO orderTbQq,String qqId, WuziOrder wuziOrder) {
    logger.info("新增领用出库单信息推送到企企----");
    if (StringUtils.isBlank(qqId)) {
      saveSysRecord(orderTbQq.getId(),"", "addOutStorehouseToQQ",new Gson().toJson(orderTbQq),
              "同步生成企企领用出库单失败，未获取到qqId", "1");
      return "{}";
    }
    if (wuziOrder == null || wuziOrder.getDetails().isEmpty()) {
      saveSysRecord(orderTbQq.getId(),"", "addOutStorehouseToQQ",new Gson().toJson(orderTbQq),
              "同步生成企企领用出库单失败，未获取到企企物资需求单记录", "1");
      return "{}";
    }
    PostAddRequest request = new PostAddRequest();
    ApiParams apiParams = new ApiParams();
    Map<String,Object> json=new HashMap();
    json.put("objectType","PickingIssue");
    Map<String,Object> data=new HashMap<>();
    data.put("externalSystemCode","110212001");//外部系统
    data.put("externalObjectType","Payment");//外部系统对象类型
    data.put("externalObjectId",orderTbQq.getId());//外部系统唯一标识 当前存的是订单id
    data.put("createdOrg.name","上海能辉科技股份有限公司"); //库存组织
    data.put("demandOrg.name","上海能辉科技股份有限公司"); // 需求组织
    data.put("projectOrg.name","上海能辉科技股份有限公司"); // 项目组织
    data.put("billType.name","领用出库单");  //单据类型
    data.put("webEditTemplate.name","领用出库单");  //单据模板
    data.put("businessType.name","领用出库");//	业务类型
    data.put("businessDate",DateUtil.today());//业务日期
    data.put("stockTransType.name","领用出库");//出入库类型
    data.put("csZhuTiGongSiCcjmskk0cft01.name","上海能辉科技股份有限公司");//主体公司
    data.put("billIoTypeId","BillIoType.blue");//单据方向
    //data.put("pickingIssueItemsCount",15);
    data.put("srcObjectType","CsWuZiLingYongShenQingDan");//类型  物资需求单
    data.put("project.code",orderTbQq.getProjectCode());//项目
    data.put("srcObjectId",qqId);//物资领用申请单id
    String srcItemObjectType = "CsWzlyscjc0jf0c8601";//来源单据明细对象名 - 甲供材料单即赊销下单
    if ("5".equals(orderTbQq.getType())) {
      srcItemObjectType = "";
    }

    List<Map> pickingIssueItems=new ArrayList<>();
    for(OrderTbQqDetailsVO vo:orderTbQq.getList()){
      Map ma=new HashMap();
      ma.put("product.code",vo.getQqCode()); //存货
      ma.put("invBaseUnit.name",vo.getUnitName());  //库存主单位
      ma.put("warehouse.code",orderTbQq.getWarehouseCode()); //仓库编码
      ma.put("invBaseQty",vo.getOutAmount());//库存主数量
      if (StringUtils.isNotBlank(srcItemObjectType)) { //甲供材料单 明细需要同步来源单据
        ma.put("srcObjectId",qqId);//物资领用申请单id
        ma.put("srcObjectType","CsWuZiLingYongShenQingDan");//来源单据对象名 类型 物资需求单
        ma.put("srcItemObjectType",srcItemObjectType);//来源单据明细对象名
        String qqDetailId = null;
        for (WuziOrderDetail detail : wuziOrder.getDetails()) {
          if (detail.getDeliverDetailId().equals(vo.getId())) {
            qqDetailId = detail.getId();
            break;
          }
        }
        ma.put("srcItemObjectId",qqDetailId);//来源单据明细
      }
      data.put("project.code",orderTbQq.getProjectCode());//项目
      pickingIssueItems.add(ma);
    }
    //pickingIssueItems=pickingIssueItems.subList(0,1);

    data.put("pickingIssueItems",pickingIssueItems);
    json.put("data",data);
    apiParams.setJson(JSONUtil.toJsonStr(json));
    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setApiParams(apiParams);
    PostAddResult postAddResult = openapi().postAdd(request);
    ApiResponse apiResponse = postAddResult.getApiResponse();
    String jsonStr = apiResponse.getJson();
    Map map=(Map) JSONObject.parseObject(jsonStr);
    if(!map.containsKey("code") && !map.containsKey("id")){
      saveSysRecord(orderTbQq.getId(),"", "addOutStorehouseToQQ",apiParams.getJson(), jsonStr, "1");
      GuardUtils.notBlank("", "数据推送企企失败，"+map.get("error"));
    }
    saveSysRecord(orderTbQq.getId(),"", "addOutStorehouseToQQ",apiParams.getJson(), jsonStr, "0");
    logger.info("新增代理商信息推送到企企返回的数据----" + jsonStr);
    return jsonStr;
  }

  @Test
  public void testList() {
    PostListRequest request = new PostListRequest();
    ApiParams apiParams = new ApiParams();
    apiParams.setJson("{\n" +
            "  \"objectType\":\"PickingIssue\",\n" +
            "  \"fields\": [\n" +
            "    \"id\",\n" +
            "    \"code\",\n" +
            "    \"billTypeId\",\n" +
            "    \"businessTypeId\",\n" +
            "    \"billIoTypeId\",\n" +
            "    \"billStatus\",\n" +
            "    \"businessDate\"\n" +
            "  ]\n" +
            "}");


    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setApiParams(apiParams);
    PostListResult postListResult = openapi().postList(request);
    ApiResponse apiResponse = postListResult.getApiResponse();
    System.out.print("测试数据--"+apiResponse.getJson());
  }

  /**
   * 获取物资需求单 记录详情
   */
  public static WuziOrder getWZXQDdetail(String qqOrderId, OrderTbQqVO vo) {
    logger.info("------->>>>>>> 获取物资需求单 记录详情到平台 start");
    PostListRequest request = new PostListRequest();
    ApiParams apiParams = new ApiParams();
    apiParams.setJson("{\n" +
            "\"objectType\":\"CsWuZiLingYongShenQingDan\",\n" +
            "  \"criteriaStr\": \"id = '" + qqOrderId + "'\",\n" +
            "  \"fields\": [\n" +
            "    \"id\",\n" +            //订单id
            "    \"code\",\n" +          //单据编码
            "    \"businessDate\",\n" +          //业务日期
            "    \"billStatus\",\n" +          //单据状态
            "    \"billTypeId\",\n" +          //单据类型
            //领出仓库
            "    {\n" +
            "      \"fieldName\": \"csLingChuCangKu\"," +
            "      \"fields\": [\n" +
            "        \"name\"," +    //仓库名称
            "        \"code\"" +    //仓库编码
            "        ]\n" +
            "    },\n" +
            // 明细列表
            "    {\n" +
            "      \"fieldName\": \"csWzlyscjc0jf0c8601Items\"," +
            "      \"fields\": [\n" +
            "      \"id\",\n" +    //明细记录id
            "      \"ordinal\",\n" +    //序号
            "        {\n" +
            "        \"fieldName\": \"csCunHuo\"," +
            "        \"fields\": [\n" +
            "          \"code\"" +    //存货编码
            "          ]\n" +
            "        },\n" +
            "      \"csShiJiShuLiang\",\n" +     //确认数量
            "      \"csTiJiaoShuLiang\",\n" +  //提交数量
            "      \"csShuiL\"\n" +  //税率
            "      ]\n" +
            "    }\n" +
            "  ]\n" +
            "}");
    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setApiParams(apiParams);
    logger.info("同步企企数据传参：{}", apiParams.getJson());
    PostListResult postListResult = openapi().postList(request);
    ApiResponse apiResponse = postListResult.getApiResponse();
    logger.info("同步企企数据返回结果：{}", new Gson().toJson(apiResponse));
    Map map = (Map) JSONObject.parseObject(apiResponse.getJson());
    if (map.get("data") != null) {
      Map data = JSONObject.parseObject(String.valueOf(map.get("data")));
      if (data.get("list") != null) {
        List<Map> list = JSONObject.parseArray(String.valueOf(data.get("list")), Map.class);
        if (CollectionUtil.isNotEmpty(list)) {
          return dealWuziOrder(list.get(0), vo);// 只需处理第一条记录即可
        }
      }
    }
    return null;
  }

  public static WuziOrder dealWuziOrder(Map data, OrderTbQqVO vo) {

    WuziOrder order = new WuziOrder();
    String id = String.valueOf(data.get("id"));//订单id
    order.setId(id);

    order.setDeliverOrderId(vo.getId()); //系统的物料发货单记录id

    List<OrderTbQqDetailsVO> voList = vo.getList();

    Map<String, OrderTbQqDetailsVO> voDetailsMap = voList.stream().collect(
            Collectors.toMap(OrderTbQqDetailsVO::getId, (p) -> p));

    String code = String.valueOf(data.get("code"));//订单编码
    order.setCode(code);

    String billStatus = String.valueOf(data.get("billStatus"));//单据状态
    order.setBillStatus(billStatus);

    String billTypeId = String.valueOf(data.get("billTypeId"));//单据类型
    order.setBillTypeId(billTypeId);

    String csLingChuCangKuCode = ""; // 仓库编码
    if (data.containsKey("csLingChuCangKu")) {
      Map ma = JSONObject.parseObject(String.valueOf(data.get("csLingChuCangKu")));
      if (ma.containsKey("code")) {
        csLingChuCangKuCode = String.valueOf(ma.get("code"));
      }
    }
    order.setCsLingChuCangKuCode(csLingChuCangKuCode);

    String longTime = String.valueOf(data.get("businessDate"));//业务日期
    Date businessDate = new Date(Long.parseLong(longTime));
    order.setBusinessDate(businessDate);

    // 订单明细
    List<Map> details = JSONObject.parseArray(String.valueOf(data.get("csWzlyscjc0jf0c8601Items")), Map.class);
    List<WuziOrderDetail> detailList = new ArrayList<>();
    for (Map detailR : details) {
      WuziOrderDetail detail = new WuziOrderDetail();

      String detailId = String.valueOf(detailR.get("id"));//订单id
      detail.setId(detailId);

      detail.setOrderId(order.getId()); // 订单id

      String ordinal = String.valueOf(detailR.get("ordinal"));//序号
      detail.setOrdinal(StringUtil.isBlank(ordinal) ?
              0l : Long.parseLong(ordinal));

      String csShuiL = String.valueOf(detailR.get("csShuiL"));//税率
      detail.setCsShuiL(StringUtil.isBlank(csShuiL) ?
              BigDecimal.ZERO : new BigDecimal(csShuiL));

      String csCunHuoCode = ""; // 存货编码
      if (detailR.containsKey("csCunHuo")) {
        Map ma = JSONObject.parseObject(String.valueOf(detailR.get("csCunHuo")));
        if (ma.containsKey("code")) {
          csCunHuoCode = String.valueOf(ma.get("code"));
        }
      }
      detail.setCsCunHuoCode(csCunHuoCode);

      String csShiJiShuLiang = String.valueOf(detailR.get("csShiJiShuLiang"));//确认数量
      detail.setCsShiJiShuLiang(StringUtil.isBlank(csShiJiShuLiang) ?
              BigDecimal.ZERO : new BigDecimal(csShiJiShuLiang));

      String csTiJiaoShuLiang = String.valueOf(detailR.get("csTiJiaoShuLiang"));//提交数量
      detail.setCsTiJiaoShuLiang(StringUtil.isBlank(csTiJiaoShuLiang) ?
              BigDecimal.ZERO : new BigDecimal(csTiJiaoShuLiang));

      // 系统的物料发货单明细记录id
      String deliverDetailId = null;
      for (OrderTbQqDetailsVO dvo : voList) {
        if (!voDetailsMap.containsKey(dvo.getId())) {
          continue;
        }
        BigDecimal outAmount = new BigDecimal(dvo.getOutAmount());
        BigDecimal dif = outAmount.subtract(detail.getCsTiJiaoShuLiang()).setScale(1, RoundingMode.HALF_UP);
        // 匹配明细，规则：企企物料代码与提交数量 都必须相同时 匹配成功
        if (dif.compareTo(BigDecimal.ZERO) == 0 && dvo.getQqCode().equals(detail.getCsCunHuoCode())) {
          deliverDetailId = dvo.getId();
          voDetailsMap.remove(dvo.getId());
          break;
        }
      }
      detail.setDeliverDetailId(deliverDetailId);

      detailList.add(detail);
    }
    order.setDetails(detailList);
    logger.info("WuziOrder：{}", new Gson().toJson(order));
    return order;
  }


  /**
   * 物资需求单(小E)
   */
  public  static String addXiaoEOrderToQQ(OrderTbQqVO obj, String way) {
    logger.info("新增销售单信息推送到企企----");
    PostAddAutoSubmitRequest request = new PostAddAutoSubmitRequest();
    ApiParams apiParams = new ApiParams();
    Map aMap=new HashMap();
    aMap.put("objectType","CsWuZiLingYongShenQingDan");
    List<Map> list=new ArrayList<>();
    List<OrderTbQqDetailsVO> list1 = obj.getList();
    if(StringUtils.isBlank(obj.getProjectCode())){
      throw  new RuntimeException("子表项目为空");
    }
    if(StringUtils.isBlank(obj.getCompanyCode())){
      throw  new RuntimeException("代理商的外部代码为空");
    }
    if(StringUtils.isBlank(obj.getProjectCode())){
      throw  new RuntimeException("项目编码为空");
    }
    if(StringUtils.isBlank(obj.getCity())){
      throw  new RuntimeException("地区为空");
    }
    for(OrderTbQqDetailsVO details:list1){
      Map bMap=new HashMap();
      if(StringUtils.isBlank(details.getQqCode())){
        throw  new RuntimeException("存货编码为空");
      }
      if(StringUtils.isBlank(details.getOutAmount())){
        throw  new RuntimeException("提交数量为空");
      }
      if(StringUtils.isBlank(details.getHsSum())){
        throw new RuntimeException("金额为空");
      }
      if(StringUtils.isBlank(details.getBhsSum())){
        throw new RuntimeException("无税金额为空");
      }
      if(StringUtils.isBlank(details.getShuiLv())){
        throw new RuntimeException("税率为空");
      }
      if(StringUtils.isBlank(details.getShuiLvSum())){
        throw new RuntimeException("税额为空");
      }
      if(StringUtils.isBlank(details.getBhsPrice())){
        throw new RuntimeException("无税单价为空");
      }
      if(StringUtils.isBlank(details.getHsPrice())){
        throw new RuntimeException("提交单价为空");
      }

      bMap.put("csCunHuoCcjc0kj0c8601.code",details.getQqCode());//存货
      bMap.put("csTiJiaoShuLiangCcjf83h0c8601",details.getOutAmount());//提交数量
      bMap.put("csShiJiShuLiangCcjf9pl0c8601",details.getOutAmount());//确认数量
      bMap.put("csJinECcjhss00cft01",details.getHsSum());//金额
      bMap.put("csWuShuiJinECcjhss50cft01",details.getBhsSum());//无税金额
      bMap.put("csShuiLCcjht0r0cft01",details.getShuiLv());//税率
      bMap.put("csShuiECcjhss80cft01",details.getShuiLvSum());//税额
      bMap.put("csWuShuiDanJiaCcjhssp0cft01",details.getBhsPrice());//无税单价
      bMap.put("csQueRenDanJiaCcjf82k0c8601",details.getHsPrice());//确认单价
      bMap.put("csTiJiaoDanJiaCcjf82c0c8601",details.getHsPrice());//提交单价,即含税单价
      bMap.put("csXiangMuCcjc0l50c2h01.code",obj.getProjectCode());//子表项目
      bMap.put("csLingChuCangKuCckxudh0j9u01.code",obj.getWarehouseCode());//	领出仓库
      list.add(bMap);
    }
    Map data=new HashMap();
    data.put("externalSystemCode","110212001");//外部系统
    data.put("externalObjectType","Payment");//外部系统对象类型
    data.put("externalObjectId",obj.getId());//外部系统唯一标识 当前存的是系统订单id
    data.put("createdOrg.name","上海能辉科技股份有限公司");//创建组织
    data.put("billType.name","小E或代理商销售单");//单据类型
    data.put("businessType.name","默认业务类型");//单据类型
    data.put("webEditTemplate.name","小E或代理商销售单");//单据模板
    data.put("businessDate", DateUtil.now());//业务日期
    data.put("csGongSiMingChengCcjcgdj0c8601.code",obj.getCompanyCode());//企企的客户编码
    data.put("csShenQingRenCcjc0gv0c8601.name","蔡苏磊");//申请人  接口账号的姓名
    data.put("csShenQingBuMenCcjc0h10c8601.name","分布式光伏事业部");//申请人  接口账号的所属部门
    data.put("csKeHuYeWuYuanCcjwxe30cft01.name","蔡苏磊");//业务员  接口账号的姓名
    data.put("csZhuTiGongSiCcjmskk0cft01.name","上海能辉科技股份有限公司");//主体公司
    data.put("csKouKuanFangShiCclnwh20jnk01.name", "材料扣款结算");//扣款方式
    data.put("currency.name","人民币");//币种
    data.put("exchangeRate","1");//汇率
    data.put("csXiangMuCcjc0lg0c8601.code",obj.getProjectCode());//项目
    data.put("csLingChuCangKuCckskk80j9u01.code",obj.getWarehouseCode());//领出仓库
    data.put("csDeQuCckcq370j6k01.name",obj.getCity());//地区
    data.put("csWzlyscjc0jf0c8601Items",list);
    aMap.put("data",data);
    apiParams.setJson(JSONUtil.toJsonStr(aMap));
    request.sdkRequestConfig(getSdkRequestConfig(request, true, false));
    request.setApiParams(apiParams);
    logger.info("小E销售单，同步数据 Json：{}", apiParams.getJson());
    logger.info(" request：{}", request);
    PostAddAutoSubmitResult postAddResult = openapi().postAddAutoSubmit(request);
    ApiResponse apiResponse = postAddResult.getApiResponse();
    String json = apiResponse.getJson();
    Map map= JSONObject.parseObject(json);
    if(!map.containsKey("code") || !map.containsKey("id")){
      saveSysRecord(obj.getId(),way, "addOrderToQQ",apiParams.getJson(), json, "1");
      throw  new RuntimeException("提交失败---->>"+json);
    } else {
      saveSysRecord(obj.getId(),way, "addOrderToQQ",apiParams.getJson(), json, "0");
    }
    logger.info("小E销售单 同步返回结果:{}", json);
    return json;
  }


  /**
   * 物资需求单(甲供材料领用单)
   */
  public  static String addJGOrderToQQ(OrderTbQqVO obj) {
    logger.info("新增甲供材料领用单推送到企企----");
    PostAddAutoSubmitRequest request = new PostAddAutoSubmitRequest();
    ApiParams apiParams = new ApiParams();
    Map aMap=new HashMap();
    aMap.put("objectType","CsWuZiLingYongShenQingDan");
    List<Map> list=new ArrayList<>();
    List<OrderTbQqDetailsVO> list1 = obj.getList();
    if(StringUtils.isBlank(obj.getProjectCode())){
      throw  new RuntimeException("子表项目为空");
    }
    if(StringUtils.isBlank(obj.getCompanyCode())){
      throw  new RuntimeException("代理商的外部代码为空");
    }
    if(StringUtils.isBlank(obj.getProjectCode())){
      throw  new RuntimeException("项目编码为空");
    }
    if(StringUtils.isBlank(obj.getCity())){
      throw  new RuntimeException("地区为空");
    }
    for(OrderTbQqDetailsVO details:list1){
      Map bMap=new HashMap();
      if(StringUtils.isBlank(details.getQqCode())){
        throw new RuntimeException("存货编码为空");
      }
      if(StringUtils.isBlank(details.getOutAmount())){
        throw new RuntimeException("提交数量为空");
      }
      if(StringUtils.isBlank(details.getHsSum())){
        throw new RuntimeException("金额为空");
      }
      if(StringUtils.isBlank(details.getBhsSum())){
        throw new RuntimeException("无税金额为空");
      }
      if(StringUtils.isBlank(details.getShuiLv())){
        throw new RuntimeException("税率为空");
      }
      if(StringUtils.isBlank(details.getShuiLvSum())){
        throw new RuntimeException("税额为空");
      }
      if(StringUtils.isBlank(details.getBhsPrice())){
        throw new RuntimeException("无税单价为空");
      }
      if(StringUtils.isBlank(details.getHsPrice())){
        throw new RuntimeException("提交单价为空");
      }

      bMap.put("csCunHuoCcjc0kj0c8601.code",details.getQqCode());//存货编码
      bMap.put("csTiJiaoDanJiaCcjf82c0c8601",details.getHsPrice());//提交单价,即含税单价
      bMap.put("csQueRenDanJiaCcjf82k0c8601",details.getHsPrice());//确认单价
      bMap.put("csWuShuiDanJiaCcjhssp0cft01",details.getBhsPrice());//无税单价
      bMap.put("csShuiLCcjht0r0cft01",details.getShuiLv());//税率
      bMap.put("csTiJiaoShuLiangCcjf83h0c8601",details.getOutAmount());//提交数量
      bMap.put("csShiJiShuLiangCcjf9pl0c8601",details.getOutAmount());//确认数量
//      bMap.put("csJiLiangDanWeiCcjhsra0cft01.name",details.getUnitName());//计量单位
      bMap.put("csJinECcjhss00cft01",details.getHsSum());//金额  含税总额
      bMap.put("csWuShuiJinECcjhss50cft01",details.getBhsSum());//无税金额
      bMap.put("csShuiECcjhss80cft01",details.getShuiLvSum());//税额
      bMap.put("csJiaGeHanShuiCcjhstm0cft01",true);//价格含税
      bMap.put("csXiangMuCcjc0l50c2h01.code",obj.getProjectCode());//子表项目
      bMap.put("csLingChuCangKuCckxudh0j9u01.code",obj.getWarehouseCode());//	领出仓库
      list.add(bMap);
    }
    String date = DateUtil.now();
    Map data=new HashMap();
    data.put("externalSystemCode","110212001");//外部系统
    data.put("externalObjectType","Payment");//外部系统对象类型
    data.put("externalObjectId",obj.getId());//外部系统唯一标识 当前存的是系统订单id
    data.put("createdOrg.name","上海能辉科技股份有限公司");//创建组织
    data.put("billType.name","甲供材料领用单");//单据类型
    data.put("businessType.name","默认业务类型");//单据类型
    data.put("webEditTemplate.name","甲供材料领用单");//单据模板
    data.put("businessDate", date);//业务日期
    data.put("csXuQiuRiQiCcjc0m30c8601", date);//需求日期
    data.put("csGongSiMingChengCcjcgdj0c8601.code",obj.getCompanyCode());//企企的客户编码
    data.put("csShenQingRenCcjc0gv0c8601.name","蔡苏磊");//申请人  接口账号的姓名
    data.put("csShenQingBuMenCcjc0h10c8601.name","分布式光伏事业部");//申请人  接口账号的所属部门
    data.put("csKeHuYeWuYuanCcjwxe30cft01.name","蔡苏磊");//业务员  接口账号的姓名
    data.put("csZhuTiGongSiCcjmskk0cft01.name","上海能辉科技股份有限公司");//主体公司
    data.put("currency.name","人民币");//币种
    data.put("exchangeRate","1");//汇率
    data.put("csXiangMuCcjc0lg0c8601.code",obj.getProjectCode());//项目
    data.put("csLingChuCangKuCckskk80j9u01.code",obj.getWarehouseCode());//领出仓库
    data.put("csDeQuCckcq370j6k01.name",obj.getCity());//地区
    data.put("csWzlyscjc0jf0c8601Items",list);
    aMap.put("data",data);
    apiParams.setJson(JSONUtil.toJsonStr(aMap));
    request.sdkRequestConfig(getSdkRequestConfig(request, true, false));
    request.setApiParams(apiParams);
    logger.info("甲供材料领用单，同步数据 Json：{}", apiParams.getJson());
    logger.info(" request：{}", request);
    PostAddAutoSubmitResult postAddResult = openapi().postAddAutoSubmit(request);
    ApiResponse apiResponse = postAddResult.getApiResponse();
    String json = apiResponse.getJson();
    Map map= JSONObject.parseObject(json);
    if(!map.containsKey("code") || !map.containsKey("id")){
      saveSysRecord(obj.getId(),"03", "addOrderToQQ",apiParams.getJson(), json, "1");
      throw  new RuntimeException("提交失败---->>"+json);
    } else {
      saveSysRecord(obj.getId(),"03", "addOrderToQQ",apiParams.getJson(), json, "0");
    }
    logger.info("甲供材料领用单 同步返回结果:{}", json);
    return json;
  }

  /**
   * 生成企企数据同步日志
   */
  public static int saveSysRecord(String orderId, String way, String urlName, String requestParam,
                                  String responseParam, String status){
    StringBuilder insertSql=new StringBuilder();
    insertSql.append(" INSERT INTO crm_qq_process(id,order_id,way,url_name,create_time,request_param, response_param, status) ");
    insertSql.append(" VALUES (MD5(UUID()), ?,?,?,NOW(),?,?,?)");
    int result=Db.update(insertSql.toString(), orderId,way,urlName,requestParam, responseParam, status);
    return result;
  }

  /**
   * 企企小e销售单存储到本系统
   * @param orderId
   * @return
   */
  public static boolean checkSysStatus(String orderId){
    StringBuilder insertSql=new StringBuilder();
    insertSql.append(" SELECT COUNT(1) FROM crm_supply_material_deliver_order_qq a WHERE status='0' and a.`order_id` = ? ");
    return Db.queryLong(insertSql.toString(), orderId) <= 0;
  }

  /**
   * 删除小e销售单
   */
  public static String updateOrderToQQ(String objectId) {
    PostDeleteRequest request=new PostDeleteRequest();
    ApiParams apiParams = new ApiParams();
    apiParams.setJson("{\n" +
            "  \"objectType\":\"CsWuZiLingYongShenQingDan\",\n" +
            "  \"objectId\":\""+objectId+"\"\n" +
            "}");
    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setApiParams(apiParams);
    PostDeleteResult result = openapi().postDelete(request);
    ApiResponse apiResponse = result.getApiResponse();
    String resultJson = apiResponse.getJson();
    logger.info("删除流程得到的结果-------" + resultJson);
    saveSysRecord(objectId,"05","postDelete,删除", apiParams.getJson(), resultJson,"0");
    return apiResponse.getJson();
  }

  /**
   * 流程弃审
   */

  public static  void flow(String objectId){
    CompletableFuture<Void> future =CompletableFuture.runAsync(() -> {
      PostWithdrawRequest request =new PostWithdrawRequest();
      request.sdkRequestConfig(getSdkRequestConfig(request));
      WithdrawParams params=new WithdrawParams();
      params.setObjectId(objectId);
      params.setObjectType("CsWuZiLingYongShenQingDan");
      params.setReason("弃审");
      request.setWithdrawParams(params);
      PostWithdrawResult result =openapi().postWithdraw(request);
      ApiResponse apiResponse =result.getApiResponse();
      String resultJson = apiResponse.getJson();
      logger.info("弃审流程得到的结果-------"+resultJson);
      saveSysRecord(objectId,"04","postWithdraw,弃审",new Gson().toJson(params), resultJson,"0");
      try {
        Thread.sleep(5000);
      }catch (Exception e){
        e.printStackTrace();
      }
      updateOrderToQQ(objectId);
    });
  }



  /**
   * 联行号查询
   */
  @Test
  public void testBankQuery() {
    PostBankQueryRequest request = new PostBankQueryRequest();
    ApiParams params = new ApiParams();
    params.setJson("{\n" +
            "  \"name\": \"工行\", \n" +
            "  \"pageNo\": 1, \n" +
            "  \"pageSize\": 10\n" +
            "}");
    request.setApiParams(params);
    request.sdkRequestConfig(getSdkRequestConfig(request));
    PostBankQueryResult result = openapi().postBankQuery(request);
    System.out.println(result);
  }

  /**
   * 人员调动
   */
  @Test
  public void testUserTransfer() {
    PostUserTransferRequest request = new PostUserTransferRequest();
    ApiParams params = new ApiParams();
    params.setJson("{\n" +
            "    \"userId\": \"03LGK261UKQ00EP\",\n" +
            "    \"autoFinishJobRelationship\": true,\n" +
            "    \"transferInOrgId\": \"FJVC7X50C09000A\",\n" +
            "    \"transferInDeptId\": \"VNMMF461UWT00BC\",\n" +
            "    \"jobStartTime\": 1690387200000,\n" +
            "    \"type\": \"create\"\n" +
            "}");
    request.setApiParams(params);
    request.sdkRequestConfig(getSdkRequestConfig(request));
    PostUserTransferResult result = openapi().postUserTransfer(request);
    System.out.println(result);
  }

  /**
   * 现存量、可用量查询
   */
  @Test
  public void testInventoryAvailQty() {
    PostInventoryAvailQtyRequest request = new PostInventoryAvailQtyRequest();
    ApiParams params = new ApiParams();
    params.setJson("{}");
    request.setApiParams(params);
    request.sdkRequestConfig(getSdkRequestConfig(request));
    PostInventoryAvailQtyResult result = openapi().postInventoryAvailQty(request);
    ApiResponse apiResponse = result.getApiResponse();
    System.out.println(apiResponse);
  }

  /**
   * 打印预览
   */
  @Test
  public void testPrintPreview() {
    PostPrintPreviewRequest request = new PostPrintPreviewRequest();
    PrintPreview printPreview = new PrintPreview();
    printPreview.setObjectType("ReimburseApply");
    printPreview.setObjectId("U4DT9361UKQ001E");
    printPreview.setTemplateId("5hs1@zEZR");
    request.setPrintPreview(printPreview);
    request.sdkRequestConfig(getSdkRequestConfig(request));
    PostPrintPreviewResult result = openapi().postPrintPreview(request);
    Attachment attachment = result.getAttachment();
    System.out.println(attachment);
  }

  /**
   * 项目阶段执行开始
   */
  @Test
  public void testProjectStartStage() {
    PostProjectStartStageRequest request = new PostProjectStartStageRequest();
    ProjectStage projectStage = new ProjectStage();
    projectStage.setId("1");
    projectStage.setProjectId("2");
    projectStage.setUsedOrgId("3");
    projectStage.setDate(String.valueOf(System.currentTimeMillis()));
    request.projectStage(projectStage);
    request.sdkRequestConfig(getSdkRequestConfig(request));
    PostProjectStartStageResult result = openapi().postProjectStartStage(request);
    System.out.println(result);
  }

  /**
   * 项目阶段执行完成
   */
  @Test
  public void testProjectFinishStage() {
    PostProjectFinishStageRequest request = new PostProjectFinishStageRequest();
    ProjectStage projectStage = new ProjectStage();
    projectStage.setId("1");
    projectStage.setProjectId("2");
    projectStage.setUsedOrgId("3");
    projectStage.setDate(String.valueOf(System.currentTimeMillis()));
    request.projectStage(projectStage);
    request.sdkRequestConfig(getSdkRequestConfig(request));
    PostProjectFinishStageResult result = openapi().postProjectFinishStage(request);
    System.out.println(result);
  }

  /**
   * 部门分配
   */
  @Test
  public void testDepartmentAssign() {
    PostDepartmentMomanualassignRequest request = new PostDepartmentMomanualassignRequest();
    DepartmentAssign params = new DepartmentAssign();
    params.setAssignInfo(new AssignInfo().objectId("1").usedOrgId("1"));
    params.setOperateOrgId("1");
    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setDepartmentAssign(params);
    PostDepartmentMomanualassignResult result = openapi().postDepartmentMomanualassign(request);
    System.out.println(result);
  }

  /**
   * 取消确认
   */
  @Test
  public void testCancelCashierConfirm() {
    PostReceiptCancelconfirmRequest request = new PostReceiptCancelconfirmRequest();
    CashierCancelConfirm params = new CashierCancelConfirm();
    params.setObjectType("Receipt");
    params.setObjectId("1");
    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setCashierCancelConfirm(params);
    PostReceiptCancelconfirmResult result = openapi().postReceiptCancelconfirm(request);
    System.out.println(result);
  }

  /**
   * 出纳确认-付款单
   */
  @Test
  public void testCashierConfirmForPayment() {
    PostReceiptCashierconfirmRequest request = new PostReceiptCashierconfirmRequest();
    CashierConfirm params = new CashierConfirm();
    params.setPaymentId("1");
    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setCashierConfirm(params);
    PostReceiptCashierconfirmResult result = openapi().postReceiptCashierconfirm(request);
    System.out.println(result);
  }


  /**
   * 出纳确认-收款单
   */
  @Test
  public void testCashierConfirmForReceipt() {
    PostReceiptCashierconfirmRequest request = new PostReceiptCashierconfirmRequest();
    CashierConfirm params = new CashierConfirm();
    params.setReceiptId("1");
    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setCashierConfirm(params);
    PostReceiptCashierconfirmResult result = openapi().postReceiptCashierconfirm(request);
    System.out.println(result);
  }

  /**
   * 查询工作日类型
   */
  @Test
  public void testQueryDateType() {
    GetWorkcalendarQuerydatetypeRequest request = new GetWorkcalendarQuerydatetypeRequest();
    request.date(String.valueOf(System.currentTimeMillis()));
    request.setWorkCalendarId("4VM2ER50U960099");
    request.sdkRequestConfig(getSdkRequestConfig(request));
    GetWorkcalendarQuerydatetypeResult result = openapi().getWorkcalendarQuerydatetype(request);
    WorkCalendar workCalendar = result.getWorkCalendar();
    System.out.println(workCalendar.getWorkDayType());
  }

  /**
   * 项目变更
   */
  @Test
  public void testChangeProject() {
    PutChangeprojectRequest request = new PutChangeprojectRequest();
    ApiParams params = new ApiParams();
    params.setJson("{\"data\":{\"id\":\"4VM2ER50U96001X\",\"description\":\"xxx\"}}");
    request.setApiParams(params);
    request.sdkRequestConfig(getSdkRequestConfig(request));
    PutChangeprojectResult putChangeprojectResult = openapi().putChangeproject(request);
    ApiResponse apiResponse = putChangeprojectResult.getApiResponse();
    System.out.println(apiResponse);
  }

  /**
   * 查询报表json
   */
  @Test
  public void testReportDefinitionJson() {
    PostReportdefinitionRequest request = new PostReportdefinitionRequest();
    ReportDefintionParams params = new ReportDefintionParams();
    params.setParams("{\"id\":\"4VM2ER50U96001X\",\"outputType\":\"json\",\"queryObject\":{\"criteria\":{}}}");
    request.setReportDefintionParams(params);
    request.sdkRequestConfig(getSdkRequestConfig(request));
    PostReportdefinitionResult reportdefinitionResult = openapi().postReportdefinition(request);
    ReportDefintionResponse reportDefintionResponse = reportdefinitionResult.getReportDefintionResponse();
    System.out.println(reportDefintionResponse);
  }

  /**
   * 查询报表pdf
   */
  @Test
  public void testReportDefinitionPdf() {
    PostReportdefinitionRequest request = new PostReportdefinitionRequest();
    ReportDefintionParams params = new ReportDefintionParams();
    params.setParams("{\"id\":\"4VM2ER50U96001X\",\"outputType\":\"pdf\",\"queryObject\":{\"criteria\":{}}}");
    request.setReportDefintionParams(params);
    request.sdkRequestConfig(getSdkRequestConfig(request));
    PostReportdefinitionResult reportdefinitionResult = openapi().postReportdefinition(request);
    ReportDefintionResponse reportDefintionResponse = reportdefinitionResult.getReportDefintionResponse();
    System.out.println(reportDefintionResponse);
  }

  /**
   * 查询报表excel
   */
  @Test
  public void testReportDefinitionExcel() {
    PostReportdefinitionRequest request = new PostReportdefinitionRequest();
    ReportDefintionParams params = new ReportDefintionParams();
    params.setParams("{\"id\":\"4VM2ER50U96001X\",\"outputType\":\"excel\",\"queryObject\":{\"criteria\":{}}}");
    request.setReportDefintionParams(params);
    request.sdkRequestConfig(getSdkRequestConfig(request));
    PostReportdefinitionResult reportdefinitionResult = openapi().postReportdefinition(request);
    ReportDefintionResponse reportDefintionResponse = reportdefinitionResult.getReportDefintionResponse();
    System.out.println(reportDefintionResponse);
  }

  /**
   * 查询执行进度
   */
  @Test
  public void getUserTask() {
    PostUsertaskRequest request = new PostUsertaskRequest();
    UserTaskParams userTaskParams = new UserTaskParams();
    userTaskParams.setObjectId("HSF4WV520RE001S");
    request.setUserTaskParams(userTaskParams);
    request.sdkRequestConfig(getSdkRequestConfig(request));
    PostUsertaskResult result = openapi().postUsertask(request);
    System.out.println(result);
  }

  /**
   * 更新接口
   */
  @Test
  public void testUpdateByCode() {
    PutUpdateRequest request = new PutUpdateRequest();
    ApiParams apiParams = new ApiParams();
    apiParams.setJson("{\"objectType\":\"Vendor\"," +
            "\"data\":{" +
            "\"name\":\"1002\"," +
            "\"abbrName\":\"1002\"," +  //简称
            "\"id\":\"PAFV5760JTD0031\"," +
            "\"usedOrgId\":{" +
                    "}"+
            "}}");
    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setApiParams(apiParams);
    PutUpdateResult result = openapi().putUpdate(request);
    ApiResponse apiResponse = result.getApiResponse();
    System.out.println(apiResponse);
  }

  /**
   * 测试根据code获取openid
   */
  @Test
  public void testGetCode() {
    GetCodeRequest request = new GetCodeRequest();
    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setCode("x");
    GetCodeResult result = openapi().getCode(request);
    Openid apiResponse = result.getOpenid();
    System.out.println(apiResponse);
  }



  @Test
  public void testBatchSignedUrl() {
    PostAttachmentSignatureBatchSignedUrlRequest request = new PostAttachmentSignatureBatchSignedUrlRequest();
    ApiParams apiParams = new ApiParams();
    apiParams.setJson("{\"keys\":[\"1\",\"2\"],\"isHttp\":false,\"expiresIn\":3600}");
    request.setApiParams(apiParams);
    request.sdkRequestConfig(getSdkRequestConfig(request));
    PostAttachmentSignatureBatchSignedUrlResult result = openapi().postAttachmentSignatureBatchSignedUrl(request);
    System.out.println(result);
  }

  /**
   * 获取队列信息
   */
  @Test
  public void testQueue() {
    GetQueueRequest request = new GetQueueRequest();
    request.sdkRequestConfig(getSdkRequestConfig(request));
    GetQueueResult result = openapi().getQueue(request);
    System.out.println(result.getQueue());
  }

  /**
   * 审批中更新接口
   */
  @Test
  public void testApprovingUpdate() {
    PutApprovingUpdateRequest request = new PutApprovingUpdateRequest();
    ApiParams apiParams = new ApiParams();
    apiParams.setJson("{\"objectType\":\"ApPayment\",\"data\":{\"description\":\"xxx\",\"id\":\"9B1F1R50LNT0028\"}}");
    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setApiParams(apiParams);
    PutApprovingUpdateResult result = openapi().putApprovingUpdate(request);
    ApiResponse apiResponse = result.getApiResponse();
    System.out.println(apiResponse);
  }

  /**
   * 更新接口
   */
  @Test
  public void testUpdate() {
    PutUpdateRequest request = new PutUpdateRequest();
    ApiParams apiParams = new ApiParams();
    apiParams.setJson("{\"objectType\":\"SubjectDef\",\"data\":{\"code\":\"9005\",\"name\":\"数据1\",\"codeRuleId\":\"N7NC1L501C60001\",\"accountingSystemId\":\"DS336K501JR0001\",\"id\":\"9B1F1R50LNT0028\"}}");
    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setApiParams(apiParams);
    PutUpdateResult result = openapi().putUpdate(request);
    ApiResponse apiResponse = result.getApiResponse();
    System.out.println(apiResponse);
  }

  /**
   * 删除接口
   */
  @Test
  public void testDelete() {
    PostDeleteRequest request = new PostDeleteRequest();
    ApiParams apiParams = new ApiParams();
    apiParams.setJson("{\"objectType\": \"Customer\",\"objectId\": \"SADFASDFSDAF1001\"}");
    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setApiParams(apiParams);
    PostDeleteResult result = openapi().postDelete(request);
    ApiResponse apiResponse = result.getApiResponse();
    System.out.println(apiResponse);
  }

  /**
   * 生成红单
   */
  @Test
  public void testToRedBill() {
    PostToredbillRequest request = new PostToredbillRequest();
    request.sdkRequestConfig(getSdkRequestConfig(request));
    ToRedBillParams params = new ToRedBillParams();
    params.objectId("123");
    params.setObjectType("RevenueConfirmation");
    request.setToRedBillParams(params);
    PostToredbillResult result = openapi().postToredbill(request);
    System.out.println(result.getProjection());
  }

  /**
   * 弃审
   */
  @Test
  public void testWithdraw() {
    PostWithdrawRequest request = new PostWithdrawRequest();
    request.sdkRequestConfig(getSdkRequestConfig(request));
    WithdrawParams params = new WithdrawParams();
    params.objectId("123");
    params.setObjectType("RevenueConfirmation");
    request.setWithdrawParams(params);
    PostWithdrawResult result = openapi().postWithdraw(request);
    ApiResponse apiResponse = result.getApiResponse();
    System.out.println(apiResponse);

  }

  /**
   * 同步任务
   */
  @Test
  public void testBatchDo() {
    PostBatchDoRequest request = new PostBatchDoRequest();
    // 忽略警告
    boolean ignoreWarn = true;
    request.sdkRequestConfig(getSdkRequestConfig(request, ignoreWarn));
    AsyncBatchDoParams params = new AsyncBatchDoParams();
    params.objectId("J81N8S512DM000E");
    params.setObjectType("Receipt");
    params.setAction("manualSubmit");
    request.setAsyncBatchDoParams(params);
    PostBatchDoResult result = openapi().postBatchDo(request);
    ApiResponse apiResponse = result.getApiResponse();
    System.out.println(apiResponse);
  }

  /**
   * 异步任务
   */
  @Test
  public void testAsyncBatchDo() {
    PostAsyncBatchDoRequest request = new PostAsyncBatchDoRequest();
    // 忽略警告
    boolean ignoreWarn = true;
    request.sdkRequestConfig(getSdkRequestConfig(request, ignoreWarn));
    AsyncBatchDoParams params = new AsyncBatchDoParams();
    params.objectId("J81N8S512DM000E");
    params.setObjectType("Receipt");
    params.setAction("manualSubmit");
    request.setAsyncBatchDoParams(params);
    PostAsyncBatchDoResult result = openapi().postAsyncBatchDo(request);
    ApiResponse apiResponse = result.getApiResponse();
    System.out.println(apiResponse);
  }

  /**
   * 异步任务结果查询
   */
  @Test
  public void testAsyncTask() {
    PostAsynctaskRequest request = new PostAsynctaskRequest();
    request.sdkRequestConfig(getSdkRequestConfig(request));
    AsyncTaskParams params = new AsyncTaskParams();
    params.setRequestId("e1fe942c-c2b6-47f1-9b6f-95ffa69433b5");
    request.setAsyncTaskParams(params);
    PostAsynctaskResult result = openapi().postAsynctask(request);
    System.out.println(result.getAsyncTask());
  }

  /**
   * 获取租户信息
   */
  @Test
  public void testGetTenant() {
    GetTenantRequest request = new GetTenantRequest();
    request.sdkRequestConfig(getSdkRequestConfig(request));

    GetTenantResult result = openapi().getTenant(request);
    System.out.println(result);
  }

  /**
   * 获取用户信息
   */
  @Test
  public void testGetUser() {
    GetUserRequest request = new GetUserRequest();
    request.sdkRequestConfig(getSdkRequestConfig(request));
    GetUserResult result = openapi().getUser(request);
    System.out.println(result);
  }

  /**
   * 新增
   */
  @Test
  public void testAdd() {
    PostAddRequest request = new PostAddRequest();
    ApiParams apiParams = new ApiParams();
    String now = String.valueOf(System.currentTimeMillis());
    apiParams.setJson("{\"objectType\":\"Customer\",\"data\":{\"billType.name\":\"凭证\",\"accountingBook.name\":\"对外-展开\",\"billStatus\":\"BillStatus.draft\",\"billFullStatus\":\"BillStatus.submitting\",\"voucherType.name\":\"记账凭证\",\"voucherNo\":\"0004\",\"businessDate\":\"2020-03-23\",\"voucherItems\":[{\"description\":\"明细1\",\"subject.name\":\"库存现金\",\"debitAmount\":\"1000\",\"currency.name\":\"人民币\"},{\"description\":\"明细2\",\"subject.name\":\"持有待售资产减值准备\",\"creditAmount\":\"1000\",\"currency.name\":\"人民币\"}],\"externalObjectId\":\"1000021\",\"externalObjectType\":\"1100001\",\"externalSystemCode\":\"110001\"}}");

    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setApiParams(apiParams);
    PostAddResult postAddResult = openapi().postAdd(request);
    ApiResponse apiResponse = postAddResult.getApiResponse();
    System.out.println(apiResponse);
  }

  /**
   * 新增并自动提交
   */
  @Test
  public void testAddAutoSubmit() {
    PostAddAutoSubmitRequest request = new PostAddAutoSubmitRequest();
    ApiParams apiParams = new ApiParams();
    apiParams.setJson("{\"objectType\":\"OtherApPayment\",\"data\":{\"createdOrgId\":\"K4WUXS50JUD0011\",\"applyOrgId\":\"K4WUXS50JUD0011\",\"code\":\"AP0120200500006\",\"businessDate\":\"2021-05-21\",\"billType.name\":\"其他应付单\",\"businessType.name\":\"其他应付\",\"objectTypeObject.title\":\"供应商\",\"transObject.name\":\"中粮集团\",\"object.name\":\"中粮集团\",\"invoiceType.name\":\"增值税普通发票\",\"payDueDate\":\"2021-05-21\",\"currency.name\":\"人民币\",\"project.name\":\"项目3\",\"exchangeRate\":1,\"otherApPaymentItems\":[{\"invoiceType.name\":\"增值税普通发票\",\"cost.name\":\"一级费用\",\"budgetAccount.name\":\"其他应付预算项目\",\"amount\":100,\"originAmount\":100,\"taxRate\":0.13,\"originAmountWithoutTax\":88.5,\"originTaxAmount\":11.5}],\"externalObjectId\":\"1001\",\"externalObjectType\":\"Payment\",\"externalSystemCode\":\"110212001\"}}");

    request.sdkRequestConfig(getSdkRequestConfig(request, true, false));
    request.setApiParams(apiParams);
    PostAddAutoSubmitResult postAddResult = openapi().postAddAutoSubmit(request);
    ApiResponse apiResponse = postAddResult.getApiResponse();
    System.out.println(apiResponse);
  }

  /**
   * 列表查询
   */




  @Test
  public void testLista() {

    PostListRequest request = new PostListRequest();
    ApiParams apiParams = new ApiParams();
    apiParams.setJson("{\n" +
            "  \"objectType\":\"PurReceipt\",\n" +
            "  \"fields\": [\n" +
            "    \"id\",\n" + //主键id
            "    \"code\",\n" + //订单编码
            "    \"billTypeId\",\n" +  //单据类型
            "    \"billFullStatus\"," + //	单据完全状态
            "    \"businessDate\"," +   //	业务日期
            "    \"address\"," +   //	收货地址

            //供应商
            "    {\n" +
            "      \"fieldName\": \"vendor\"," +
            "      \"fields\": [\n" +
            "        \"id\"," +     //供应商Id
            "        \"name\"" +    //供应商名称
            "      ]\n" +
            "    },\n" +
            //主体公司
            "    {\n" +
            "      \"fieldName\": \"csZhuTiGongSiCcjmskk0cft01\"," +
            "      \"fields\": [\n" +
            "        \"code\"," +     //主体公司code
            "        \"name\"" +    //主体公司名称
            "      ]\n" +
            "    },\n" +
            //入库的仓库
            "    {\n" +
            "      \"fieldName\": \"warehouse\"," +
            "      \"fields\": [\n" +
            "        \"code\"," +     //仓库code
            "        \"name\"" +    //仓库名称
            "      ]\n" +
            "    },\n" +
            //采购入库明细列表
            "    {\n" +
            "      \"fieldName\": \"purReceiptItems\"," +
            "      \"fields\": [\n" +
            "        \"baseQty\"," +    //主数量
            //存货
            "    {\n" +
            "      \"fieldName\": \"product\"," +
            "      \"fields\": [\n" +
            "        \"name\"," +    //存货名称
            "        \"spec\"" +    //存货规格
            "      ]\n" +
            "    },\n" +
            //仓库
            "    {\n" +
            "      \"fieldName\": \"warehouse\"," +
            "      \"fields\": [\n" +
            "        \"name\"" +    //仓库名称
            "      ]\n" +
            "    },\n" +
            //单位
            "    {\n" +
            "      \"fieldName\": \"baseUnit\"," +
            "      \"fields\": [\n" +
            "        \"name\"" +    //单位名称
            "      ]\n" +
            "    },\n" +

            //采购订单编号
            "    {\n" +
            "      \"fieldName\": \"purObject\"," +
            "      \"fields\": [\n" +
            "        \"code\"" +    //采购订单编号
            "      ]\n" +
            "    }\n" +

            "      ]\n" +
            "    }\n" +

            "  ]\n" +
            "}");


    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setApiParams(apiParams);
    PostListResult postListResult = openapi().postList(request);
    ApiResponse apiResponse = postListResult.getApiResponse();
    System.out.print("测试数据--"+apiResponse.getJson());
  }




  public static SdkRequestConfig getSdkRequestConfig(BaseRequest request) {
    return getSdkRequestConfig(request, false);
  }

  /**
   * 获取sdk请求配置
   *
   * @param request    请求
   * @param ignoreWarn 是否忽略警告：true为忽略
   * @return SdkRequestConfig
   */
  public static SdkRequestConfig getSdkRequestConfig(BaseRequest request, boolean ignoreWarn) {
    return getSdkRequestConfig(request, ignoreWarn, false);
  }

  /**
   * 获取sdk请求配置
   * <pre>
   *   支持设置忽略警告
   *   支持单据保存为草稿
   * </pre>
   *
   * @param request     请求
   * @param ignoreWarn  是否忽略警告：true为忽略
   * @param saveAsDraft 是否保存为草稿：true为保存为草稿
   * @return SdkRequestConfig
   */
  public static SdkRequestConfig getSdkRequestConfig(BaseRequest request, boolean ignoreWarn, boolean saveAsDraft) {
    return request.sdkRequestConfig().copyBuilder()
            .customHeader("Content-Type", "application/json")
            .customHeader("Access-Key-Id", Q7linkConstants.ACCESS_KEY_ID)
            .customHeader("Open-Id", Q7linkConstants.OPEN_ID)
            .customHeader("Ignore-Warn", String.valueOf(ignoreWarn))
            .customHeader("Save-As-Draft", String.valueOf(saveAsDraft))
            .build();
  }

  public static Openapi openapi() {
    if (openapi == null) {
      BasicAWSCredentials awsCredentials = new BasicAWSCredentials(Q7linkConstants.ACCESS_KEY_ID,
              Q7linkConstants.ACCESS_SECRET);
      openapi = Openapi.builder()
              .connectionConfiguration(new ConnectionConfiguration()
                      .maxConnections(100)
                      .connectionMaxIdleMillis(10000))
              .timeoutConfiguration(new TimeoutConfiguration()
                      .httpRequestTimeout(29000)
                      .totalExecutionTimeout(29000)
                      .socketTimeout(29000))
              .iamCredentials(new AWSStaticCredentialsProvider(awsCredentials))
              .build();
    }
    return openapi;
  }


  public static String getAttachmentUrl(String key){
    try {
      Thread.sleep(1000);
    }catch (Exception e){
      e.printStackTrace();
    }

    GetAttachmentSignatureSignedurlRequest request = new GetAttachmentSignatureSignedurlRequest();
    request.sdkRequestConfig(getSdkRequestConfig(request));
    request.setKey(key);
    GetAttachmentSignatureSignedurlResult attachmentSignatureSignedurl = openapi().getAttachmentSignatureSignedurl(request);
    Attachment attachment = attachmentSignatureSignedurl.getAttachment();
    return attachment.getUrl();

  }





}
