package com.yem.ia.intebilllogon.commom;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.ensign.common.StringUtils;
import com.yem.wm.utils.YunzhijiaUtils;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.entity.MulBasedataDynamicObjectCollection;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.ValueMapItem;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.property.ComboProp;
import kd.bos.exception.KDBizException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.MetadataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhouc
 * @date 2023/8/17 17:46
 * @className CommonUtils
 * @description 智能审批单据注册帮助类
 */
public class CommonUtils {
    /**
     * 根据编码/名称查询基础资料
     *
     * @param yem_filedtypename   基础资料类型
     * @param yem_identifierbasic 查询条件
     * @param filterVal           查询Value
     * @return obj
     */
    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 Object          基础资料对象
     * @param identifierbasic 查询属性Key
     * @return 获取属性值
     */
    public static String GetObjDynamicObjectStats(DynamicObject Object, String identifierbasic) {
        String Stats = "";
        if (Object != null) {
            Stats = Object.getString(identifierbasic);
        }
        return Stats;
    }

    /**
     * 根据单据ERP类型进行JSON拼接
     *
     * @param entityDynamico 数据获取对象
     * @param subentryentity 单据注册单据体
     * @param Bill           单据对象  用于默认方法
     * @param Bill           单据对象  用于默认方法
     * @return
     */
    public static JSONObject SpliceJson(DynamicObject entityDynamico, DynamicObject subentryentity, DynamicObject Bill) {
        JSONObject entityObject = new JSONObject();
        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");//动态默认
        if (com.yem.wm.utils.StringUtils.isNotEmpty(yem_defaultvalue1)) {//是否默认不为空
            if ("人员选择".equals(yem_iatype1)) {
                entityObject.put(yem_iaformid1, new String[]{yem_defaultvalue1});
            } else {
                entityObject.put(yem_iaformid1, yem_defaultvalue1);
            }
        }
        if (com.yem.wm.utils.StringUtils.isNotEmpty(yem_modledefaultvalue1)) {//动态默认不为空
            entityObject.put(yem_iaformid1, DyDataUtils.getDyData(Bill, yem_modledefaultvalue1, yem_identifierbasic1));
        }
        if (com.yem.wm.utils.StringUtils.isNotEmpty(yem_erpfiledformid1)) {////ERP字段标识不为空
            entityObject.put("fentryid", entityDynamico.getLong("id"));
            //创建人修改人审核人已基础资料处理
            if ("basedata".equals(yem_erpfiledtype1) || "auditor".equals(yem_erpfiledtype1)
                    || "modifier".equals(yem_erpfiledtype1) || "creator".equals(yem_erpfiledtype1)
                    || "user".equals(yem_erpfiledtype1)) {
                DynamicObject DynamicObject = entityDynamico.getDynamicObject(yem_erpfiledformid1);
                if (DynamicObject != null) {
                    entityObject.put(yem_iaformid1, CommonUtils.GetObjDynamicObjectStats(DynamicObject, yem_identifierbasic1));
                }
            } else if ("datetime".equals(yem_erpfiledtype1) || "date".equals(yem_erpfiledtype1)) {
                Date DateObject = entityDynamico.getDate(yem_erpfiledformid1);
                if (com.yem.wm.utils.StringUtils.isNotEmpty(yem_identifierbasic1)) {
//                                                        entityObject.put(yem_iaformid1, new SimpleDateFormat(yem_identifierbasic1).format(DateObject));
                    entityObject.put(yem_iaformid1, DateObject.getTime());
                }
            } else if ("number".equals(yem_erpfiledtype1)) {
                if (iaaccuracy1 > 0) {
                    BigDecimal value = entityDynamico.getBigDecimal(yem_erpfiledformid1).setScale(iaaccuracy1, BigDecimal.ROUND_HALF_UP);
                    entityObject.put(yem_iaformid1, value);
                } else {
                    entityObject.put(yem_iaformid1, entityDynamico.getBigDecimal(yem_erpfiledformid1));
                }
            } else {
                entityObject.put(yem_iaformid1, entityDynamico.getString(yem_erpfiledformid1));
            }
        }
        return entityObject;
    }

