package com.malk.heshu;

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.service.aliwork.YDClient;
import com.malk.utils.PublicUtil;
import com.malk.utils.UtilMap;
import com.malk.heshu.config.KDWebApiConf;
import com.malk.heshu.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 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 saveCust() throws Exception {
        JSONObject params=new JSONObject();
        params.put("fid","f27295d0-7eec-4210-aca0-77d83fc1331e");
        params.put("key","textField_mnhav84y");
        try {
            Map formData= (Map) ydClient.queryData(YDParam.builder().formInstId(params.getString("fid")).build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
            if(formData==null){
                return ;
            }
            formData.put("textField_mma6vp851",formData.get("textField_mma6vp85"));
            CustomerInfo customerInfo = BeanUtil.toBean(formData, CustomerInfo.class);
            List<Map> list=UtilMap.getList(formData,"tableField_mma72l0q");
            List<CustomerInfo.CustBank> bkList=new ArrayList<>();
            for(Map map:list){
                CustomerInfo.CustBank  fBankInfo = BeanUtil.toBean(map, CustomerInfo.CustBank.class);
                bkList.add(fBankInfo);
            }
            customerInfo.setFT_BD_CUSTBANK(bkList);
            List<Map> list2=UtilMap.getList(formData,"tableField_mma72kx1");
            List<ContactInfo> lxrList=new ArrayList<>();
            for(Map map:list2){
                ContactInfo contactInfo=new ContactInfo();
                contactInfo.setFName(UtilMap.getString(map,"textField_mma72kx2"));
                contactInfo.setFMobile(UtilMap.getString(map,"textField_mma72kx3"));
                contactInfo.setFCompanyType("BD_Customer");
                contactInfo.setFBizLocation(UtilMap.getString(map,"textField_mogukmdi"));
                contactInfo.setFBizAddress(UtilMap.getString(map,"textField_mogukmdi"));
                lxrList.add(contactInfo);
            }
            customerInfo.setFSALDEPTID(new FNumber(UtilMap.getString(formData,"textField_mogukmdd")));// 业务部门
            String custTypeValue=UtilMap.getString(formData,"radioField_mma72kxi");
            String custType;
            if(custTypeValue.equals("贸易商")){
                custType="02";
            }else if(custTypeValue.equals("工厂")){
                custType="01";
            }else {
                custType="05";
            }
            customerInfo.setFGroup(new FNumber(custType));
            String operator=UtilMap.getString(formData,"radioField_mma72l0t");// 操作类型 客商准入  客商更新
//            if(operator.equals("客商更新")){
//                String fId=UtilMap.getString(formData,"textField_moi1ejl1");
//                if(!PublicUtil.isNull(fId)){
//                    // 反审核
//                    unAudit("BD_Customer",fId);
//                    customerInfo.setFCUSTID(Integer.parseInt(fId));
//                }
//            }
//            McR mcr=saveToAudit("BD_Customer",customerInfo,params.getString("fid"),params.getString("key"),"selectField_mogukmd8","textareaField_mogukmda","textField_moi1ejl1",lxrList);
            System.out.println(JSONObject.toJSONString(customerInfo));
        }catch (Exception e){
        }
    }

    @Test
    public void saveSupplier() throws Exception {
        Map formData= (Map) ydClient.queryData(YDParam.builder().formInstId("a4fba63b-586c-43ee-9d34-daaeee2b19f1").build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
        System.out.println(formData);
        SupplierEntity supplierEntity = BeanUtil.toBean(formData, SupplierEntity.class);
        SupplierEntity.FBaseInfo fBaseInfo = BeanUtil.toBean(formData, SupplierEntity.FBaseInfo.class);
        List<Map> list=UtilMap.getList(formData,"tableField_mma72l0q");
        List<SupplierEntity.FBankInfo> bkList=new ArrayList<>();
        for(Map map:list){
            SupplierEntity.FBankInfo  fBankInfo = BeanUtil.toBean(map, SupplierEntity.FBankInfo.class);
            bkList.add(fBankInfo);
        }
        supplierEntity.setFBaseInfo(fBaseInfo);
        supplierEntity.setFBankInfo(bkList);
        List<Map> list2=UtilMap.getList(formData,"tableField_mma72kx1");
        List<SupplierEntity.FSupplierContact> lxrList=new ArrayList<>();
        for(Map map:list2){
            SupplierEntity.FSupplierContact  lxrInfo = BeanUtil.toBean(map, SupplierEntity.FSupplierContact.class);
            lxrList.add(lxrInfo);
        }
        supplierEntity.setFSupplierContact(lxrList);
        System.out.println(supplierEntity);
//        System.out.println(saveToAudit("BD_Supplier",supplierEntity));
    }

    private McR saveToAudit(String formid, Object object,String fid,String codeKey,String statusKey,String msgKey,String idKey,List<ContactInfo> lxrList) 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);
        JSONObject reObj = JSONObject.parseObject(result,JSONObject.class);
        if (sRet.isSuccessfully()) {
            if(!PublicUtil.isNull(codeKey)){
                // 回写信息
                Map updateMap=UtilMap.map(codeKey,reObj.getJSONObject("Result").getString("Number"));
                updateMap.put(statusKey,"成功");
                updateMap.put(idKey,reObj.getJSONObject("Result").getString("Id"));// ID 内码
                ydClient.operateData(YDParam.builder().formInstId(fid).updateFormDataJson(
                        JSONObject.toJSONString(updateMap)
                ).build(), YDConf.FORM_OPERATION.update);
            }
            if(lxrList!=null){
                for (ContactInfo contactInfo : lxrList) {
                    contactInfo.setFCompany(new FNumber(reObj.getJSONObject("Result").getString("Number")));
                    String data=new Gson().toJson(contactInfo);
                    String id=saveToAudit("BD_CommonContact",new Gson().fromJson(data,Object.class));
                }
            }
            JsonObject jsonData = new JsonObject();
            jsonData.addProperty("Ids", sRet.getResult().getId());
            String result2=client.submit(formid, jsonData.toString());
            resultObj.put("submit",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());
                resultObj.put("audit",result3);
                RepoRet repoRet3 = gson.fromJson(result3, RepoRet.class);
                if (repoRet3.getResult().getResponseStatus().isIsSuccess()) {
                    log.info("审批通过，新增完成");
                    return McR.success(resultObj);
//                    Map map=UtilMap.map("PkIds, TOrgIds",sRet.getResult().getId(),"1,105818,105822,127834,127835,127838,127843,127846,127847,127848,127850,127862,1370321,1325841,1327202,1646858");
//                    String result4=client.allocate("formid",JSONObject.toJSONString(map));
//                    resultObj.put("allocate",result4);
//                    RepoRet repoRet4 = gson.fromJson(result4, RepoRet.class);
//                    if (repoRet4.getResult().getResponseStatus().isIsSuccess()) {
//                        log.info("分配完成");
//                        return McR.success(resultObj);
//                    }
                }
            }
        }else {
            log.info("保存失败：{}",result);
            Map updateMap=UtilMap.map(statusKey,"失败");
            updateMap.put(msgKey,result);
            ydClient.operateData(YDParam.builder().formInstId(fid).updateFormDataJson(
                    JSONObject.toJSONString(updateMap)
            ).build(), YDConf.FORM_OPERATION.update);
        }
        return McR.error("203",JSONObject.toJSONString(resultObj));
    }

    private void unAudit(String formid,String fNumber) throws Exception {
        K3CloudApi client = new K3CloudApi(initIden());
        Gson gson = new Gson();
        JsonObject jsonData = new JsonObject();
        jsonData.addProperty("Ids", fNumber);
        String result=client.unAudit(formid, jsonData.toString());
        RepoRet sRet2 = gson.fromJson(result, RepoRet.class);
        if (!sRet2.isSuccessfully()) {
            log.info("反审核失败:{}",result);
        }
    }

    @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",4,"","","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));
            System.out.println(result);
