package com.malk.zhiwei;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.kingdee.bos.webapi.entity.IdentifyInfo;
import com.kingdee.bos.webapi.entity.RepoRet;
import com.kingdee.bos.webapi.sdk.K3CloudApi;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
import com.malk.server.aliwork.YDSearch;
import com.malk.server.common.McR;
import com.malk.server.dingtalk.DDR;
import com.malk.service.aliwork.YDClient;
import com.malk.service.dingtalk.DDClient;
import com.malk.utils.PublicUtil;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import com.malk.zhiwei.config.KDWebApiConf;
import com.malk.zhiwei.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.*;

@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class JdTest {

    @Autowired
    private KDWebApiConf kdWebApiConf;
    @Autowired
    private DDClient ddClient;

    @Autowired
    private YDClient ydClient;
    @Autowired
    private YDConf ydConf;

    private IdentifyInfo initIden(){
        //注意 1：此处不再使用参数形式传入用户名及密码等敏感信息，改为在登录配置文件中设置。
        //注意 2：必须先配置第三方系统登录授权信息后，再进行业务操作，详情参考各语言版本SDK介绍中的登录配置文件说明。
        //读取配置，初始化SDK
        IdentifyInfo iden = new IdentifyInfo();
        iden.setUserName(kdWebApiConf.getXKDApiUserName());
        iden.setAppId(kdWebApiConf.getXKDApiAppID());
        iden.setdCID(kdWebApiConf.getXKDApiAcctID());
        iden.setAppSecret(kdWebApiConf.getXKDApiAppSec());
        iden.setServerUrl(kdWebApiConf.getXKDApiServerUrl());

        return iden;
    }

    @Test
    public void test(){
        K3CloudApi client = new K3CloudApi(initIden());
        String value="{\"CreateOrgId\":0,\"Number\":\"\",\"Id\":\"\",\"IsSortBySeq\":\"false\"}";
        try {
//            String result=client.view("BAS_PreBaseDataOne",value);
            PreBaseDataOne preBaseDataOne = new PreBaseDataOne();
            preBaseDataOne.setCreateOrgId(value);
            String result=client.submit("BAS_PreBaseDataOne", JSONObject.toJSONString(preBaseDataOne));
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void saveProject(){
        K3CloudApi client = new K3CloudApi(initIden());
        try {
            FBillHead fBillHead = new FBillHead("测试项目","TEST-2026-03-18-001","AI");
            String result=client.save("BD_Customer",JSONObject.toJSONString(UtilMap.map("Model",fBillHead)));
            System.out.println(result); // 保存数据到金蝶
//            JsonObject jsonData = new JsonObject();
//            jsonData.addProperty("Numbers", "TEST-2026-03-18-001");
//            String result=client.audit("BAS_PreBaseDataOne", jsonData.toString());
            System.out.println(result);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Test
    public void saveCust() throws Exception {
        FNumber zd = new FNumber("其他");//终端
        FNumber syb = new FNumber("MPP");//事业部
        FNumber hy = new FNumber("001");//行业
        FNumber sktj = new FNumber("008");//收款条件
        FNumber xsbm = new FNumber("BM000027");//销售部门
        FNumber xsy = new FNumber("0016_GW000014_1");//销售员
        CustomerModel customerModel = new CustomerModel("测试客户3",sktj,hy,syb,zd,"李英","1234",xsbm,xsy);
        System.out.println(saveToAudit("BD_Customer", customerModel));
    }

    private McR saveToAudit(String formid, Object object) throws Exception {
        JSONObject resultObj = new JSONObject();
        K3CloudApi client = new K3CloudApi(initIden());
        String result=client.save(formid,JSONObject.toJSONString(UtilMap.map("Model",object)));
        resultObj.put("save",result);
        Gson gson = new Gson();
        RepoRet sRet = gson.fromJson(result, RepoRet.class);
        if (sRet.isSuccessfully()) {
            JsonObject jsonData = new JsonObject();
            jsonData.addProperty("Ids", sRet.getResult().getId());
            String result2=client.submit(formid, jsonData.toString());
            resultObj.put("save",result2);
            RepoRet sRet2 = gson.fromJson(result, RepoRet.class);
            if (sRet2.isSuccessfully()) {
                JsonObject jsonData3 = new JsonObject();
                jsonData3.addProperty("Ids", sRet2.getResult().getId());
                String result3 = client.audit(formid, jsonData3.toString());
                RepoRet repoRet3 = gson.fromJson(result3, RepoRet.class);
                if (repoRet3.getResult().getResponseStatus().isIsSuccess()) {
                    log.info("审批通过，新增完成");
                    return McR.success(resultObj);
                }
            }
        }
        return McR.error("203",JSONObject.toJSONString(resultObj));
    }

    @Test
    public void queryOrder(){
        K3CloudApi client = new K3CloudApi(initIden());
        try {
            int startRow = 0;
            int limit = 2000;
            BillQuery billQuery = new BillQuery();
            billQuery.setFormId("AR_RECEIVEBILL");
            billQuery.setFieldKeys("FPAYUNIT.FName,FREALRECAMOUNTFOR,FDATE,FSETTLETYPEID,FSETTLETYPEID.FName,F_ABC_Base1,FRECACCOUNTNAME,FACCOUNTID.FNumber,FACCOUNTID.FName,FSALEERID.FName,F_ABC_Base,F_ABC_BaseProperty,FBPBILLNUMBER,FBPBILLPARAMOUNT,FBPBILLTYPE,FEXPIRY");
//            billQuery.setFieldKeys("FBillNo,FBillTypeID.FName,FPAYUNITTYPE,FDate,FPAYUNIT.FName,FCURRENCYID.FName,FRECEIVEAMOUNTFOR_H,FREALRECAMOUNTFOR,FSALEERID.FName,FSETTLETYPEID,FSETTLETYPEID.FName,FPURPOSEID.FName,FACCOUNTID.FNumber,FACCOUNTID.FName,FRECTOTALAMOUNTFOR,FREALRECAMOUNTFOR_D,FCOMMENT");
            List<Map> filterString = new ArrayList<>();
            //审核日期为昨天至今天
            filterString.add(UtilMap.map("FieldName, Compare, Value, Left, Right, Logic","FApproveDate","265",1,"","","0"));//审核日期在今天之前N天以后
//        filterString.add(UtilMap.map("FieldName, Compare, Value, Left, Right, Logic","FApproveDate","420","2025-10-20 00:00:00","","","0"));//审核日期年=XX
//        filterString.add(UtilMap.map("FieldName, Compare, Value, Left, Right, Logic","FNumber","67","35","","","0"));//物料编码等于XX
            billQuery.setFilterString(filterString);
            billQuery.setLimit(limit);
            billQuery.setStartRow(startRow);
            String result=client.billQuery(JSONObject.toJSONString(billQuery));
            JSONArray jsonArray = JSONArray.parseArray(result);
            for(int i=0;i<jsonArray.size();i++){
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                System.out.println(jsonObject);
                Receivebill rb= BeanUtil.toBean(jsonObject, Receivebill.class);
                if(!PublicUtil.isNull(rb.getAssociationFormField_lypey1wr())){
                    List<Map> data=(List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-8E4AA59DFB354F2D922826F47F70B31AZ8ES")
                            .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_lx05suvl",rb.getAssociationFormField_lypey1wr(),"eq"))))
                            .build(), YDConf.FORM_QUERY.retrieve_list).getData();
                    if(data.size()>0){
                        System.out.println(data.get(0).get("formInstanceId"));
                        List<Map> kh=ydConf.associationForm("FORM-8E4AA59DFB354F2D922826F47F70B31AZ8ES", String.valueOf(data.get(0).get("formInstanceId")),rb.getAssociationFormField_lypey1wr(),"",false);
                        rb.setAssociationFormField_lypey1wr(JSONObject.toJSONString(kh));
                    }else{
                        rb.setAssociationFormField_lypey1wr("[]");
                    }
                }
                Map prodata=new HashMap();
                if(!PublicUtil.isNull(rb.getAssociationFormField_lsvmld22())){
                    List<Map> data=(List<Map>) ydClient.queryData(YDParam.builder().formUuid("FORM-2E06211370FA43D3AEAAC0CF7636365491YX")
                            .searchCondition(JSONObject.toJSONString(Arrays.asList(YDConf.searchCondition_TextFiled("textField_m0c4utr2",rb.getAssociationFormField_lsvmld22(),"eq"))))
                            .build(), YDConf.FORM_QUERY.retrieve_list).getData();
                    if(data.size()>0){
                        System.out.println(data.get(0).get("formInstanceId"));
                        Map formData= UtilMap.getMap(data.get(0),"formData");
                        List<Map> kh=ydConf.associationForm("FORM-2E06211370FA43D3AEAAC0CF7636365491YX", String.valueOf(data.get(0).get("formInstanceId")),UtilMap.getString(formData,"textField_m50ci9rk"),"",false);
                        rb.setAssociationFormField_lsvmld22(JSONObject.toJSONString(kh));
                        prodata.put("textField_lwgba84b",formData.get("textField_m0namazl"));
                        prodata.put("textField_lxvrmu61",formData.get("textField_m0namazj"));
                        prodata.put("textField_lypey1wx",formData.get("textField_m0c4utr2"));
                        prodata.put("textField_m1aft8ye",formData.get("textField_m6yurmat"));
                        prodata.put("numberField_lxu21h6c",formData.get("numberField_mdcwz9mr"));
                        prodata.put("numberField_lxu29mvg",formData.get("numberField_mdcwz9mv"));
                        prodata.put("numberField_lxu336sn",formData.get("numberField_m0gb97py"));
                    }else{
                        rb.setAssociationFormField_lsvmld22("[]");
                    }
                }
                prodata.putAll(JSONObject.parseObject(JSONObject.toJSONString(rb.toYiDa())));
                ydClient.operateData(YDParam.builder().formUuid("FORM-9BDAFB39320246EFACC176C9E33E51DC4N40")
                        .formDataJson(JSONObject.toJSONString(prodata)).build(), YDConf.FORM_OPERATION.start);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Test
    public void queryOrder2(){
        Map body = new HashMap();
        body.put("queryWord","李英");
        body.put("offset",0);
        body.put("size",10);
        body.put("fullMatchField",1);
        DDR ddr  = (DDR) UtilHttp.doPost("https://api.dingtalk.com/v1.0/contact/users/search", ddClient.initTokenHeader(), new HashMap<>(), body, DDR.class);
        System.out.println(ddr);
    }




}
