package com.benyun.project.third.kingdee.sdk.material;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.benyun.common.utils.DateUtils;
import com.benyun.project.third.kingdee.domain.BDStock;
import com.benyun.project.third.kingdee.sdk.common.SeqHelper;
import com.benyun.project.third.kingdee.sdk.customer.BdCustomer;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.internal.LinkedTreeMap;
import com.kingdee.bos.webapi.entity.IdentifyInfo;
import com.kingdee.bos.webapi.entity.QueryParam;
import com.kingdee.bos.webapi.entity.RepoRet;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

import static org.junit.Assert.fail;



@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@Slf4j
public class BdMaterialTest {
    static String FNumber = SeqHelper.genNumber("WL");
    static String FName = "auwl_" + UUID.randomUUID().toString();
    private static String groupid = "";
    private static String materid = "";
    private static String fileid = "";

    @Autowired
//    static K3CloudApi api = new K3CloudApi();



    /* 本接口用于实现物料 (BD_Material) 的保存功能 */
    @Test
    public void atestSaveMaterial() throws Exception {
        K3CloudApi api = new K3CloudApi(false);
        BdMaterial c = new BdMaterial();
        String data = "{\"NeedUpDateFields\": [],\"NeedReturnFields\": [],\"IsDeleteEntry\": \"true\",\"SubSystemId\": \"\",\"IsVerifyBaseDataField\": \"false\",\"IsEntryBatchFill\": \"true\",\"ValidateFlag\": \"true\",\"NumberSearch\": \"true\",\"IsAutoAdjustField\": \"false\",\"InterationFlags\": \"\",\"IgnoreInterationFlag\": \"\",\"IsControlPrecision\": \"false\",\"ValidateRepeatJson\": \"false\",\"Model\": {\"FNumber\": "+"\""+FNumber+"\""+",\"FName\": "+"\""+FName+"\""+",\"FImgStorageType\": \"A\",\"FCreateOrgId\": {\"FNumber\": \"100\"},\"FUseOrgId\": {\"FNumber\": \"100\"},\"FSubHeadEntity\": {\"FTimeUnit\": \"H\"},\"SubHeadEntity\": {\"FErpClsID\": \"1\",\"FFeatureItem\": \"1\",\"FCategoryID\": {\"FNumber\": \"CHLB01_SYS\"},\"FTaxType\": {\"FNumber\": \"WLDSFL01_SYS\"},\"FTaxRateId\": {\"FNUMBER\": \"SL02_SYS\"},\"FBaseUnitId\": {\"FNumber\": \"Pcs\"},\"FIsPurchase\": true,\"FIsInventory\": true,\"FIsSale\": true,\"FWEIGHTUNITID\": {\"FNUMBER\": \"kg\"},\"FVOLUMEUNITID\": {\"FNUMBER\": \"m\"}},\"SubHeadEntity1\": {\"FStoreUnitID\": {\"FNumber\": \"Pcs\"},\"FUnitConvertDir\": \"1\",\"FIsLockStock\": true,\"FCountCycle\": \"1\",\"FCountDay\": 1,\"FCurrencyId\": {\"FNumber\": \"PRE001\"},\"FSNManageType\": \"1\",\"FSNGenerateTime\": \"1\"},\"SubHeadEntity2\": {\"FSaleUnitId\": {\"FNumber\": \"Pcs\"},\"FSalePriceUnitId\": {\"FNumber\": \"Pcs\"},\"FMaxQty\": 100000,\"FIsReturn\": true,\"FISAFTERSALE\": true,\"FISPRODUCTFILES\": true,\"FWARRANTYUNITID\": \"D\",\"FOutLmtUnit\": \"SAL\"},\"SubHeadEntity3\": {\"FPurchaseUnitId\": {\"FNumber\": \"Pcs\"},\"FPurchasePriceUnitId\": {\"FNumber\": \"Pcs\"},\"FQuotaType\": \"1\",\"FIsReturnMaterial\": true,\"FPOBillTypeId\": {\"FNUMBER\": \"CGSQD01_SYS\"},\"FPrintCount\": 1,\"FMinPackCount\": 1},\"SubHeadEntity4\": {\"FPlanningStrategy\": \"1\",\"FMfgPolicyId\": {\"FNumber\": \"ZZCL001_SYS\"},\"FFixLeadTimeType\": \"1\",\"FVarLeadTimeType\": \"1\",\"FCheckLeadTimeType\": \"1\",\"FOrderIntervalTimeType\": \"3\",\"FMaxPOQty\": 100000,\"FEOQ\": 1,\"FVarLeadTimeLotSize\": 1,\"FIsMrpComBill\": true,\"FReserveType\": \"1\",\"FCanDelayDays\": 999,\"FAllowPartDelay\": true,\"FPlanOffsetTimeType\": \"1\",\"FWriteOffQty\": 1},\"SubHeadEntity5\": {\"FProduceUnitId\": {\"FNumber\": \"Pcs\"},\"FProduceBillType\": {\"FNUMBER\": \"SCDD03_SYS\"},\"FOrgTrustBillType\": {\"FNUMBER\": \"SCDD06_SYS\"},\"FBOMUnitId\": {\"FNumber\": \"Pcs\"},\"FIssueType\": \"1\",\"FOverControlMode\": \"1\",\"FMinIssueQty\": 1,\"FMinIssueUnitId\": {\"FNUMBER\": \"Pcs\"},\"FStandHourUnitId\": \"3600\",\"FBackFlushType\": \"1\"},\"SubHeadEntity7\": {\"FSubconUnitId\": {\"FNumber\": \"Pcs\"},\"FSubconPriceUnitId\": {\"FNumber\": \"Pcs\"},\"FSubBillType\": {\"FNUMBER\": \"WWDD01_SYS\"}},\"FEntityAuxPty\": [{\"FAuxPropertyId\": {\"FNumber\": \"10\"}},{\"FAuxPropertyId\": {\"FNumber\": \"20\"}},{\"FAuxPropertyId\": {\"FNumber\": \"30\"}}],\"FEntityInvPty\": [{\"FInvPtyId\": {\"FNumber\": \"01\"},\"FIsEnable\": true},{\"FInvPtyId\": {\"FNumber\": \"02\"},\"FIsEnable\": true},{\"FInvPtyId\": {\"FNumber\": \"03\"}},{\"FInvPtyId\": {\"FNumber\": \"04\"}},{\"FInvPtyId\": {\"FNumber\": \"06\"}}]}}";
        String result = api.save("BD_Material",  data);
        Gson gson = new Gson();
        RepoRet sRet = gson.fromJson(result, RepoRet.class);
        if (sRet.isSuccessfully()) {
            materid = sRet.getResult().getId();
            System.out.printf("物料保存接口: %s%n", gson.toJson(sRet.getResult()));
        } else {
            fail("物料保存接口: " + gson.toJson(sRet.getResult()));
        }
    }


