package com.yem.ia.intebilllogon.Utils;

import com.yem.ia.intebilllogon.commom.CommonUtils;
import com.yem.wm.utils.AttachmentUtil;
import com.yem.wm.utils.StringUtils;
import com.yem.wm.utils.YunzhijiaUtils;
//import json.JSONArray;
//import json.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDBizException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Iterator;
import java.util.Map;

/**
 * @author zhouc
 * @date 2023/8/22 10:11
 * @className BackfilljsonAssignUtils
 * @description 根据云之家返回json 读取单据注册是否回填进行循环赋值
 */
public class BackfilljsonAssignUtils {

    /**
     * 根据云之家返回Json赋值
     *
     * @param Json 云之家返回Json对象
     */
    public static void BackfilljsonAssign(String Json) {
        JSONObject jsonData = JSONObject.parseObject(Json);
//        Boolean success = jsonData.getBoolean("success");
//        if (success) {
//            JSONObject basicInfojson = JSONObject.parseObject(JSONObject.parseObject(jsonData.getString("data")).getString("basicInfo"));
        JSONObject basicInfojson = jsonData.getJSONObject("basicInfo");
        String formCodeId = basicInfojson.getString("formCodeId");//表单模板id
        String formInstId = basicInfojson.getString("formInstId");//表单实例id
        String yem_formidNumber = StringUtils.getEmpty();
        //根据表单模板id获取智能审批单据注册id
        QFilter qFilter = new QFilter("yem_yzjid", QCP.equals, formCodeId);
        qFilter.and(new QFilter("yem_isdisable", QCP.equals, false));
        DynamicObject yem_ia_intebilllogon = BusinessDataServiceHelper.loadSingle("yem_ia_intebilllogon", "id", qFilter.toArray());
        if (yem_ia_intebilllogon != null) {
            long intebilllogonID = yem_ia_intebilllogon.getLong("id");
            //查询单据注册数据
            DynamicObject dataEntity = BusinessDataServiceHelper.loadSingle(intebilllogonID, "yem_ia_intebilllogon");
            if (dataEntity != null) {
                DynamicObject yem_formid = dataEntity.getDynamicObject("yem_formid");
                if (yem_formid != null) {
                    yem_formidNumber = yem_formid.getString("number");
                }
            }
            //根据表单实例id获取单据id
            if (StringUtils.isNotEmpty(yem_formidNumber)) {
                QFilter qFilter1 = new QFilter("yem_forminstid", QCP.equals, formInstId);
//                    qFilter1.and(new QFilter("yem_isdisable", QCP.equals, false));
                DynamicObject querydata = BusinessDataServiceHelper.loadSingle(yem_formidNumber, "id", qFilter1.toArray());
                if (querydata != null) {
                    long formid = querydata.getLong("id");
                    if (formid > 0) {
                        DynamicObject BilldataEntity = BusinessDataServiceHelper.loadSingle(formid, yem_formidNumber);
                        if (BilldataEntity != null) {
                            Backfilljson(jsonData, dataEntity, BilldataEntity);
                        }
                    }
                }
            }
        }
//        }
    }