//            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 update(){
//        unAudit("BD_Customer","");
    }

    @Test
    public void queryOrder2(){
        ContactInfo contactInfo=new ContactInfo();
        contactInfo.setFName("张三");
        contactInfo.setFMobile("17700001111");
        contactInfo.setFCompanyType("BD_Customer");
        contactInfo.setFCompany(new FNumber("CUST5127"));
        contactInfo.setFBizLocation("测试地址");
        contactInfo.setFBizAddress("测试地址");
        try {
            String data=new Gson().toJson(contactInfo);
            System.out.println(data);
            JSONObject jsonObject=JSONObject.parseObject(data);
            System.out.println(jsonObject);
            String id=saveToAudit("BD_CommonContact",new Gson().fromJson(data,Object.class));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private String saveToAudit(String formid, Object object) throws Exception {
        K3CloudApi client = new K3CloudApi(initIden());
        String result=client.save(formid,JSONObject.toJSONString(UtilMap.map("Model",object)));
        System.out.println(result);
        Gson gson = new Gson();
        RepoRet sRet = gson.fromJson(result, RepoRet.class);
        JSONObject reObj = JSONObject.parseObject(result,JSONObject.class);
        if (sRet.isSuccessfully()) {
            return reObj.getJSONObject("Result").getString("Id");
        }else {
            return "";
        }
    }





}
