package yem.wmc.ydn.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.coderule.api.CodeRuleInfo;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import yem.base.common.utils.BigDecimalUtils;
import yem.base.common.utils.StringUtils;
import yem.base.common.utils.YEM;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


/**
 * @author 金亮
 * @date 2023/12/26 11:37
 * @relevantfile
 * @description jsonToData-将josn数据根据单据注册表新增到数据库中，dataToJson-将动态对象转化为指定的json格式
 * 仅可对单据类型的表单使用
 * @versions 1.0
 */
public class JsonToDataUtils {
    static final String NewRegisterEntityName = "yem_ydn_billogon"; //单据注册 表名

    public static DynamicObject jsonToData(String entityName, JSONObject realJson, JSONObject elseJson) {
        boolean isExist = false; // 数据库是否存在这条数据

        // 判断：数据应该更新还是新增
        DynamicObject bill = null;
//        DynamicObject dataBase = BusinessDataServiceHelper.loadSingle(entityName, "id", new QFilter[]{new QFilter("billno", QFilter.equals)});
//        if (dataBase != null) {
//            bill = BusinessDataServiceHelper.loadSingle(dataBase.getPkValue(), entityName);
//            isExist = true;
//        } else {
        bill = BusinessDataServiceHelper.newDynamicObject(entityName);
//        }
        QFilter qFilter1 = new QFilter("yem_formid.number", QCP.equals, entityName); // 单据标识
        DynamicObject registerObject = BusinessDataServiceHelper.loadSingle(NewRegisterEntityName, "id,billno,billstatus", new QFilter[]{qFilter1});
        if (registerObject == null) {
            return null;
        }
        registerObject = BusinessDataServiceHelper.loadSingle(registerObject.getPkValue(), NewRegisterEntityName);
        //实体容器
        DynamicObjectCollection yem_entitycontainer_s = registerObject.getDynamicObjectCollection("yem_entitycontainer");
        if (null == yem_entitycontainer_s || yem_entitycontainer_s.size() == 0) {
            return null;
        }
        // 遍历实体容器
        for (int i = 0; i < yem_entitycontainer_s.size(); i++) {
            DynamicObject yem_entitycontainer = yem_entitycontainer_s.get(i);
            String yem_entitytype = yem_entitycontainer.getString("yem_entitytype");//实体类型
            String yem_entityformid = yem_entitycontainer.getString("yem_entityformid");//容器标识
            String yem_parentcontainer = yem_entitycontainer.getString("yem_parentcontainer");//父级容器
            String yem_jsonformid = yem_entitycontainer.getString("yem_jsonformid");//json标识
            String yem_entryformid = yem_entitycontainer.getString("yem_entryformid");//分录标识
            DynamicObjectCollection yem_entityfieldcol_s = yem_entitycontainer.getDynamicObjectCollection("yem_entityfieldcol");//实体容器对应的整个实体字段集合
            if (null != yem_entityfieldcol_s && yem_entityfieldcol_s.size() > 0) {
                if ("A".equals(yem_entitytype)) { //单据头
                    traversalAssignment(yem_entityfieldcol_s, realJson, bill);
                } else if ("B".equals(yem_entitytype)) { //单据体
                    DynamicObjectCollection entryCollector = bill.getDynamicObjectCollection(yem_entityformid);
                    if (!isExist) {
                        JSONArray detailList = realJson.getJSONArray(yem_jsonformid);
                        if (detailList != null) {
                            for (int k = 0; k < detailList.size(); k++) {
                                JSONObject entryData = detailList.getJSONObject(k);
                                DynamicObject entry = entryCollector.addNew(); //新增一行分录
                                traversalAssignment(yem_entityfieldcol_s, entryData, entry);
                            }
                        }
                    } else if (isExist) { //更新操作
                        JSONArray detailList = realJson.getJSONArray(yem_jsonformid);
                        if (detailList != null) {
                            for (int k = 0; k < detailList.size(); k++) {
                                JSONObject entryData = detailList.getJSONObject(k);
                                DynamicObject dynamicObject = entryCollector.get(k);
                                traversalAssignment(yem_entityfieldcol_s, entryData, dynamicObject);
                            }
                        }
                    }
                } else if ("C".equals(yem_entitytype)) { //子单据体
                    // 获取父容器标识
                    if (StringUtils.isEmpty(yem_parentcontainer)) {
                        return null;
                    }
                    String fatherJsonBS = null;
                    for (DynamicObject yemEntitycontainer : yem_entitycontainer_s) { //单据注册表
                        String yemEntityformid = yemEntitycontainer.getString("yem_entityformid");//容器标识
                        if (yemEntityformid.equals(yem_parentcontainer)) {
                            fatherJsonBS = yemEntitycontainer.getString("yem_jsonformid");//json标识（父级json标识）
                        }
                    }
                    if (fatherJsonBS == null) {
                        return null;
                    }
                    DynamicObjectCollection superiorContainer = bill.getDynamicObjectCollection(yem_parentcontainer);//父级分录（已存入数据）
                    for (int index = 0; index < superiorContainer.size(); index++) {
                        DynamicObject rowDynamic = superiorContainer.get(index);
                        DynamicObjectCollection subordinate = rowDynamic.getDynamicObjectCollection(yem_entityformid);//子容器标识
                        if (!isExist) { //数据库里没有这个数据的时候,插入操作
                            JSONArray detailList = realJson.getJSONArray(fatherJsonBS);
                            if (detailList != null && detailList.size() > 0) {
                                JSONObject jsonObject = detailList.getJSONObject(index);
                                JSONArray jsonArray = jsonObject.getJSONArray(yem_jsonformid);
                                for (Object object : jsonArray) {
                                    JSONObject sonRowJsonObj = (JSONObject) object;
                                    DynamicObject entry = subordinate.addNew();
                                    // 遍历实体字段集合
                                    traversalAssignment(yem_entityfieldcol_s, sonRowJsonObj, entry);
                                }
                            }
                        } else if (isExist) { //更新
                            subordinate.clear();
                            JSONArray detailList = realJson.getJSONArray(fatherJsonBS);
                            if (detailList != null && detailList.size() > 0) {
                                JSONObject jsonObject = detailList.getJSONObject(index);
                                JSONArray jsonArray = jsonObject.getJSONArray(yem_jsonformid);//子jssonA 数据
                                for (Object object : jsonArray) {
                                    JSONObject sonRowJsonObj = (JSONObject) object;
                                    DynamicObject entry = subordinate.addNew();
                                    traversalAssignment(yem_entityfieldcol_s, sonRowJsonObj, entry);
                                }
                            }
                        }
                    }
                }
            }
        }
        // 特殊单据赋值
        if (entityName.equals("yem_ydn_shipdocking")) {//船舶历史挂港
            String mmsi = elseJson.getString("mmsi");
            String begin = elseJson.getString("begin");
            String end = elseJson.getString("end");
            bill.set("yem_mmsi", mmsi);
            bill.set("yem_begin", begin);
            bill.set("yem_end", end);
        }
        // 保存
        OperationResult operationResult = OperationServiceHelper.executeOperate("save", entityName, new DynamicObject[]{bill},
                OperateOption.create());
        boolean success = operationResult.isSuccess();
        if (!success) {
            return null;
        }
        return bill;
    }