    /**
     * 根据配置获取值
     *
     * @param yem_erpfiledtype1    字段类型
     * @param entityDynamico       对象集合
     * @param yem_erpfiledformid1  ERP字段标识
     * @param yem_identifierbasic1 定义唯一标识
     * @param iaaccuracy1          字段精度
     * @param entityName           单据对象标识
     * @param yem_iatype           审批字段类型
     * @return 返回obj value
     */
    public static Object GetDynamicobjectValue(String yem_erpfiledtype1, DynamicObject entityDynamico, String yem_erpfiledformid1,
                                               String yem_identifierbasic1, int iaaccuracy1, String entityName, String yem_iatype) {
        Object obj = null;
        if (yem_erpfiledformid1.length() > 0) {
            //创建人修改人审核人已基础资料处理
            if ("basedata".equals(yem_erpfiledtype1) || "auditor".equals(yem_erpfiledtype1)
                    || "modifier".equals(yem_erpfiledtype1) || "creator".equals(yem_erpfiledtype1)
                    || "user".equals(yem_erpfiledtype1) || "org".equals(yem_erpfiledtype1)) {
                if (entityDynamico.get(yem_erpfiledformid1) instanceof MulBasedataDynamicObjectCollection) {
                    DynamicObjectCollection dynamicObjectCollection = entityDynamico.getDynamicObjectCollection(yem_erpfiledformid1);
                    for (DynamicObject dynamicObject : dynamicObjectCollection) {
                        if (obj == null) {
                            if (!"name".equals(yem_identifierbasic1)) {
                                obj = dynamicObject.get("fbasedataid." + yem_identifierbasic1);
                            } else {
                                obj = dynamicObject.get("fbasedataid.name.zh_CN");
                            }
                        } else {
                            if (!"name".equals(yem_identifierbasic1)) {
                                obj = obj + "," + dynamicObject.get("fbasedataid." + yem_identifierbasic1);
                            } else {
                                obj = obj + "," + dynamicObject.get("fbasedataid.name.zh_CN");
                            }
                        }
                    }
                } else {
                    DynamicObject DynamicObject = entityDynamico.getDynamicObject(yem_erpfiledformid1);
                    if (DynamicObject != null) {
                        obj = CommonUtils.GetObjDynamicObjectStats(DynamicObject, yem_identifierbasic1);
                    }
                }
            } else if ("datetime".equals(yem_erpfiledtype1) || "date".equals(yem_erpfiledtype1)) {
                if (StringUtils.isNotEmpty(yem_erpfiledtype1) && yem_iatype.equals("单行文本框")) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    if (entityDynamico.getDate(yem_erpfiledformid1) == null) {
                        obj = "";
                    } else {
                        obj = sdf.format(entityDynamico.getDate(yem_erpfiledformid1));
                    }
                } else {
                    if (entityDynamico.getDate(yem_erpfiledformid1) != null) {
                        obj = entityDynamico.getDate(yem_erpfiledformid1).getTime();//长日期
                    }
                }
            } else if ("short_date".equals(yem_erpfiledtype1)) {
                if (StringUtils.isNotEmpty(yem_erpfiledtype1) && yem_iatype.equals("单行文本框")) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                    if (entityDynamico.getDate(yem_erpfiledformid1) == null) {
                        obj = "";
                    } else {
                        obj = sdf.format(entityDynamico.getDate(yem_erpfiledformid1));
                    }
                }
            } else if ("number".equals(yem_erpfiledtype1)) {
                if (iaaccuracy1 > 0) {
                    obj = entityDynamico.getBigDecimal(yem_erpfiledformid1).setScale(iaaccuracy1, BigDecimal.ROUND_HALF_UP).toString();
//                if("numberWidget".equals(yem_iatype)||"moneyWidget".equals(yem_iatype)){
//                    obj = new BigDecimal(obj.toString()).setScale(iaaccuracy1);
//                }
                } else {
                    if (entityDynamico.getBigDecimal(yem_erpfiledformid1).compareTo(BigDecimal.ZERO) == 0) {
                        obj = BigDecimal.ZERO.toString();
                    } else {
                        obj = entityDynamico.getBigDecimal(yem_erpfiledformid1).setScale(iaaccuracy1, BigDecimal.ROUND_HALF_UP).toString();
//                    if("numberWidget".equals(yem_iatype)||"moneyWidget".equals(yem_iatype)){
//                        obj = new BigDecimal(obj.toString()).setScale(iaaccuracy1).setScale(iaaccuracy1);
//                    }
                    }

                }
            } else if ("enum".equals(yem_erpfiledtype1)) {//下拉
                if (StringUtils.isNotEmpty(yem_erpfiledformid1)) {
                    Boolean BooleanProp = CheckBooleanProp(entityName, yem_erpfiledformid1);
                    if (BooleanProp) {
                        boolean erpfiledformid1Value = entityDynamico.getBoolean(yem_erpfiledformid1);
                        if (erpfiledformid1Value) {
                            obj = "是";
                        } else {
                            obj = "否";
                        }
                    } else {
                        if (StringUtils.isNotEmpty(yem_identifierbasic1) || yem_identifierbasic1.equals("key")) {
                            obj = entityDynamico.getString(yem_erpfiledformid1);
                        } else {
                            obj = getDownList(entityName, yem_erpfiledformid1, entityDynamico.getString(yem_erpfiledformid1));
                        }
                    }
                }
            } else {
                obj = entityDynamico.getString(yem_erpfiledformid1);
            }
        }
        return obj;
    }

    /**
     * 获取下拉项的值
     *
     * @param fromMark             表单标识
     * @param fieldMark            单据体内字段标识
     * @param yem_identifierbasic1 获取方式获取值对应标题
     * @return 标题
     */
    public static String getDownList(String fromMark, String fieldMark, String yem_identifierbasic1) {
        MainEntityType type11 = MetadataServiceHelper.getDataEntityType(fromMark);
        ComboProp ComboProp = (ComboProp) type11.findProperty(fieldMark);
        List<ValueMapItem> comboItems = ComboProp.getComboItems();
        LocaleString comboItemName = comboItems.get(0).getName();
        HashMap<String, Object> mapSetResult = new HashMap<>(16);
        for (ValueMapItem comboItem : comboItems) {
            String key = comboItem.getValue();
            LocaleString value = comboItem.getName();
            mapSetResult.put(key, value);
        }
        if (mapSetResult.get(yem_identifierbasic1) == null) {
            return null;
        }
        return mapSetResult.get(yem_identifierbasic1).toString();
    }

    /**
     * 判断是否复选框
     *
     * @param entityName 单据标识
     * @param fieldMark  字段标识
     * @return 是否复选框
     */
    public static Boolean CheckBooleanProp(String entityName, String fieldMark) {
        Boolean reut = false;
        MainEntityType type11 = MetadataServiceHelper.getDataEntityType(entityName);
        IDataEntityProperty property = type11.findProperty(fieldMark);
        if (property instanceof ComboProp) {
            reut = false;
        } else {
            reut = true;
        }
        return reut;
    }

    /**
     * 根据表单id获取附件指定附件面板信息
     *
     * @param formId    表单标识
     * @param pkId      单据id
     * @param attachKey 附件标识
     * @return JSONArray
     */
    public static JSONArray GetAttachment(String formId, Object pkId, String attachKey) {
        JSONArray jsonArray = new JSONArray();
        try {
            List<Map<String, Object>> attachments = AttachmentServiceHelper.getAttachments(formId, pkId, attachKey);
            if (attachments.size() > 0) {
                String accessToken = YunzhijiaUtils.getYzhToken();
                if (accessToken != null) {
                    for (int i = 0; i < attachments.size(); i++) {
                        Map<String, Object> map = attachments.get(i);
                        String fileurl = (String) map.get("url");
                        if (fileurl.contains("http://localhost:8080/ierp/")) {
                            fileurl = fileurl.replace("http://localhost:8080/", "http://10.64.112.152:8022/");
                        }

                        String result = YunzhijiaUtils.uploadfile(fileurl, accessToken, (String) map.get("name"));
                        JSONObject json = JSONObject.parseObject(result);
                        Boolean success = json.getBoolean("success");
                        if (success) {
                            JSONArray data = json.getJSONArray("data");
                            for (int j = 0; j < data.size(); j++) {
                                JSONObject object = new JSONObject();
                                JSONObject jsonObject = data.getJSONObject(j);
                                if (jsonObject != null) {
//                                    object.put("fileName", jsonObject.getString("fileName"));
                                    object.put("fileName", map.get("name").toString());
                                    object.put("fileId", jsonObject.getString("fileId"));
                                    object.put("fileSize", jsonObject.getString("length"));
                                    object.put("fileType", jsonObject.getString("fileType"));
                                    object.put("fileExt", map.get("type").toString());
                                    jsonArray.add(object);
                                    //创建ERP与云之家对照表
                                    Addattyunzhijia(formId, pkId, map, attachKey, jsonObject);
                                }
                            }
                        }
                    }
                }
            } else {

            }
        } catch (Exception ex) {
            String message = ex.getMessage();
            throw new KDBizException(message);
        }
        return jsonArray;
    }

    /**
     * 根据云之家返回结果创建底表
     *
     * @param formId     表单id
     * @param pkId       单据标识
     * @param map        附件信息
     * @param attachKey  附件面板标识
     * @param jsonObject 云之家返回结果
     */
    public static void Addattyunzhijia(String formId, Object pkId, Map<String, Object> map, String attachKey, JSONObject jsonObject) {
        DynamicObject billObj = BusinessDataServiceHelper.newDynamicObject("yem_attyunzhijia");
        billObj.set("enable", "1");
        billObj.set("status", "C");
        billObj.set("number", formId);
        billObj.set("name", pkId.toString());
        billObj.set("yem_cosmicid", map.get("attPkId").toString());
        billObj.set("yem_cosmicname", map.get("name").toString());
        String url = map.get("url").toString();
        if (url.contains("http://localhost:8080/ierp/")) {
            String yem_cosmicurl = url.replace("http://localhost:8080/", "http://10.64.112.152:8022/");
            billObj.set("yem_cosmicurl", yem_cosmicurl);
        } else {
            billObj.set("yem_cosmicurl", map.get("url").toString());
        }
        billObj.set("yem_cosmickey", attachKey);
        billObj.set("yem_yzjid", jsonObject.getString("fileId"));
        billObj.set("yem_yzjname", jsonObject.getString("fileName"));
        billObj.set("yem_yzjid", jsonObject.getString("fileId"));
        billObj.set("yem_yzjresult", jsonObject.toString());

        OperationResult Operate = OperationServiceHelper.executeOperate("save",
                billObj.getDynamicObjectType().getName(),
                new DynamicObject[]{billObj}, OperateOption.create());
        if (Operate.isSuccess()) {

        } else {
//            List<IOperateInfo> allErrorOrValidateInfo = Operate.getAllErrorOrValidateInfo();
//            String message = Operate.getMessage();
//            throw new KDBizException("保存《替换关系》失败，失败信息为：," + message + "，" + allErrorOrValidateInfo);
        }
    }
}
