package nckd.jxccl.base.entity.helper;

import com.google.common.collect.Lists;
import kd.bos.common.enums.EnableEnum;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.constant.StatusEnum;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.base.orm.helper.QFilterCommonHelper;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 实体（DynamicObject） 帮助类
 * @author W.Y.C
 * @date 2025/7/17 19:58
 * @version 1.0
 */
public class EntityHelper {

    public static DynamicObject newEntity(String entityName){
        return BusinessDataServiceHelper.newDynamicObject(entityName);
    }

    public static DynamicObject newEntity(String entityName, Long id){
        DynamicObject dy = BusinessDataServiceHelper.newDynamicObject(entityName);
        dy.set(FormConstant.ID_KEY, id);
        return dy;
    }

    /**
     * 创建一个状态为"可用"的基础资料对象
     * @param entityName 实体标识
     * @return: kd.bos.dataentity.entity.DynamicObject 新创建的基础资料实体，状态已设置为可用（数据状态：已审核、使用状态：可用），并设置创建时间、创建人、创建组织、业务单元
     * @author W.Y.C
     * @date: 2025/07/17 20:06
     */
    public static DynamicObject newAvailableBasicEntity(String entityName){
        return newAvailableBasicEntity(entityName, null, null);
    }

    /**
     * 创建一个状态为"可用"的基础资料对象
     * @param entityName 实体标识
     * @param org 组织id
     * @param currUser 当前用户
     * @return: kd.bos.dataentity.entity.DynamicObject 新创建的基础资料实体，状态已设置为可用（数据状态：已审核、使用状态：可用），并设置创建时间
     * @author W.Y.C
     * @date: 2025/07/17 20:13
     */
    public static DynamicObject newAvailableBasicEntity(String entityName,DynamicObject org, DynamicObject currUser){
        if(currUser == null){
            DynamicObject buildEvalResult = BusinessDataServiceHelper.newDynamicObject(entityName);
            Long currUserId =  RequestContext.get().getCurrUserId();
            //当前登录用户
            currUser = UserServiceHelper.getUserInfoByID(currUserId, FormConstant.ID_KEY);
        }
        if(org == null){
            Long currOrgId =  RequestContext.get().getOrgId();
            // 获取苍穹平台组织实体元数据
            MainEntityType bosOrgEntityType = EntityMetadataCache.getDataEntityType(FormConstant.BOS_ORG);
            // 基于元数据创建 DynamicObject
            org = new DynamicObject(bosOrgEntityType);
            org.set(FormConstant.ID_KEY,currOrgId);
        }

        DynamicObject dynamicObject = BusinessDataServiceHelper.newDynamicObject(entityName);
        dynamicObject.set(FormConstant.CREATEORG_KEY, org);
        dynamicObject.set(FormConstant.USEORG_KEY, org);
        dynamicObject.set(FormConstant.CREATE_TIME_KEY, new Date());
        dynamicObject.set(FormConstant.CREATOR_KEY, currUser);
        dynamicObject.set(FormConstant.STATUS, StatusEnum.C.toString());
        dynamicObject.set(FormConstant.ENABLE, EnableEnum.YES.getCode());
        return dynamicObject;
    }


    /**
     * 根据编码查询最新的id
     * @param entityNumber
     * @param number
     */
    public static Long getLatestIdByNumber(String entityNumber, String number) {
        Map<String, Long> map = getLatestIdByNumber(entityNumber, Lists.newArrayList(number));
        return !map.isEmpty() ? map.get(number) : null;
    }

    /**
     * 根据编码查询最新的id
     * @param entityNumber
     * @param number
     * @return
     */
    public static Map<String,Long> getLatestIdByNumber(String entityNumber, List<String> number) {
        QFilter filter = new QFilter("number", QCP.in, number)
                .and(QFilterCommonHelper.getCurrentVersionFilter())
                .and(QFilterCommonHelper.getStatusFilter())
                .and(QFilterCommonHelper.getEnableFilter());
        QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create()
                .add(FormConstant.ID_KEY)
                .add(FormConstant.NUMBER_KEY)
                .add(FormConstant.MODIFY_TIME_KEY);
        DynamicObjectCollection query = QueryServiceHelper.query(entityNumber, queryFieldBuilder.buildSelect(), new QFilter[]{filter});

        // 按number分组，取每组的第一条（即最新的记录）
        return query.stream()
                .collect(Collectors.groupingBy(
                        obj -> obj.getString(FormConstant.NUMBER_KEY)
                ))
                .entrySet()
                .stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> entry.getValue().get(0).getLong(FormConstant.ID_KEY) // 取每组第一条记录的ID
                ));
    }

    /**
     * 根据编码查询id
     * @param entityNumber
     * @param number
     */
    public static Long getIdByNumber(String entityNumber,String number) {
        Map<String, Long> map = getIdByNumber(entityNumber, Lists.newArrayList(number));
        return !map.isEmpty() ? map.get(number) : null;
    }


    /**
     * 根据编码查询id
     * @param entityNumber
     * @param number
     * @return
     */
    public static Map<String,Long> getIdByNumber(String entityNumber, List<String> number) {
        QFilter filter = new QFilter("number", QCP.in, number)
                .and(QFilterCommonHelper.getStatusFilter())
                .and(QFilterCommonHelper.getEnableFilter());
        QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create().add(FormConstant.ID_KEY).add(FormConstant.NUMBER_KEY);
        DynamicObjectCollection query = QueryServiceHelper.query(entityNumber, queryFieldBuilder.buildSelect(), new QFilter[]{filter});
        return query.stream()
                .collect(Collectors.toMap(
                        obj -> obj.getString(FormConstant.NUMBER_KEY),  // key: number
                        obj -> obj.getLong(FormConstant.ID_KEY)         // value: id
                ));

    }


}