    /**
     * 循环实体字段分录赋值处理方式
     *
     * @param yem_entityfieldcol_s 实体字段分录
     * @param realJson             josn对象
     * @param bill                 要设置的对象
     */
    public static void traversalAssignment(DynamicObjectCollection yem_entityfieldcol_s, JSONObject realJson, DynamicObject bill) {
        for (int j = 0; j < yem_entityfieldcol_s.size(); j++) {
            DynamicObject yem_entityfieldcol = yem_entityfieldcol_s.get(j);
            //ERP字段标识
            String yem_erpfiledformid = yem_entityfieldcol.getString("yem_erpfiledformid");
            // 字段类型
            String yem_filedtype = yem_entityfieldcol.getString("yem_filedtype");
            // json字段标识
            String yem_jsonfieldid = yem_entityfieldcol.getString("yem_jsonfieldid");
            //默认值
            String yem_defaultvalue = yem_entityfieldcol.getString("yem_defaultvalue");
            //定义基础数据唯一标识
            String yem_identifierbasic = yem_entityfieldcol.getString("yem_identifierbasic");
            // 字段类型名称-基础资料的的表名
            String yem_filedtypename = yem_entityfieldcol.getString("yem_filedtypename");
            String val = "";
            //  优先判断是否有默认值
            if (StringUtils.isNotEmpty(yem_defaultvalue)) {
                val = yem_defaultvalue;
            } else {
                if (realJson.containsKey(yem_jsonfieldid)) {
                    val = realJson.getString(yem_jsonfieldid);
                }
            }
            if ("basedata".equals(yem_filedtype)) {
                bill.set(yem_erpfiledformid, getObjDynamicObject(yem_filedtypename, yem_identifierbasic, val));
            } else if ("datetime".equals(yem_filedtype) || "date".equals(yem_filedtype)) {//字段类型为时间的
                if (yem_erpfiledformid.equals("auditdate")) { //审核时间
                    bill.set(yem_erpfiledformid, new Date());
                }
                if (StringUtils.isNotEmpty(val) && val.indexOf("-") != -1) {
                    bill.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd"));
                } else if (StringUtils.isNotEmpty(val) && val.indexOf("-") == -1 && !val.contains("AM") && !val.contains("PM")) {
                    bill.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyyMMdd"));
                } else if (StringUtils.isNotEmpty(val) && CheckFormat(val)) {
                    bill.set(yem_erpfiledformid, DateUtils.formatDate(val, "yyyy-MM-dd HH:mm:ss"));
                } else if (StringUtils.isNotEmpty(val) && val.indexOf(",") != -1 && (val.contains("AM") || val.contains("PM"))) {
                    bill.set(yem_erpfiledformid, DateUtils.formatDateLocale(val, "MMM dd, yyyy hh:mm:ss"));
                }
            } else if ("number".equals(yem_filedtype)) { //字段类型为数字类型的
                if (StringUtils.isNotEmpty(val)) {
                    bill.set(yem_erpfiledformid, BigDecimalUtils.toBigDecimal(val));
                }
            } else if ("org".equals(yem_filedtype)) { //组织-默认当前登录人组织
                bill.set(yem_erpfiledformid, YEM.getCurrentOrgId());
            } else if ("user".equals(yem_filedtype)) { //人员
                if ("auditor".equals(yem_erpfiledformid) || "creator".equals(yem_erpfiledformid) || "modifier".equals(yem_erpfiledformid)) {
                    bill.set(yem_erpfiledformid, YEM.getCurrentUserId());
                }
            } else { //否则就是文本类型的，直接使用获取到的json
                if (StringUtils.isNotEmpty(val)) {
                    if (val.contains("{}")) {
                        bill.set(yem_erpfiledformid, null);
                    } else {
                        bill.set(yem_erpfiledformid, val);
                    }
                }
            }
        }
    }


    /**
     * 基础资料数据处理工具方式
     */
    public static DynamicObject getObjDynamicObject(String yem_filedtypename, String yem_identifierbasic, String filterVal) {
        DynamicObject obj = null;
        if (StringUtils.isNotEmpty(yem_filedtypename) && StringUtils.isNotEmpty(filterVal)) {
            QFilter filter = new QFilter(yem_identifierbasic, QCP.equals, filterVal);
            obj = BusinessDataServiceHelper.loadSingle(yem_filedtypename, "id,name,number", new QFilter[]{filter});
        }
        return obj;
    }


    /**
     * 时间处理工具方式
     *
     * @param str
     * @return
     */
    public static boolean CheckFormat(String str) {
        boolean falg = false;
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = formatter.parse(str);
            falg = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return falg;
    }
}
