package com.yem.ia.intebilllogon.Utils;

import akka.actor.Stash;
import com.grapecity.documents.excel.O;
import com.yem.ia.intebilllogon.commom.CommonUtils;
import com.yem.ia.intebilllogon.commom.DyDataUtils;
import com.yem.wm.utils.StringUtils;
import com.yem.wm.utils.YEM;
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.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.exception.KDBizException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

import java.io.IOException;
import java.math.BigDecimal;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Map;

/**
 * @author zhouc
 * @date 2023/8/21 14:45
 * @className ObjectToJsonUtils
 * @description 单据对象转JSON工具类
 */
public class ObjectToJsonUtils {

    /**
     * 根据智能审批单据注册，依据单据ID、单据标识构建Json
     *
     * @param pkid 获取单据id
     * @param map  entityName :获取单据标识
     *             billtype:单据类型编码
     *             Stashtype: 仓库类型 枚举
     *             VMI库	V
     *             制造中心库	Z
     *             正常仓库	C
     *             yem_salesordertype 合同类型（下单审批必传）
     *             外贸整机合同	yem_es_salesorder_ZJ
     *             外贸配件合同	yem_es_salesorder_PJ
     *             内贸整机合同	yem_es_salesorder_nmzj
     *             内贸配件合同	yem_es_salesorder_nmpj
     * @return JSONObject
     */
    public static JSONObject ObjectToJson(Object pkid, Map<String, Object> map) {
        JSONObject Object = new JSONObject();
        String getpostcreator = getpostcreator();
//        if (getpostcreator == null || getpostcreator.length() == 0) {
//            throw new KDBizException("未获取到云之家对应id，请联系云之家管理员处理！");
//        }
        if (map.size() > 0) {
            //根据单据标识获取单据注册信息
            QFilter qFilter = new QFilter("yem_isdisable", QCP.equals, false);
            if (map.containsKey("entityName")) {
                qFilter.and(new QFilter("yem_formid.number", QCP.equals, map.get("entityName")));
                if (!map.get("entityName").equals("yem_es_contactbook")) {
                    if (map.containsKey("billtype")) {
                        Object billtype = map.get("billtype");
                        if (billtype != null) {
                            if (map.get("billtype").equals("yem_orderproreqbill_DB")) {
                                if (!map.containsKey("Stashtype")) {
                                    Object.put("errmessage", "传入的单据类型为【配件调拨计划】，仓库类型必传！！");
                                    return Object;
                                } else {
                                    qFilter.and(new QFilter("yem_billtype.fbasedataid.number", QCP.in, map.get("billtype")));
                                }
                            } else {
                                qFilter.and(new QFilter("yem_billtype.fbasedataid.number", QCP.in, map.get("billtype")));
                            }
                        }
                    }
                }
                if (map.containsKey("Stashtype")) {
                    qFilter.and(new QFilter("yem_isvmi", QCP.equals, map.get("Stashtype")));
                }
                if (map.containsKey("yem_salesordertype")) {
                    qFilter.and(new QFilter("yem_salesordertype", QCP.equals, map.get("yem_salesordertype")));
                }
                if (map.containsKey("yem_procbilltype")) {
                    qFilter.and(new QFilter("yem_procbilltype", QCP.equals, map.get("yem_procbilltype")));
                }
                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 && pkid != null && pkid != "") {
                        Object = ToJson(dataEntity, pkid, map.get("entityName").toString(), getpostcreator);
                    }
                } else {
                    Object.put("errmessage", "未读取启用的《智能审批单据注册》，请修改后重试！");
                }
            } else {
                Object.put("errmessage", "未读取到单据对象，请修改后重试！");
            }
        }
        return Object;
    }

    /**
     * 根据单据注册对象创建JSon实现方法
     *
     * @param dataEntity 单据注册对象
     * @param pkid       获取单据id
     * @param entityName 获取单据标识
     * @return JSONObject
     */
    public static JSONObject ToJson(DynamicObject dataEntity, Object pkid, String entityName, String creator) {
        JSONObject Object = new JSONObject();
        Object.put("formCodeId", dataEntity.getString("yem_yzjid"));
        if (creator == null || creator.length() == 0) {
            Object.put("creator", dataEntity.getString("yem_creator"));
        } else {
            Object.put("creator", creator);
        }
        JSONObject widgetValueObject = new JSONObject();//单据头对象
        JSONObject json = new JSONObject();//
        if (StringUtils.isNotEmpty(pkid.toString())) {
            //获取单据数据
            DynamicObject Bill = BusinessDataServiceHelper.loadSingle(pkid, entityName);
            if (Bill != null) {
                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_subisdelete = signentryentity.getBoolean("yem_subisdelete");//是否删除
                        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_erpfiledtype = signentryentity.getString("yem_erpfiledtype");//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_issubentry = signentryentity.getBoolean("yem_issubentry");//是否子分录
                        Boolean yem_isattachment = signentryentity.getBoolean("yem_isattachment");//是否附件
                        String yem_attachmentkey = signentryentity.getString("yem_attachmentkey");//附件标识
                        if (!yem_subisdelete) {
                            //单据头H  单据体D
                            if (yem_iaentitytype.equals("H")) {
                                if (StringUtils.isNotEmpty(yem_defaultvalue)) {//是否默认不为空
                                    if ("人员选择".equals(yem_iatype)) {
                                        widgetValueObject.put(yem_iaformid, new String[]{yem_defaultvalue});
                                    } else {
                                        widgetValueObject.put(yem_iaformid, yem_defaultvalue);
                                    }
                                }
                                if (StringUtils.isNotEmpty(yem_modledefaultvalue)) {//动态默认不为空
                                    widgetValueObject.put(yem_iaformid, DyDataUtils.getDyData(Bill, yem_modledefaultvalue, yem_identifierbasic));
                                }
                                if (StringUtils.isNotEmpty(yem_erpfiledformid)) {////ERP字段标识不为空
                                    Object value = CommonUtils.GetDynamicobjectValue(yem_erpfiledtype, Bill, yem_erpfiledformid, yem_identifierbasic, iaaccuracy, entityName, yem_iatype);
                                    widgetValueObject.put(yem_iaformid, value);
                                }
                                //是否附件
                                if (yem_isattachment) {
                                    JSONArray jsonArray = CommonUtils.GetAttachment(entityName, pkid, yem_attachmentkey);
                                    if (jsonArray != null && jsonArray.size() > 0) {
                                        widgetValueObject.put(yem_iaformid, jsonArray);
                                    }
                                }
                                Object.put("widgetValue", widgetValueObject);
                            } else {
                                //单据数据集合
                                JSONObject widgetValueEntry = new JSONObject();//单据头对象
                                JSONArray jsonArray = new JSONArray();
                                DynamicObjectCollection yem_subentryentity = signentryentity.getDynamicObjectCollection("yem_subentryentity");
                                //子单据体
                                if (yem_issubentry) {
                                    String yem_parentcontainer = signentryentity.getString("yem_parentcontainer");//父分录标识
                                    if (yem_parentcontainer != null && StringUtils.isNotEmpty(yem_parentcontainer)) {
                                        DynamicObjectCollection entity = Bill.getDynamicObjectCollection(yem_parentcontainer);//父单据体
                                        for (int t = 0; t < entity.size(); t++) {
                                            DynamicObject dynamicObject = entity.get(t);
                                            DynamicObjectCollection subEntry = entity.get(t).getDynamicObjectCollection(yem_erpfiledformid);//子单据体
                                            if (subEntry.size() > 0) {
                                                for (int K = 0; K < subEntry.size(); K++) {
                                                    DynamicObject subEntryDynamico = subEntry.get(K);
                                                    JSONObject entityObject = new JSONObject();
                                                    for (int j = 0; j < yem_subentryentity.size(); j++) {
                                                        DynamicObject subentryentity = yem_subentryentity.get(j);
                                                        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");//动态默认
                                                        String yem_erpentitytype1 = subentryentity.getString("yem_erpentitytype1");//实体类型
                                                        if (StringUtils.isNotEmpty(yem_defaultvalue1)) {//是否默认不为空
                                                            if ("人员选择".equals(yem_iatype1)) {
                                                                entityObject.put(yem_iaformid1, new String[]{yem_defaultvalue1});
                                                            } else {
                                                                entityObject.put(yem_iaformid1, yem_defaultvalue1);
                                                            }
                                                        }
                                                        if (StringUtils.isNotEmpty(yem_modledefaultvalue1)) {//动态默认不为空
                                                            entityObject.put(yem_iaformid1, DyDataUtils.getDyDataEntry(Bill, subEntryDynamico, yem_modledefaultvalue1, yem_identifierbasic1));
                                                        }
                                                        if (StringUtils.isNotEmpty(yem_erpfiledformid1)) {
                                                            if (yem_erpentitytype1.equals("H")) {//单据头
                                                                Object value = CommonUtils.GetDynamicobjectValue(yem_erpfiledtype1, Bill, yem_erpfiledformid1, yem_identifierbasic1, iaaccuracy1, entityName, yem_iatype1);
                                                                entityObject.put(yem_iaformid1, value);
                                                            }
                                                            if (yem_erpentitytype1.equals("D")) {
                                                                Object value = CommonUtils.GetDynamicobjectValue(yem_erpfiledtype1, entity.get(t), yem_erpfiledformid1, yem_identifierbasic1, iaaccuracy1, entityName, yem_iatype1);
                                                                entityObject.put(yem_iaformid1, value);
                                                            }
                                                            if (yem_erpentitytype1.equals("S")) {
                                                                Object value = CommonUtils.GetDynamicobjectValue(yem_erpfiledtype1, subEntryDynamico, yem_erpfiledformid1, yem_identifierbasic1, iaaccuracy1, entityName, yem_iatype1);
                                                                entityObject.put(yem_iaformid1, value);
                                                            }
                                                            if (StringUtils.isEmpty(yem_erpentitytype1) && StringUtils.isNotEmpty(yem_erpfiledformid1) && StringUtils.isNotNull(yem_erpfiledformid1)) {
                                                                yem_erpfiledformid1 = yem_erpfiledformid1;
                                                                String[] sourceItems = yem_erpfiledformid1.split("\\.");
                                                                if (sourceItems[0].equals(yem_erpfiledformid)) {//子分录
                                                                    Object value = CommonUtils.GetDynamicobjectValue(yem_erpfiledtype1, subEntryDynamico, sourceItems[1], yem_identifierbasic1, iaaccuracy1, entityName, yem_iatype1);
                                                                    entityObject.put(yem_iaformid1, value);
                                                                }
                                                                if (sourceItems[0].equals(yem_parentcontainer)) {//父分录
                                                                    Object value = CommonUtils.GetDynamicobjectValue(yem_erpfiledtype1, entity.get(t), sourceItems[1], yem_identifierbasic1, iaaccuracy1, entityName, yem_iatype1);
                                                                    entityObject.put(yem_iaformid1, value);
                                                                }

                                                            }
                                                        }
                                                    }
                                                    jsonArray.add(entityObject);
                                                }
                                            }else{
                                                JSONObject entityObject = new JSONObject();
                                                for (int j = 0; j < yem_subentryentity.size(); j++) {
                                                    DynamicObject subentryentity = yem_subentryentity.get(j);
                                                    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");//动态默认
                                                    String yem_erpentitytype1 = subentryentity.getString("yem_erpentitytype1");//实体类型
                                                    if (StringUtils.isNotEmpty(yem_defaultvalue1)) {//是否默认不为空
                                                        if ("人员选择".equals(yem_iatype1)) {
                                                            entityObject.put(yem_iaformid1, new String[]{yem_defaultvalue1});
                                                        } else {
                                                            entityObject.put(yem_iaformid1, yem_defaultvalue1);
                                                        }
                                                    }
                                                    if (StringUtils.isNotEmpty(yem_modledefaultvalue1)) {//动态默认不为空
                                                        entityObject.put(yem_iaformid1, DyDataUtils.getDyDataEntry(Bill, dynamicObject, yem_modledefaultvalue1, yem_identifierbasic1));
                                                    }
                                                    if (StringUtils.isNotEmpty(yem_erpfiledformid1)) {
                                                        if (yem_erpentitytype1.equals("H")) {//单据头
                                                            Object value = CommonUtils.GetDynamicobjectValue(yem_erpfiledtype1, Bill, yem_erpfiledformid1, yem_identifierbasic1, iaaccuracy1, entityName, yem_iatype1);
                                                            entityObject.put(yem_iaformid1, value);
                                                        }
                                                        if (yem_erpentitytype1.equals("D")) {
                                                            Object value = CommonUtils.GetDynamicobjectValue(yem_erpfiledtype1, entity.get(t), yem_erpfiledformid1, yem_identifierbasic1, iaaccuracy1, entityName, yem_iatype1);
                                                            entityObject.put(yem_iaformid1, value);
                                                        }
                                                        if (yem_erpentitytype1.equals("S")) {
//                                                            Object value = CommonUtils.GetDynamicobjectValue(yem_erpfiledtype1, subEntryDynamico, yem_erpfiledformid1, yem_identifierbasic1, iaaccuracy1, entityName, yem_iatype1);
//                                                            entityObject.put(yem_iaformid1, value);
                                                            continue;
                                                        }
                                                        if (StringUtils.isEmpty(yem_erpentitytype1) && StringUtils.isNotEmpty(yem_erpfiledformid1) && StringUtils.isNotNull(yem_erpfiledformid1)) {
                                                            yem_erpfiledformid1 = yem_erpfiledformid1;
                                                            String[] sourceItems = yem_erpfiledformid1.split("\\.");
                                                            if (sourceItems[0].equals(yem_erpfiledformid)) {//子分录
//                                                                Object value = CommonUtils.GetDynamicobjectValue(yem_erpfiledtype1, dynamicObject, sourceItems[1], yem_identifierbasic1, iaaccuracy1, entityName, yem_iatype1);
//                                                                entityObject.put(yem_iaformid1, value);
                                                                continue;
                                                            }
                                                            if (sourceItems[0].equals(yem_parentcontainer)) {//父分录
                                                                Object value = CommonUtils.GetDynamicobjectValue(yem_erpfiledtype1, entity.get(t), sourceItems[1], yem_identifierbasic1, iaaccuracy1, entityName, yem_iatype1);
                                                                entityObject.put(yem_iaformid1, value);
                                                            }

                                                        }
                                                    }
                                                }
                                                jsonArray.add(entityObject);
                                            }
                                        }
                                    }
                                } else { //单据提拼接
                                    if (StringUtils.isEmpty(yem_erpfiledformid)) {
                                        continue;
                                    }
                                    DynamicObjectCollection entity = Bill.getDynamicObjectCollection(yem_erpfiledformid);
                                    for (int K = 0; K < entity.size(); K++) {
                                        DynamicObject entityDynamico = entity.get(K);
                                        JSONObject entityObject = new JSONObject();
                                        for (int j = 0; j < yem_subentryentity.size(); j++) {
                                            DynamicObject subentryentity = yem_subentryentity.get(j);
                                            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_erpfiledtype1 = subentryentity.getString("yem_erpfiledtype1");//ERP字段类型
                                            String yem_identifierbasic1 = subentryentity.getString("yem_identifierbasic1");//ERP基础数据唯一标识
                                            String yem_defaultvalue1 = subentryentity.getString("yem_defaultvalue1");//默认值
                                            String yem_modledefaultvalue1 = subentryentity.getString("yem_modledefaultvalue1");//动态默认
                                            String yem_erpentitytype1 = subentryentity.getString("yem_erpentitytype1");//实体类型
//                                            entityObject.put("cosmicfentryid", entityDynamico.getLong("id"));
                                            if (StringUtils.isNotEmpty(yem_defaultvalue1)) {//是否默认不为空
                                                if ("人员选择".equals(yem_iatype1)) {
                                                    entityObject.put(yem_iaformid1, new String[]{yem_defaultvalue1});
                                                } else {
                                                    entityObject.put(yem_iaformid1, yem_defaultvalue1);
                                                }
                                            }
                                            if (StringUtils.isNotEmpty(yem_modledefaultvalue1)) {//动态默认不为空
                                                entityObject.put(yem_iaformid1, DyDataUtils.getDyDataEntry(Bill, entityDynamico, yem_modledefaultvalue1, yem_identifierbasic1));
                                            }
                                            if (StringUtils.isNotEmpty(yem_erpfiledformid1)) {////ERP字段标识不为空
                                                if (yem_erpentitytype1.equals("H")) {//单据头
                                                    Object value = CommonUtils.GetDynamicobjectValue(yem_erpfiledtype1, Bill, yem_erpfiledformid1, yem_identifierbasic1, iaaccuracy1, entityName, yem_iatype1);
                                                    entityObject.put(yem_iaformid1, value);
                                                }
                                                if (yem_erpentitytype1.equals("D")) {
                                                    Object value = CommonUtils.GetDynamicobjectValue(yem_erpfiledtype1, entityDynamico, yem_erpfiledformid1, yem_identifierbasic1, iaaccuracy1, entityName, yem_iatype1);
                                                    entityObject.put(yem_iaformid1, value);
                                                }
                                                if (StringUtils.isEmpty(yem_erpentitytype1)) {
                                                    entityObject.put(yem_iaformid1, entityDynamico.getString("id"));
                                                }
                                            }
                                        }
                                        jsonArray.add(entityObject);
                                    }
                                }
                                widgetValueEntry.put("widgetValue", jsonArray);
                                json.put(yem_iaformid, widgetValueEntry);
                                Object.put("details", json);//分录数据
                            }
                        }
                    }
                }
            }
        }
        return Object;
    }

    /**
     * 获取云之家用户id
     *
     * @return 返回云之家用户id
     */
    public static String getpostcreator() {
        String openId = null;
        //当前登录用户
        long currentUserId = YEM.getCurrentUserId();
        if (currentUserId > 0) {
            DynamicObject dataEntity = BusinessDataServiceHelper.loadSingle(currentUserId, "bos_user");
            if (dataEntity != null) {
                String phone = dataEntity.getString("phone");
                try {
                    openId = YunzhijiaUtils.getOpenId(phone);
                } catch (IOException ex) {
                    throw new KDBizException(ex.getMessage());
                } catch (NoSuchAlgorithmException ex) {
                    throw new KDBizException(ex.getMessage());
                } catch (KeyManagementException ex) {
                    throw new KDBizException(ex.getMessage());
                }
            }
        }
        return openId;
    }
}
