package nckd.jxccl.base.entity.helper;

import kd.bos.common.enums.EnableEnum;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.constant.StatusEnum;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import nckd.jxccl.base.common.constant.FormConstant;

import java.util.Date;

/**
 * 实体（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;
    }
}