    /**
     * 根据获取到的对象进行循环赋值
     *
     * @param jsonData       云之家返回Json对象
     * @param dataEntity     单据注册对象
     * @param BilldataEntity 获取单据对象
     */
    public static void Backfilljson(JSONObject jsonData, DynamicObject dataEntity, DynamicObject BilldataEntity) {
        //获取单据id
        long fid = BilldataEntity.getLong("id");
        //单据注册单据对象
        DynamicObjectCollection yem_signentryentity = dataEntity.getDynamicObjectCollection("yem_signentryentity");
        if (yem_signentryentity.size() > 0) {
            for (int i = 0; i < yem_signentryentity.size(); i++) {
                DynamicObject signentryentity = yem_signentryentity.get(i);
                Boolean yem_isbackfill = signentryentity.getBoolean("yem_isbackfill");//是否回填
                if (yem_isbackfill) {
                    String yem_iaentitytype = signentryentity.getString("yem_iaentitytype");//审批实体类型
                    String yem_iaformid = signentryentity.getString("yem_iaformid");//审批字段标识
                    String yem_ianame = signentryentity.getString("yem_ianame");//审批字段名称
                    String yem_iatype = signentryentity.getString("yem_iatype");//审批字段类型
                    int iaaccuracy = signentryentity.getInt("yem_iaaccuracy");//字段精度
                    String yem_erpfiledformid = signentryentity.getString("yem_erpfiledformid");//ERP字段标识
                    String yem_erpfiledformname = signentryentity.getString("yem_erpfiledformname");//ERP字段名称
                    String yem_erpfiledtype = signentryentity.getString("yem_erpfiledtype");//ERP字段类型
                    String yem_filedtypename = signentryentity.getString("yem_filedtypename");//ERP基础资料标识
                    String yem_identifierbasic = signentryentity.getString("yem_identifierbasic");//ERP基础数据唯一标识
                    String yem_defaultvalue = signentryentity.getString("yem_defaultvalue");//默认值
                    String yem_modledefaultvalue = signentryentity.getString("yem_modledefaultvalue");//动态默认
                    Boolean yem_isattachment = signentryentity.getBoolean("yem_isattachment");//是否附件
                    String yem_attachmentkey = signentryentity.getString("yem_attachmentkey");//附件标识
                    if (yem_iaentitytype.equals("H")) {//单据头H  单据体D
                        if (yem_isattachment) {
                            Setattachment(jsonData, BilldataEntity, yem_attachmentkey, yem_iaformid);
                        } else {
                            //获取Json对象单据头数据
                            String value = GetJsonValue(yem_iaentitytype, jsonData, yem_iaformid, "", 0L);
                            //单据头字段直接赋值
                            if (yem_erpfiledformid.length() > 0) {
                                BilldataEntity.set(yem_erpfiledformid, value);
                            }
                        }
                    } else {
                        //单据注册子单据体
                        DynamicObjectCollection yem_subentryentity = signentryentity.getDynamicObjectCollection("yem_subentryentity");
                        Boolean yem_issubentry = signentryentity.getBoolean("yem_issubentry");//是否子分录
                        if (yem_issubentry) {
                            String yem_parentcontainer = signentryentity.getString("yem_parentcontainer");//父分录标识
                            //获取单据明细数据
                            DynamicObjectCollection entity = BilldataEntity.getDynamicObjectCollection(yem_parentcontainer);
                            for (int j = 0; j < yem_subentryentity.size(); j++) {
                                DynamicObject subentryentity = yem_subentryentity.get(j);
                                String yem_iaformid1 = subentryentity.getString("yem_iaformid1");//审批字段标识
                                Boolean yem_isbackfill1 = subentryentity.getBoolean("yem_isbackfill1");//是否回填
                                String yem_erpfiledformid1 = subentryentity.getString("yem_erpfiledformid1");//ERP字段标识
                                String yem_erpentitytype1 = subentryentity.getString("yem_erpentitytype1");//ERP实体类型
                                if (yem_isbackfill1) {

                                    for (int k = 0; k < entity.size(); k++) {
                                        DynamicObject entity_s = entity.get(k);
                                        DynamicObjectCollection Subentity = entity_s.getDynamicObjectCollection(yem_erpfiledformid);
                                        if (yem_erpentitytype1.equals("D")) {
                                            String value = GetJsonValue(yem_iaentitytype, jsonData, yem_iaformid1, yem_iaformid, entity_s.getLong("id"));
                                            if (yem_erpfiledformid1.length() > 0) {
                                                entity_s.set(yem_erpfiledformid1, value);
                                            }
                                        }
                                        if (yem_erpentitytype1.equals("S")) {//子单据体
                                            for (int e = 0; e < Subentity.size(); e++) {
                                                DynamicObject Subentity_s = Subentity.get(e);
                                                String value = GetJsonValue(yem_iaentitytype, jsonData, yem_iaformid1, yem_iaformid, Subentity_s.getLong("id"));
                                                if (yem_erpfiledformid1.length() > 0) {
                                                    Subentity_s.set(yem_erpfiledformid1, value);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        } else {
                            //获取单据明细数据
                            DynamicObjectCollection entity = BilldataEntity.getDynamicObjectCollection(yem_erpfiledformid);
                            for (int j = 0; j < yem_subentryentity.size(); j++) {
                                DynamicObject subentryentity = yem_subentryentity.get(j);
                                Boolean yem_isbackfill1 = subentryentity.getBoolean("yem_isbackfill1");//是否回填
                                if (yem_isbackfill1) {
                                    String yem_iaformid1 = subentryentity.getString("yem_iaformid1");//审批字段标识
                                    int iaaccuracy1 = subentryentity.getInt("yem_iaaccuracy1");//字段精度
                                    String yem_iatype1 = subentryentity.getString("yem_iatype1");//审批字段类型
                                    String yem_erpfiledformid1 = subentryentity.getString("yem_erpfiledformid1");//ERP字段标识
                                    String yem_erpfiledformname1 = subentryentity.getString("yem_erpfiledformname1");//ERP字段名称
                                    String yem_erpfiledtype1 = subentryentity.getString("yem_erpfiledtype1");//ERP字段类型
                                    String yem_filedtypename1 = subentryentity.getString("yem_filedtypename1");//ERP基础资料标识
                                    String yem_identifierbasic1 = subentryentity.getString("yem_identifierbasic1");//ERP基础数据唯一标识
                                    String yem_defaultvalue1 = subentryentity.getString("yem_defaultvalue1");//默认值
                                    String yem_modledefaultvalue1 = subentryentity.getString("yem_modledefaultvalue1");//动态默认
                                    for (int k = 0; k < entity.size(); k++) {
                                        DynamicObject entity_s = entity.get(k);
                                        String value = GetJsonValue(yem_iaentitytype, jsonData, yem_iaformid1, yem_iaformid, entity_s.getLong("id"));
                                        if (yem_erpfiledformid1.length() > 0) {
                                            entity_s.set(yem_erpfiledformid1, value);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        //赋值完毕调用保存
        OperationResult Operate = OperationServiceHelper.executeOperate("save",
                BilldataEntity.getDynamicObjectType().getName(), new DynamicObject[]{BilldataEntity},
                OperateOption.create());
        if (Operate.isSuccess()) {

        } else {
            String errMessage = Operate.getMessage();    // 错误摘要
            String detailMessage = "";
            // 演示提取保存详细错误
            for (IOperateInfo errInfo : Operate.getAllErrorOrValidateInfo()) {
                detailMessage += errInfo.getMessage() + "\r\n";
            }
//            throw new KDBizException("保存失败：" + detailMessage);
        }
    }

    /**
     * 获取Json对象中的Value
     *
     * @param Type      类型 单据头H  单据体D
     * @param jsonData  Json对象集合
     * @param key       获取jsonKey
     * @param EntityKey 获取json分录Key
     * @param entryid   单据分录id
     * @return
     */
    public static String GetJsonValue(String Type, JSONObject jsonData, String key, String EntityKey, Long entryid) {
        String Value = StringUtils.getEmpty();
        if (Type.equals("H")) {
//            JSONObject widgetMapjson = JSONObject.parseObject(JSONObject.parseObject(JSONObject.parseObject(jsonData.getString("data")).getString("formInfo")).getString("widgetMap"));
            JSONObject widgetMapjson = JSONObject.parseObject(JSONObject.parseObject(JSONObject.parseObject(jsonData.toString()).getString("formInfo")).getString("widgetMap"));
            if (widgetMapjson.containsKey(key)) {
                JSONObject keyJson = JSONObject.parseObject(widgetMapjson.getString(key));
                if (keyJson.containsKey("value")) {
                    Value = keyJson.getString("value");
                }
            }
        } else {
//            JSONObject detailMapjson = JSONObject.parseObject(JSONObject.parseObject(JSONObject.parseObject(jsonData.getString("data")).getString("formInfo")).getString("detailMap"));
            JSONObject detailMapjson = JSONObject.parseObject(JSONObject.parseObject(JSONObject.parseObject(jsonData.toString()).getString("formInfo")).getString("detailMap"));
            JSONObject EntityKeyJson = JSONObject.parseObject(detailMapjson.getString(EntityKey));
            if (EntityKeyJson != null) {
                if (EntityKeyJson.containsKey("widgetValue")) {
                    JSONArray entryData_s = EntityKeyJson.getJSONArray("widgetValue");
                    for (int i = 0; i < entryData_s.size(); i++) {
                        JSONObject entryData = entryData_s.getJSONObject(i);
                        if (entryData != null) {
                            //单据分录id与json分录对比 如一致则直接根据key获取
//                            if (entryid == entryData.getLong("id")) {
//                                Value = entryData.getString(key);
//                            }
                            for (Map.Entry<String, Object> stringObjectEntry : entryData.entrySet()) {
                                Long tempid = null;
                                try {
                                    tempid = Long.parseLong(entryData.getString(stringObjectEntry.getKey()));
                                } catch (Exception e) {
                                    continue;
                                }
                                if (entryid.equals(tempid)) {
                                    Value = entryData.getString(key);
                                }
                            }

                        }
                    }
                }
            }
        }
        return Value;
    }


    /**
     * 根据返回json给附件面板赋值
     *
     * @param jsonData          返回json
     * @param BilldataEntity    单据对象
     * @param yem_attachmentkey 附件面板key
     * @param yem_iaformid      json字段标识
     */
    public static void Setattachment(JSONObject jsonData, DynamicObject BilldataEntity, String yem_attachmentkey, String yem_iaformid) {
        String name = BilldataEntity.getDataEntityType().getName();
        String id = BilldataEntity.getString("id");
        JSONObject widgetMapjson = JSONObject.parseObject(JSONObject.parseObject(JSONObject.parseObject(jsonData.toString()).getString("formInfo")).getString("widgetMap"));
        if (widgetMapjson.containsKey(yem_iaformid)) {
            JSONObject keyJson = JSONObject.parseObject(widgetMapjson.getString(yem_iaformid));
            if (keyJson.containsKey("value")) {
                JSONArray value = keyJson.getJSONArray("value");
                for (int i = 0; i < value.size(); i++) {
                    JSONObject jsonObject = value.getJSONObject(i);
                    String fileName = jsonObject.getString("fileName");
                    String fileId = jsonObject.getString("fileId");
                    QFilter qFilter = new QFilter("yem_yzjid", QCP.equals, fileId);
                    DynamicObject yem_attyunzhijia = BusinessDataServiceHelper.loadSingle("yem_attyunzhijia", "id", qFilter.toArray());
                    if (yem_attyunzhijia == null) {
                        //获取云之家token
                        String url = YunzhijiaUtils.yzjurl + "/cmmpapi/cmmp/fileToken.do?tokenId=D4EB05B9FE9C41D0868D33EC92AAEDB4";
                        String Token = "";
                        try {
                            Token = YunzhijiaUtils.doPost(url, "");
                        } catch (Exception ex) {
                            throw new KDBizException(ex.toString());
                        }
                        JSONObject json = JSONObject.parseObject(Token);
                        System.err.println(json);
                        Boolean success = json.getBoolean("success");
                        if (success) {
                            JSONObject data = json.getJSONObject("data");
                            String accessToken = data.getString("accessToken");
                            byte[] downloadfile = YunzhijiaUtils.downloadfile(fileId, accessToken);
                            if (downloadfile.length > 0) {
                                InputStream input = new ByteArrayInputStream(downloadfile);
                                DynamicObject dynamicObject = AttachmentUtil.uploadAttachment(
                                        "yem_es", name, id, yem_attachmentkey, fileName, input);
                            }
                        }
                    }
                }
            }
        }
    }
}
