package yem.base.common.module.meta.task;

import kd.bos.algo.DataSet;
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.entity.report.FilterInfo;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.DeleteServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;
import yem.base.common.module.meta.report.DataDictionaryRptQuery;
import yem.base.common.utils.YEM;

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

/**
 * @Description: 字段标识库 定时更新插件
 * @author: lib
 * @date: 2025/1/9 9:54
 */
public class FieldKeyStoreUpdateTaskPlugin extends AbstractTask implements Plugin {

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        // 获取参数
        String bizcloudkey = (String) map.get("bizcloudkey");// 业务云标识
        String appkeys = (String) map.get("appkeys");// 应用标识拼接
        if (YEM.isEmpty(bizcloudkey) || YEM.isEmpty(appkeys))return;
        String[] appkeyArray = appkeys.split(",");
        for (String appkey : appkeyArray) {
            // 更新数据
            try {
                updateFieldKeyStore(bizcloudkey, appkey);
            } catch (Throwable e) {
                throw new KDException(e.getMessage());
            }
        }
    }



    /**
     * @Description: 查询并更新字段标识库数据
     * @function 功能：
     *              1、根据业务云、应用标识查询【数据字典】报表：获取对应应用下所有表单元数据项
     *              2、根据所查结果分别查询每个元数据 对应表单字段
     *              3、查询【字段标识库】，删除已有对应历史数据，创建最新数据
     * @purposes 定时任务更新调用
     * @param bizcloudkey  业务云标识
     * @param appkey       应用标识
     * @return void  无
     */
    private void updateFieldKeyStore (String bizcloudkey ,String appkey) throws Throwable {
        // 定义List 用以收集 新增的数据
        List<DynamicObject> creatNewList = new ArrayList<>();
        // 定义List 用以收集 涉及到的表单ID
        List<String> billIdList = new ArrayList<>();
        // 查询 业务云/应用 的所有元数据实体
        DataDictionaryRptQuery report = new DataDictionaryRptQuery();
        ReportQueryParam Param  = new  ReportQueryParam();
        FilterInfo filters = Param.getFilter();
        filters.addFilterItem("yem_datefilter", "1");
        filters.addFilterItem("yem_fbizcloud", bizcloudkey);
        filters.addFilterItem("yem_fapp", appkey);
        Param.setFilter(filters);
        DataSet entityList = report.query(Param, null);
        entityList = entityList.where(String.format("yem_appkey = '%s'", appkey));
        DynamicObjectCollection entityCollection = ORM.create().toPlainDynamicObjectCollection(entityList);
        for (DynamicObject entity : entityCollection){
            String yemEntityid = entity.getString("yem_entityid");// 表单ID
            String yemEntitykey = entity.getString("yem_entitykey");// 表单标识
            // 查询 元数据实体 的所有字段信息
            DataSet entityFields = DataDictionaryRptQuery.queryDataBill(yemEntitykey);
            DynamicObjectCollection fieldsCollection = ORM.create().toPlainDynamicObjectCollection(entityFields);
            for(DynamicObject fields : fieldsCollection){
                DynamicObject addNew = BusinessDataServiceHelper.newDynamicObject("yem_base_fieldkeystore");
                addNew.set("name",yemEntitykey+fields.getString("yem_number2"));//名称
                addNew.set("enable", "1");//使用状态
                addNew.set("status", "C");//数据状态
                addNew.set("yem_bizcloud",entity.getString("yem_bizcloud"));// 业务云ID
                addNew.set("yem_bizcloudkey",entity.getString("yem_bizcloudkey"));// 业务云标识
                addNew.set("yem_bizcloudname",entity.getString("yem_bizcloudname"));// 业务云名称
                addNew.set("yem_appid",entity.getString("yem_appid"));// 应用ID
                addNew.set("yem_appkey",entity.getString("yem_appkey"));// 应用标识
                addNew.set("yem_appname",entity.getString("yem_appname"));// 应用名称
                addNew.set("yem_dbroute",entity.getString("yem_dbroute"));// 数据库标识
                addNew.set("yem_entityid",yemEntityid);// 表单ID
                addNew.set("yem_entitykey",yemEntitykey);// 表单标识
                addNew.set("yem_entityname",entity.getString("yem_entityname"));// 表单名称
                addNew.set("yem_modeltype",entity.getString("yem_modeltype"));// 模型类型
                addNew.set("yem_isv",entity.getString("yem_isv"));// 开发商标识
                addNew.set("yem_parentname",fields.getString("yem_parent2"));// 父实体名称
                addNew.set("yem_entitysname",fields.getString("yem_entity2"));// 实体名称
                addNew.set("yem_fieldnumber",fields.getString("yem_number2"));// 字段编码
                addNew.set("yem_fieldnumbers",fields.getString("yem_fullnumber2"));// 字段全编码
                addNew.set("yem_aliasname",fields.getString("yem_alias2"));// 对应数据库字段名
                addNew.set("yem_datatype",fields.getString("yem_aliastype2"));// 数据类型
                addNew.set("yem_fieldname",fields.getString("yem_name2"));// 字段名称
                addNew.set("yem_fieldnames",fields.getString("yem_fullname2"));// 字段全名
                addNew.set("yem_fieldtype",fields.getString("yem_datatype2"));// 字段类型
//                addNew.set("yem_fieldtypekey",fields.getString("yem_datatype_key2"));// 字段类型key
                addNew.set("yem_basedatatype",fields.getString("yem_basedatakey2"));// 基础资料类型
                creatNewList.add(addNew);
            }
            billIdList.add(yemEntityid);
        }
        Log log = LogFactory.getLog(this.getClass());
        // 删除 字段标识库 中的历史数据
        if (!billIdList.isEmpty()){
            DeleteServiceHelper.delete("yem_base_fieldkeystore",
                    new QFilter[]{new QFilter("yem_entityid", QCP.in, billIdList)});
            log.info("字段标识库定时更新: 历史数据删除成功-"+billIdList.size()+"条");
        }
        // 保存最新的数据
        if(!creatNewList.isEmpty()){
            OperationResult operationResult = SaveServiceHelper.saveOperate("save",
                    "yem_base_fieldkeystore", creatNewList.toArray(new DynamicObject[0]),
                    OperateOption.create());
            if (operationResult.isSuccess()){
                log.info("字段标识库定时更新: 更新数据成功-云标识："+bizcloudkey+"应用标识："+appkey+
                        "数据："+creatNewList.size()+"条");
            } else {
                log.error("字段标识库定时更新: 更新数据失败-云标识："+bizcloudkey+"应用标识："+appkey+
                        "数据："+creatNewList.size()+"条; 失败原因："+operationResult.getMessage());
            }
        }

    }
}