package com.malk.heshu.controller;

import cn.hutool.core.bean.BeanUtil;
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.heshu.entity.*;
import com.malk.server.aliwork.YDConf;
import com.malk.server.aliwork.YDParam;
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

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

import static org.junit.Assert.fail;

@RestController
@Slf4j
public class HeShuController {

    @Autowired
    private KDWebApiConf kdWebApiConf;
    @Autowired
    private YDClient ydClient;

    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;
    }
    @GetMapping("/test")
    public McR test(){
        return McR.success("111");
    }

    @PostMapping("/saveSupplier")
    public McR saveSupplier(@RequestBody JSONObject params){
        log.info("saveSupplier:{}",params);
        if(PublicUtil.isNull(params,"fid")){
            return McR.error("201","缺少参数!");
        }
        try {
            Thread.sleep(500);// 休眠5s避免同时更新一条数据
            Map formData= (Map) ydClient.queryData(YDParam.builder().formInstId(params.getString("fid")).build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
            if(formData==null){
                return McR.error("201","未查询到数据!");
            }
            List<String> types=UtilMap.getList(formData,"checkboxField_mma72l0x");
            String gysType;
            if(types.contains("供应商")){
                gysType="01";
            }else {
                gysType="03";
            }
            SupplierEntity supplierEntity = BeanUtil.toBean(formData, SupplierEntity.class);
            SupplierEntity.FBaseInfo fBaseInfo = BeanUtil.toBean(formData, SupplierEntity.FBaseInfo.class);
            SupplierEntity.FFinanceInfo fFinanceInfo = BeanUtil.toBean(formData, SupplierEntity.FFinanceInfo.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);
            }
            fBaseInfo.setFDeptId(new IdObject(UtilMap.getString(formData,"textField_mogukmdd")));// 业务部门
            supplierEntity.setFBaseInfo(fBaseInfo);
            supplierEntity.setFFinanceInfo(fFinanceInfo);
            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);
            supplierEntity.setFGroup(new IdObject(gysType));
            supplierEntity.setF_UNW_yida("https://garktl.aliwork.com/APP_QM42OEGLMNNGBLIJELJI/processDetail?formUuid=FORM-9C0EC03227CC49738447A27B4563779F0WLW&procInsId="+params.getString("fid"));
            String operator=UtilMap.getString(formData,"radioField_mma72l0t");// 操作类型 客商准入  客商更新
            if(operator.equals("客商更新")){
                String fId=UtilMap.getString(formData,"textField_moi1ejl2");
                if(!PublicUtil.isNull(fId)){
                    // 反审核
                    unAudit("BD_Supplier",fId);
                    supplierEntity.setFSupplierId(Integer.parseInt(fId));
                }
            }
            return  saveToAudit("BD_Supplier",supplierEntity,params.getString("fid"),params.getString("key"),"selectField_mogukmd9","textareaField_mogukmdb","textField_moi1ejl2",null);
        }catch (Exception e){
            return McR.error("201",e.getMessage());
        }
    }

    @PostMapping("/saveCust")
    public McR saveCust(@RequestBody JSONObject params){
        log.info("saveCust:{}",params);
        if(PublicUtil.isNull(params,"fid")){
            return McR.error("201","缺少参数!");
        }
        try {
            Map formData= (Map) ydClient.queryData(YDParam.builder().formInstId(params.getString("fid")).build(), YDConf.FORM_QUERY.retrieve_id).getFormData();
            if(formData==null){
                return McR.error("201","未查询到数据!");
            }
            formData.put("textField_mma6vp851",formData.get("textField_mma6vp85"));
            formData.put("textField_mma6vp7p1",formData.get("textField_mma6vp7p"));
            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));
                }
            }
            return  saveToAudit("BD_Customer",customerInfo,params.getString("fid"),params.getString("key"),"selectField_mogukmd8","textareaField_mogukmda","textField_moi1ejl1",lxrList);
        }catch (Exception e){
            return McR.error("201",e.getMessage());
        }
    }


    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 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 "";
        }
    }
    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);
        }
    }
}