    /*本接口用于实现物料 (BD_Material) 的提交功能*/
    @Test
    public void btestSubmitMaterial() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String data = "{\"CreateOrgId\": 0,\"Numbers\": "+"\""+FNumber+"\""+" ,\"Ids\": \"\",\"SelectedPostId\": 0,\"NetworkCtrl\": \"\",\"IgnoreInterationFlag\": \"\"}";
        String result = api.submit("BD_Material", data);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
            System.out.printf("物料提交接口: %s%n", gson.toJson(repoRet.getResult()));
        } else {
            fail("物料提交接口: " + gson.toJson(repoRet.getResult()));
        }

    }

    /*本接口用于实现物料 (BD_Material) 的审核功能*/
    @Test
    public void ctestauditMaterial() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String data = "{\"CreateOrgId\": 0,\"Numbers\": ["+"\""+FNumber+"\""+"],\"Ids\": \"\",\"InterationFlags\": \"\",\"NetworkCtrl\": \"\",\"IsVerifyProcInst\": \"\",\"IgnoreInterationFlag\": \"\"}";
        String result = api.audit("BD_Material", data);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
            System.out.printf("物料审核接口: %s%n", gson.toJson(repoRet.getResult()));
        } else {
            fail("物料审核接口: "+gson.toJson(repoRet.getResult()));
        }

    }



    /*本接口用于实现物料 (BD_Material) 的分配功能*/
    @Test
    public void etestallocateMaterial() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String data = "{ \"PkIds\": "+materid+", \"TOrgIds\": \"100002\"}";
        String result = api.allocate("BD_Material", data);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
            System.out.printf("物料分配接口: %s%n", gson.toJson(repoRet.getResult()));
        } else {
            fail("物料分配接口: "+gson.toJson(repoRet.getResult()));
        }

    }

    /*本接口用于实现物料 (BD_Material) 的取消分配功能*/
    @Test
    public void ftestcancelAllocatetMaterial() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String data = "{ \"PkIds\": "+materid+", \"TOrgIds\": \"100002\"}";
        String result = api.cancelAllocate("BD_Material", data);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
            System.out.printf("物料取消分配接口: %s%n", gson.toJson(repoRet.getResult()));
        } else {
            fail("物料取消分配接口: "+gson.toJson(repoRet.getResult()));
        }

    }

    /*本接口用于实现物料 (BD_Material) 的反审核功能*/
    @Test
    public void gestunauditMaterial() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String data = "{\"CreateOrgId\": 0,\"Numbers\": ["+"\""+FNumber+"\""+"],\"Ids\": \"\",\"InterationFlags\": \"\",\"NetworkCtrl\": \"\",\"IsVerifyProcInst\": \"\",\"IgnoreInterationFlag\": \"\"}";
        String result = api.unAudit("BD_Material", data);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
            System.out.printf("物料反审核接口: %s%n", gson.toJson(repoRet.getResult()));
        } else {
            fail("物料反审核接口: " + gson.toJson(repoRet.getResult()));
        }
    }


    /*本接口用于实现物料 (BD_Material) 的附件上传功能*/
    @Test
    public void htestAttachmentUploadMaterial() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String path=(new File(".")).getCanonicalPath() + "/image2.png";
        byte[] buffer=image2Bytes(path);
        String imgbase64=new String(Base64.getEncoder().encode(buffer));
        String  json = "{\"FileName\":\"1016.txt\",\"FEntryKey\":\"\",\"FormId\": \"BD_MATERIAL\",\"IsLast\": true,\"InterId\": "+materid+"," +
                "\"BillNO\": "+"\""+FNumber+"\""+",\"AliasFileName\": \"test\",\"SendByte\": \""+imgbase64+"\"}";
        String result = api.attachmentUpload(json);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
            JsonElement jsondata = new JsonParser().parse(result);
            fileid = jsondata.getAsJsonObject().get("Result").getAsJsonObject().get("FileId").toString();
            System.out.printf("物料附件上传接口: %s%n", result);
        } else {
            fail("物料附件上传接口: " + result);
        }
    }

    public static byte[] image2Bytes(String imgSrc) throws Exception {
        FileInputStream fin = new FileInputStream(new File(imgSrc));
        //可能溢出,简单起见就不考虑太多,如果太大就要另外想办法，比如一次传入固定长度byte[]
        byte[] bytes  = new byte[fin.available()];
        //将文件内容写入字节数组，提供测试的case
        fin.read(bytes);

        fin.close();
        return bytes;
    }




    /*本接口用于实现物料 (BD_Material) 的附件下载功能*/
    @Test
    public void itestattachmentDownLoadMaterial() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String  json = " {\"FileId\": "+fileid+", \"StartIndex\": 0}";
        String result = api.attachmentDownLoad(json);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
            System.out.printf("物料附件下载接口: %s%n", result);
        } else {
            fail("物料附件下载接口: " + result);
        }
    }


    /*本接口用于实现物料 (BD_Material) 的禁用功能*/
    @Test
    public void jtestForbidMaterial() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String data = "{\"CreateOrgId\": 0,\"Numbers\": ["+"\""+FNumber+"\""+"],\"Ids\": \"\",\"PkEntryIds\":[],\"NetworkCtrl\": \"\",\"IgnoreInterationFlag\": \"\"}";
        String result = api.excuteOperation("BD_Material", "Forbid", data);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {

            System.out.printf("物料禁用接口: %s%n", gson.toJson(repoRet.getResult()));
        } else {
            fail("物料提交接口: " + gson.toJson(repoRet.getResult()));
        }
    }

    /*本接口用于实现物料 (BD_Material) 的反禁用功能*/
    @Test
    public void ktestenableMaterial() throws Exception {

        K3CloudApi api = new K3CloudApi();
        String data = "{\"CreateOrgId\": 0,\"Numbers\": ["+"\""+FNumber+"\""+"],\"Ids\": \"\",\"PkEntryIds\":[],\"NetworkCtrl\": \"\",\"IgnoreInterationFlag\": \"\"}";
        String result = api.excuteOperation("BD_Material", "enable",data);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {

            System.out.printf("物料反禁用接口: %s%n", gson.toJson(repoRet.getResult()));
        } else {
            fail("物料反禁用接口: " + gson.toJson(repoRet.getResult()));
        }
    }


    //todo  查询具体物料接口   查询具体sku接口    通过物料ID
    /*本接口用于实现物料 (BD_Material) 的查看功能*/
    @Test
    public void ltestviewMaterialForId() throws Exception {
        String num = "134628";
        Properties properties = new Properties();
        File file = new File((new File("./src")).getCanonicalPath() + "/kdwebapi.properties");
        System.out.println("读取根目录下的配置文件->" + file.getPath());
        InputStream inputStream = new FileInputStream(file.getPath());
        properties.load(new InputStreamReader(inputStream, "utf-8"));
        inputStream.close();
        IdentifyInfo  iden = new IdentifyInfo();
        iden.setUserName(properties.getProperty("X-KDApi-UserName"));
        iden.setAppId(properties.getProperty("X-KDApi-AppID"));
        iden.setdCID(properties.getProperty("X-KDApi-AcctID"));
        iden.setAppSecret(properties.getProperty("X-KDApi-AppSec"));
        iden.setlCID(2052);
        iden.setServerUrl(properties.getProperty("X-KDApi-ServerUrl"));
        K3CloudApi api = new K3CloudApi(iden);
        Map<String, Object> sendMap = new HashMap<>();
        sendMap.put("Number", "");
        sendMap.put("Id", num);
        sendMap.put("IsSortBySeq", "false");
        sendMap.put("CreateOrgId", 0);
        String data = JSONObject.toJSONString(sendMap);
        String result = api.view("BD_Material", data);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
            System.out.printf("物料查看接口: %s%n", result);
        } else {
            fail("物料查看接口: " + result);
        }
    }

    //todo  查询具体物料接口   查询具体sku接口    通过物料Code
    /*本接口用于实现物料 (BD_Material) 的查看功能*/
    @Test
    public void ltestviewMaterialForCode() throws Exception {
        String num = "134629";
//        String num = "冯工测试物料编码01";
        Properties properties = new Properties();
        File file = new File((new File("./src")).getCanonicalPath() + "/kdwebapi.properties");
        System.out.println("读取根目录下的配置文件->" + file.getPath());
        InputStream inputStream = new FileInputStream(file.getPath());
        properties.load(new InputStreamReader(inputStream, "utf-8"));
        inputStream.close();
        IdentifyInfo  iden = new IdentifyInfo();
        iden.setUserName(properties.getProperty("X-KDApi-UserName"));
        iden.setAppId(properties.getProperty("X-KDApi-AppID"));
        iden.setdCID(properties.getProperty("X-KDApi-AcctID"));
        iden.setAppSecret(properties.getProperty("X-KDApi-AppSec"));
        iden.setlCID(2052);
        iden.setServerUrl(properties.getProperty("X-KDApi-ServerUrl"));
        K3CloudApi api = new K3CloudApi(iden);
        Map<String, Object> sendMap = new HashMap<>();
        sendMap.put("Number", num);
        sendMap.put("Id", "");
        sendMap.put("IsSortBySeq", "false");
        sendMap.put("CreateOrgId", 0);
        String data = JSONObject.toJSONString(sendMap);
        String result = api.view("BD_Material", data);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
            System.out.printf("物料查看接口: %s%n", result);
        } else {
            fail("物料查看接口: " + result);
        }
    }


    //todo  查询具体销售出库单接口
    /*本接口用于实现物料 (BD_Material) 的查看功能*/
    @Test
    public void ltestviewOutStock() throws Exception {
        String num = "XSCKD003333";
        Properties properties = new Properties();
        File file = new File((new File("./src/main/resources")).getCanonicalPath() + "/kdwebapi.properties");
//        File file = new File((new File("./src")).getCanonicalPath() + "/kdwebapi.properties");
        System.out.println("读取根目录下的配置文件->" + file.getPath());
        InputStream inputStream = new FileInputStream(file.getPath());
        properties.load(new InputStreamReader(inputStream, "utf-8"));
        inputStream.close();
        IdentifyInfo  iden = new IdentifyInfo();
        iden.setUserName(properties.getProperty("X-KDApi-UserName"));
        iden.setAppId(properties.getProperty("X-KDApi-AppID"));
        iden.setdCID(properties.getProperty("X-KDApi-AcctID"));
        iden.setAppSecret(properties.getProperty("X-KDApi-AppSec"));
        iden.setlCID(2052);
        iden.setServerUrl(properties.getProperty("X-KDApi-ServerUrl"));
        K3CloudApi api = new K3CloudApi(iden);
        Map<String, Object> sendMap = new HashMap<>();
        sendMap.put("Number", num);
        sendMap.put("Id", "");
        sendMap.put("IsSortBySeq", "false");
        sendMap.put("CreateOrgId", 0);
        String data = JSONObject.toJSONString(sendMap);


//        String  data = "{\"CreateOrgId\": 0,\"Number\": "+"\""+num+"\""+",\"Id\": \"\",\"IsSortBySeq\": \"false\"}";
        String result = api.view("SAL_OUTSTOCK", data);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
            Map res = (LinkedTreeMap<String,Object>)repoRet.getResult().getResult();
            List salOutstockentryList = (ArrayList<Map<String,Object>>)res.get("SAL_OUTSTOCKENTRY");
            Map  salOutstockentryMap= (LinkedTreeMap<String,Object>)salOutstockentryList.get(0);
            Map stockID = (LinkedTreeMap<String,Object>)salOutstockentryMap.get("StockID");
            if(MapUtil.isEmpty(stockID)){
            }
            String number = (String) stockID.get("Number");
            System.out.printf("查询具体销售出库单接口: %s%n", result);
            System.out.printf("查询具体销售出库单的仓库: %s%n", number);
        } else {
            fail("查询具体销售出库单接口: " + result);
        }
    }

    //todo  查询具体其他出库单接口
    /*本接口用于实现物料 (BD_Material) 的查看功能*/
    @Test
    public void ltestviewOtherOutStock() throws Exception {
        String num = "QTCK000013";
        Properties properties = new Properties();
        File file = new File((new File("./src/main/resources")).getCanonicalPath() + "/kdwebapi.properties");
//        File file = new File((new File("./src")).getCanonicalPath() + "/kdwebapi.properties");
        System.out.println("读取根目录下的配置文件->" + file.getPath());
        InputStream inputStream = new FileInputStream(file.getPath());
        properties.load(new InputStreamReader(inputStream, "utf-8"));
        inputStream.close();
        IdentifyInfo  iden = new IdentifyInfo();
        iden.setUserName(properties.getProperty("X-KDApi-UserName"));
        iden.setAppId(properties.getProperty("X-KDApi-AppID"));
        iden.setdCID(properties.getProperty("X-KDApi-AcctID"));
        iden.setAppSecret(properties.getProperty("X-KDApi-AppSec"));
        iden.setlCID(2052);
        iden.setServerUrl(properties.getProperty("X-KDApi-ServerUrl"));
        K3CloudApi api = new K3CloudApi(iden);
        Map<String, Object> sendMap = new HashMap<>();
        sendMap.put("Number", num);
        sendMap.put("Id", "");
        sendMap.put("IsSortBySeq", "false");
        sendMap.put("CreateOrgId", 0);
        String data = JSONObject.toJSONString(sendMap);


        String result = api.view("STK_MisDelivery", data);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
            Map res = (LinkedTreeMap<String,Object>)repoRet.getResult().getResult();
            List salOutstockentryList = (ArrayList<Map<String,Object>>)res.get("BillEntry");
            Map  salOutstockentryMap= (LinkedTreeMap<String,Object>)salOutstockentryList.get(0);
            Map stockID = (LinkedTreeMap<String,Object>)salOutstockentryMap.get("StockId");
            String stockNum = (String) stockID.get("Number");
            if(MapUtil.isEmpty(stockID)){
            }
            String number = (String) stockID.get("Number");
            System.out.printf("查询具体其他出库单接口: %s%n", result);
            System.out.printf("查询具体其他出库单接口: %s%n", stockNum);
        } else {
            fail("查询具体其他出库单接口: " + result);
        }
    }



    /*本接口用于实现物料 (BD_Material)的单据查询功能*/
    @Test
    public void mtestQueryMaterial2() throws Exception {
        String num = "134629";
        K3CloudApi api = new K3CloudApi();
        Gson gson = new Gson();
        QueryParam<List<Map<String,Object>>> para = new QueryParam<>();
        para.setFormId("BD_Material");
        para.setFieldKeys("FMATERIALID,FNumber,FName,FCreateOrgId,FUseOrgId");
        Map<String,Object> map = new HashMap<>();
        map.put("Left", "(");
        map.put("FieldName", "FMATERIALID");
        map.put("Compare", "=");
        map.put("Value", num);
        map.put("Right", ")");
        map.put("Logic", "and");
        List<Map<String,Object>> list = new ArrayList<>();
        list.add(map);
        para.setFilterString(list);
        System.out.println("list: " + gson.toJson(list));
        List result = api.executeBillQuery(para, BdCustomer.class);
        System.out.println("物料单据查询接口: " + gson.toJson(result));
    }


    //todo   查询物料列表接口
    /*本接口用于实现物料 (BD_Material)的单据查询功能*/
    @Test
    public void mtestQueryMaterial() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String json = "{\n" +
                "    \"FormId\": \"BD_Material\",\n" +
                //                  金蝶物料Id  金蝶物料code 名称    组织ID      使用组织     库存单位Id
                "    \"FieldKeys\": \"FMATERIALID,FNumber,FName,FCreateOrgId,FUseOrgId,FStockID\",\n" +
                "}";

        List<List<Object>> lists = api.executeBillQuery(json);
        System.out.println("物料列表查询接口: " + lists);
    }

    //todo   查询仓库列表接口
    /*本接口用于实现物料 (BD_Material)的单据查询功能*/
    @Test
    public void queryStockList() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String json = "{\n" +
                "    \"FormId\": \"BD_STOCK\",\n" +
                //                  仓库地址  仓库编码   名称    组织ID      使用组织     库存单位Id
                "    \"FieldKeys\": \"FAddress,FNumber,FName,FCreateOrgId,FStockID\",\n" +
                "}";

        List<List<Object>> lists = api.executeBillQuery(json);
        System.out.println("仓库列表查询接口: " + lists);
    }

    //todo   查询具体仓库信息
    /*本接口用于实现物料 (BD_Material)的单据查询功能*/
    @Test
    public void queryStockList11() throws Exception {
        String num = "CK016";
        K3CloudApi api = new K3CloudApi();
        Gson gson = new Gson();
        QueryParam<List<Map<String,Object>>> para = new QueryParam<>();
        para.setFormId("BD_STOCK");
        para.setFieldKeys("FAddress,FNumber,FName,FCreateOrgId,FStockID");
        Map<String,Object> map = new HashMap<>();
        map.put("Left", "(");
        map.put("FieldName", "FNumber");
        map.put("Compare", "=");
        map.put("Value", num);
        map.put("Right", ")");
        map.put("Logic", "and");
        List<Map<String,Object>> list = new ArrayList<>();
        list.add(map);
        para.setFilterString(list);
        System.out.println("list: " + gson.toJson(list));
        List result = api.executeBillQuery(para, BDStock.Model.class);
        System.out.println("查询仓库列表接口: " + gson.toJson(result));
    }


    //todo   查询销售出库单列表接口
    /*本接口用于实现物料 (BD_Material)的单据查询功能*/
    @Test
    public void mtestQueryOutStockList() throws Exception {
        K3CloudApi api = new K3CloudApi();
        Gson gson = new Gson();
        QueryParam<List<Map<String,Object>>> para = new QueryParam<>();
        para.setFormId("SAL_OUTSTOCK");
        //                 单据编号，  客户，     物料编码，      数量     销售组织， 日期    仓库      价格     订单类型
        para.setFieldKeys("FBillNo,FCustomerID,FMaterialID,FRealQty,FSaleOrgId,FDate,FStockID,FPrice,FBillTypeID");
        Map<String,Object> map = new HashMap<>();
        map.put("Left", "(");
        map.put("FieldName", "FDate");
        map.put("Compare", ">=");
        String yesterday = DateUtils.getYesterday("yyyy-MM-dd");
        map.put("Value", "2023-12-01T00:00:00");
//        map.put("Value", yesterday+"T00:00:00");
        map.put("Right", ")");
        map.put("Logic", "and");
        List<Map<String,Object>> list = new ArrayList<>();
        list.add(map);
        para.setFilterString(list);
        List<List<Object>> lists = api.executeBillQuery(para.toJson());
        for (List<Object> objects : lists) {

        }
        System.out.println("查询销售出库单列表接口: " + gson.toJson(lists));
    }

    //todo   查询其他出库单列表接口
    /*本接口用于实现物料 (BD_Material)的单据查询功能*/
    @Test
    public void queryOtherOutstock() throws Exception {
        K3CloudApi api = new K3CloudApi();
        Gson gson = new Gson();
        QueryParam<List<Map<String,Object>>> para = new QueryParam<>();
        para.setFormId("STK_MisDelivery");
//        //                 单据编号， 客户id     物料编码，  日期    价格     仓库      订单类型
//        para.setFieldKeys("FBillNo,FCustId,FMaterialID,FDate,FPrice,FStockID,FBillTypeID");
        //                 单据编号，  物料编码，     数量   日期    仓库      价格   客户id
        para.setFieldKeys("FBillNo,FMaterialID,FBaseQty,FDate,FStockID,FPrice,FCustId,FBILLTYPEID");

        Map<String,Object> map = new HashMap<>();
        map.put("Left", "(");
        map.put("FieldName", "FDate");
        map.put("Compare", ">=");
        String yesterday = DateUtils.getYesterday("yyyy-MM-dd");
        map.put("Value", yesterday);
//        map.put("Value", yesterday+"T00:00:00");
        map.put("Right", ")");
        map.put("Logic", "and");
        List<Map<String,Object>> list = new ArrayList<>();
        list.add(map);
        para.setFilterString(list);
        List<List<Object>> lists = api.executeBillQuery(para.toJson());
        for (List<Object> objects : lists) {

        }
        System.out.println("查询其他出库单列表接口: " + gson.toJson(lists));
    }

    @Test
    public void queryTransferDirect(){
     try {
         K3CloudApi api = new K3CloudApi();
         QueryParam<List<Map<String, Object>>> para = new QueryParam<>();
         para.setFormId("STK_TransferDirect");
         //                  日期    调拨单号   单据类型      调入货主类型        调入货主        调出货主类型         调出货主         调拨方向          物料编码      物料名称        调出仓库   调入仓库      单位   数量  成本价
         para.setFieldKeys("FDate,FBillNo,FBillTypeID,FOwnerTypeIdHead,FOwnerIdHead,FOwnerTypeOutIdHead,FOwnerOutIdHead,FTransferDirect,FMaterialId,FMaterialName,FSrcStockId,FDestStockId,FUnitID,FQty,FPrice");
         Map<String, Object> map = new HashMap<>();
         map.put("Left", "(");
         map.put("FieldName", "FDate");
         map.put("Compare", ">=");
         String yesterday = DateUtils.getYesterday(DateUtils.YYYY_MM_DD);
         map.put("Value", yesterday + "T00:00:00");
         map.put("Right", ")");
         map.put("Logic", "and");

//
//         Map<String, Object> srcStockIdmap = new HashMap<>();
//         srcStockIdmap.put("Left", "(");
//         srcStockIdmap.put("FieldName", "FSrcStockId");
//         srcStockIdmap.put("Compare", "=");
//         srcStockIdmap.put("Value", "134628");
//         srcStockIdmap.put("Right", ")");
//         srcStockIdmap.put("Logic", "or");

         Map<String, Object> destStockIdMap = new HashMap<>();
         destStockIdMap.put("Left", "(");
         destStockIdMap.put("FieldName", "FDestStockId");
         destStockIdMap.put("Compare", "=");
         destStockIdMap.put("Value", "134628");
         destStockIdMap.put("Right", ")");
         destStockIdMap.put("Logic", "or");


         List<Map<String, Object>> list = new ArrayList<>();
         list.add(map);
//         list.add(srcStockIdmap);
         list.add(destStockIdMap);

         para.setFilterString(list);
         List<List<Object>> lists = api.executeBillQuery(para.toJson());
         System.out.println("======="+new Gson().toJson(lists));
         for (List<Object> objects : lists) {
             //如果是调出仓库是134628的，就是调出
                if ((objects.get(10).toString()).equals("134628")) {
                    System.out.println("调出仓库是134628的，就是调出");
                }
                //如果调入仓库是134628的，就是调入
                if ((objects.get(11).toString()).equals("134628")) {
                    System.out.println("调入仓库是134628的，就是调入");
                }

         }
     }catch (Exception e){
         log.error("查询直接调拨单列表接口异常",e);
     }
    }


    /*本接口用于实现物料 (BD_Material)的单据查询功能*/
    @Test
    public void mtestQueryMaterialList() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String json = "{\n" +
                "    \"FormId\": \"BD_Material\",\n" +
                "    \"FieldKeys\": \"FMATERIALID,FNumber,FName,FCreateOrgId,FUseOrgId,\",\n" +
                "    \"FilterString\": \"FNumber=\'"  + "\'\",\n" +
                "    \"OrderString\": \"\",\n" +
                "    \"TopRowCount\": 0,\n" +
                "    \"StartRow\": 0,\n" +
                "    \"Limit\": 2000,\n" +
                "    \"SubSystemId\": \"\"\n" +
                "}";
        String result = String.valueOf(api.executeBillQuery(json));
        System.out.println("物料单据查询接口: " + result);

    }

    /*本接口用于实现物料 (BD_Material)的单据查询功能*/
    @Test
    public void mtestMaterialBillQuery() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String json = "{\n" +
                "    \"FormId\": \"BD_Material\",\n" +
                "    \"FieldKeys\": \"FMATERIALID,FNumber,FName,FCreateOrgId,FUseOrgId,\",\n" +
                "    \"FilterString\": \"FNumber=\'" + FNumber + "\'\",\n" +
                "    \"OrderString\": \"\",\n" +
                "    \"TopRowCount\": 0,\n" +
                "    \"StartRow\": 0,\n" +
                "    \"Limit\": 2000,\n" +
                "    \"SubSystemId\": \"\"\n" +
                "}";
        String result = api.billQuery(json);
        System.out.println("物料单据查询接口: " + result);
    }

    /*本接口用于实现物料 (BD_Material)的删除功能*/
    @Test
    public void ntestdeleteMaterial() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String  data = "{\"CreateOrgId\": 0,\"Numbers\": ["+"\""+FNumber+"\""+"],\"Id\": \"\",\"IsSortBySeq\": \"false\"}";
        String result = api.delete("BD_Material", data);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {

            System.out.printf("物料删除接口: %s%n", gson.toJson(repoRet.getResult().getResponseStatus().getSuccessEntitys()));
        } else {
            fail(gson.toJson(repoRet.getResult().getResponseStatus()));
        }
    }

    /*本接口用于实现物料 (BD_Material) 的分组保存功能*/
    @Test
    public void otestgroupSaveMaterial() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String  json = "{\"GroupFieldKey\": \"\", \"GroupPkId\": 0, \"FParentId\": 0, \"FNumber\": "+"\""+FNumber+"\""+", \"FName\": "+"\""+FNumber+"\""+", \"FDescription\": \"\"}";
        String result = api.groupSave("BD_Material", json);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {

            System.out.printf("物料分组保存接口: %s%n", gson.toJson(repoRet.getResult().getResponseStatus().getSuccessEntitys()));
            String re = gson.toJson(repoRet.getResult().getResponseStatus().getSuccessEntitys().get(0));
            JsonElement jsondata = new JsonParser().parse(re);
            JsonElement id = jsondata.getAsJsonObject().get("Id");
            groupid = id.toString();
        } else {
            fail("物料分组保存接口: " + gson.toJson(repoRet.getResult().getResponseStatus()));
        }

    }


    /*本接口用于实现物料 (BD_Material) 的分组查询功能*/
    @Test
    public void ptestqueryGroupInfoMaterial() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String  json = "{\"FormId\": \"BD_MATERIAL\", \"GroupFieldKey\": \"FMaterialGroup\", \"GroupPkIds\": "+groupid+", \"Ids\": \"\"}";
        String result = api.queryGroupInfo(json);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {

            System.out.printf("物料分组查询接口: %s%n", gson.toJson(repoRet.getResult()));
        } else {
            fail("物料分组查询接口: " + gson.toJson(repoRet.getResult().getResponseStatus()));
        }

    }

    /*本接口用于实现物料 (BD_Material) 的分组删除功能*/
    @Test
    public void qtestgroupDeleteMaterial() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String  json = "{\"FormId\": \"BD_MATERIAL\", \"GroupFieldKey\": \"FMaterialGroup\", \"GroupPkIds\": "+groupid+",}";
        String result = api.groupDelete(json);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {

            System.out.printf("物料分组删除接口: %s%n", gson.toJson(repoRet.getResult()));
        } else {
            fail("物料分组删除接口: " + gson.toJson(repoRet.getResult().getResponseStatus()));
        }

    }

    /*本接口用于实现物料 (BD_Material) 的切换组织接口功能*/
    @Test
    public void rtestswitchOrg() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String  json = "{ \"OrgNumber\": \"200\"}";
        String result = api.switchOrg(json);
        /*为不影响组织数据，切换组织后再切换回来*/
        String  json2 = "{ \"OrgNumber\": \"100\"}";
        String result2 = api.switchOrg(json);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result2, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {

            System.out.printf("物料切换组织接口: %s%n", gson.toJson(repoRet.getResult()));
        } else {
            fail("物料切换组织接口: " + gson.toJson(repoRet.getResult().getResponseStatus()));
        }

    }


    /*本接口用于实现物料 (BD_Material) 的批量保存功能*/
    @Test
    public void stestBatchSaveCustomer() throws Exception {
        K3CloudApi api = new K3CloudApi();
        List<String> materialsmodel = new ArrayList<String>();
        int count =0;
        for (int i = 0; i < 2; i++) {
            String m =  "{\"FNumber\": "+"\""+SeqHelper.genNumber("WL")+"\""+",\"FName\": "+"\""+"auwl_" + UUID.randomUUID().toString()+"\""+",\"FImgStorageType\": \"A\",\"FCreateOrgId\": {\"FNumber\": \"100\"},\"FUseOrgId\": {\"FNumber\": \"100\"},\"FSubHeadEntity\": {\"FTimeUnit\": \"H\"},\"SubHeadEntity\": {\"FErpClsID\": \"1\",\"FFeatureItem\": \"1\",\"FCategoryID\": {\"FNumber\": \"CHLB01_SYS\"},\"FTaxType\": {\"FNumber\": \"WLDSFL01_SYS\"},\"FTaxRateId\": {\"FNUMBER\": \"SL02_SYS\"},\"FBaseUnitId\": {\"FNumber\": \"Pcs\"},\"FIsPurchase\": true,\"FIsInventory\": true,\"FIsSale\": true,\"FWEIGHTUNITID\": {\"FNUMBER\": \"kg\"},\"FVOLUMEUNITID\": {\"FNUMBER\": \"m\"}},\"SubHeadEntity1\": {\"FStoreUnitID\": {\"FNumber\": \"Pcs\"},\"FUnitConvertDir\": \"1\",\"FIsLockStock\": true,\"FCountCycle\": \"1\",\"FCountDay\": 1,\"FCurrencyId\": {\"FNumber\": \"PRE001\"},\"FSNManageType\": \"1\",\"FSNGenerateTime\": \"1\"},\"SubHeadEntity2\": {\"FSaleUnitId\": {\"FNumber\": \"Pcs\"},\"FSalePriceUnitId\": {\"FNumber\": \"Pcs\"},\"FMaxQty\": 100000,\"FIsReturn\": true,\"FISAFTERSALE\": true,\"FISPRODUCTFILES\": true,\"FWARRANTYUNITID\": \"D\",\"FOutLmtUnit\": \"SAL\"},\"SubHeadEntity3\": {\"FPurchaseUnitId\": {\"FNumber\": \"Pcs\"},\"FPurchasePriceUnitId\": {\"FNumber\": \"Pcs\"},\"FQuotaType\": \"1\",\"FIsReturnMaterial\": true,\"FPOBillTypeId\": {\"FNUMBER\": \"CGSQD01_SYS\"},\"FPrintCount\": 1,\"FMinPackCount\": 1},\"SubHeadEntity4\": {\"FPlanningStrategy\": \"1\",\"FMfgPolicyId\": {\"FNumber\": \"ZZCL001_SYS\"},\"FFixLeadTimeType\": \"1\",\"FVarLeadTimeType\": \"1\",\"FCheckLeadTimeType\": \"1\",\"FOrderIntervalTimeType\": \"3\",\"FMaxPOQty\": 100000,\"FEOQ\": 1,\"FVarLeadTimeLotSize\": 1,\"FIsMrpComBill\": true,\"FReserveType\": \"1\",\"FCanDelayDays\": 999,\"FAllowPartDelay\": true,\"FPlanOffsetTimeType\": \"1\",\"FWriteOffQty\": 1},\"SubHeadEntity5\": {\"FProduceUnitId\": {\"FNumber\": \"Pcs\"},\"FProduceBillType\": {\"FNUMBER\": \"SCDD03_SYS\"},\"FOrgTrustBillType\": {\"FNUMBER\": \"SCDD06_SYS\"},\"FBOMUnitId\": {\"FNumber\": \"Pcs\"},\"FIssueType\": \"1\",\"FOverControlMode\": \"1\",\"FMinIssueQty\": 1,\"FMinIssueUnitId\": {\"FNUMBER\": \"Pcs\"},\"FStandHourUnitId\": \"3600\",\"FBackFlushType\": \"1\"},\"SubHeadEntity7\": {\"FSubconUnitId\": {\"FNumber\": \"Pcs\"},\"FSubconPriceUnitId\": {\"FNumber\": \"Pcs\"},\"FSubBillType\": {\"FNUMBER\": \"WWDD01_SYS\"}},\"FEntityAuxPty\": [{\"FAuxPropertyId\": {\"FNumber\": \"10\"}},{\"FAuxPropertyId\": {\"FNumber\": \"20\"}},{\"FAuxPropertyId\": {\"FNumber\": \"30\"}}],\"FEntityInvPty\": [{\"FInvPtyId\": {\"FNumber\": \"01\"},\"FIsEnable\": true},{\"FInvPtyId\": {\"FNumber\": \"02\"},\"FIsEnable\": true},{\"FInvPtyId\": {\"FNumber\": \"03\"}},{\"FInvPtyId\": {\"FNumber\": \"04\"}},{\"FInvPtyId\": {\"FNumber\": \"06\"}}]}";
            materialsmodel.add(m);
            count = i+1;
        }
        String data = "{\"NumberSearch\":\"true\",\"ValidateFlag\":\"true\",\"IsDeleteEntry\":\"true\",\"IsEntryBatchFill\":\"true\",\"NeedUpDateFields\":[],\"NeedReturnFields\":[],\"SubSystemId\":\"\",\"InterationFlags\":\"\",\"Model\":"+materialsmodel+",\"BatchCount\":"+count+",\"IsVerifyBaseDataField\":\"false\",\"IsAutoAdjustField\":\"false\",\"IgnoreInterationFlag\":\"false\",\"IsControlPrecision\":\"false\",\"ValidateRepeatJson\":\"false\",}";
        // 批量保存物料信息
        String sRet = api.batchSave("BD_Material", data);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(sRet, RepoRet.class);
        if (repoRet.isSuccessfully()) {
            for (int i = 0; i < materialsmodel.size(); i++)
                System.out.println(String.format("批量保持物料:%s%s", i+1,
                        gson.toJson(repoRet.getResult().getResponseStatus().getSuccessEntitys().get(i))));
        } else {
            fail("物料批量保存接口："+gson.toJson(repoRet.getResult()));
        }
    }

    /*本接口用于实现发送消息功能*/
    @Test
    public void ttestsendmsg() throws Exception {
        K3CloudApi api = new K3CloudApi();
        String  data =  "{\"Model\":[{\"FTitle\":\"我是标题\",\"FContent\":\"我是内容\",\"FReceivers\":\"demo\",\"FType\":\"1\"}]}";
        String result = api.sendMsg(data);
        Gson gson = new Gson();
        RepoRet repoRet = gson.fromJson(result, RepoRet.class);
        if (repoRet.getResult().getResponseStatus().isIsSuccess()) {
            System.out.printf("消息发送接口: %s%n", gson.toJson(repoRet.getResult()));
        } else {
            fail("消息发送接口: " + gson.toJson(repoRet.getResult().getResponseStatus()));
        }
    }

    /*本接口用于接收token*/
    @Test
    public void getTokenForKingdee() throws Exception {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\n    \"parameters\": [\n        \"6588dca82559c5\",\n        \"chen\",\n        \"kingdee*123\",\n        2052\n    ]\n}");
        Request request = new Request.Builder()
                .url("http://36.137.37.13:9010/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc")
                .method("POST", body)
//                .addHeader("kdservice-sessionid", "7c60f765-8317-4b14-b1cf-b20f45765681")
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        System.out.println(response);
    }

}




