package com.kingdee.eas.custom.integration.feishu.app;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.IObjectPK;
import com.kingdee.bos.dao.IObjectValue;
import com.kingdee.bos.dao.ObjectNotFoundException;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.integration.feishu.FeishuConfigCollection;
import com.kingdee.eas.custom.integration.feishu.FeishuConfigInfo;
import com.kingdee.shr.base.syssetting.BaseItemException;
import com.kingdee.shr.base.syssetting.BaseItemStateEnum;
import com.lark.oapi.Client;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 飞书应用配置
 */
public class FeishuConfigControllerBean extends AbstractFeishuConfigControllerBean {
    private static Logger logger = Logger.getLogger(FeishuConfigControllerBean.class);

    private static final Map<String, Client> FEISHU_CLIENT_CONFIG = new HashMap<String, Client>();
    //是否加载配置
    //private static Boolean isLoadConfig = false;

//    private void loadConfig(Context ctx) throws BOSException {
//        try {
//            // 构建查询条件并获取配置集合
//            FilterInfo filterInfo = new FilterInfo();
//            //状态等于启用
//            filterInfo.getFilterItems().add(new FilterItemInfo("state", BaseItemStateEnum.ENABLE));
//            EntityViewInfo viewInfo = EntityViewInfo.getInstance(filterInfo, null, null);
//            FeishuConfigCollection feishuConfigCollection = getFeishuConfigCollection(ctx, viewInfo);
//            // 验证查询结果
//            if (feishuConfigCollection.isEmpty()) {
//                throw new BOSException("加载配置失败，未找到启用状态的飞书应用配置");
//            }
//            for (int i = 0; i < feishuConfigCollection.size(); i++) {
//                FeishuConfigInfo feishuConfigInfo = feishuConfigCollection.get(i);
//                String appID = feishuConfigInfo.getAppID();
//                // 构建client
//                FEISHU_CLIENT_CONFIG.put(appID, Client.newBuilder(feishuConfigInfo.getAppID(), feishuConfigInfo.getAppSecret()).build());
//            }
//            isLoadConfig = true;
//        } catch (BOSException e) {
//            logger.error("加载飞书应用配置异常: " + e.getMessage(), e);
//            throw new BOSException("加载飞书应用配置异常: " + e.getMessage());
//        }
//    }
//
//    private void updateConfig(Context ctx, String appId) throws BOSException {
//        try {
//            //移除
//            FEISHU_CLIENT_CONFIG.remove(appId);
//
//            // 构建查询条件并获取配置集合
//            FilterInfo filterInfo = new FilterInfo();
//            filterInfo.getFilterItems().add(new FilterItemInfo("appId", appId));
//            EntityViewInfo viewInfo = EntityViewInfo.getInstance(filterInfo, null, null);
//            FeishuConfigCollection feishuConfigCollection = getFeishuConfigCollection(ctx, viewInfo);
//            // 验证查询结果
//            if (feishuConfigCollection.isEmpty()) {
//                throw new BOSException("加载配置失败，未找到启用状态的飞书应用配置");
//            }
//            for (int i = 0; i < feishuConfigCollection.size(); i++) {
//                FeishuConfigInfo feishuConfigInfo = feishuConfigCollection.get(i);
//                String appID = feishuConfigInfo.getAppID();
//                // 构建client
//                FEISHU_CLIENT_CONFIG.put(appID, Client.newBuilder(feishuConfigInfo.getAppID(), feishuConfigInfo.getAppSecret()).build());
//            }
//            isLoadConfig = true;
//        } catch (BOSException e) {
//            logger.error("加载飞书应用配置异常: " + e.getMessage(), e);
//            throw new BOSException("加载飞书应用配置异常: " + e.getMessage());
//        }
//    }


    @Override
    protected IObjectPK _save(Context ctx, IObjectValue model) throws BOSException, EASBizException {

        FeishuConfigInfo info = (FeishuConfigInfo) model;
        //应用id
        String appID = info.getAppID();

        String appSecret = info.getAppSecret();
        Set<String> errorMsg = new HashSet<String>();
        if (StringUtils.isBlank(appID)) {
            errorMsg.add("应用ID");
        }
        if (StringUtils.isBlank(appSecret)) {
            errorMsg.add("应用密钥");
        }
        if (!errorMsg.isEmpty()) {
            throw new BaseItemException(BaseItemException.CUSTOM_EXCEPTION,
                    new Object[]{String.join("、", errorMsg) + "不能为空！"});
        }

        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        filterItems.add(new FilterItemInfo("appID", appID));
        if (info.getId() != null) {
            filterItems.add(new FilterItemInfo("id", info.getId(), CompareType.NOTEQUALS));
        }
        if (exists(ctx, filterInfo)) {
            throw new BaseItemException(BaseItemException.CUSTOM_EXCEPTION, new Object[]{"应用Id[" + appID + "]已存在！"});
        }
        return super._save(ctx, model);
    }

    /**
     * 新增
     *
     * @param ctx
     * @param model
     * @return
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected IObjectPK _addnew(Context ctx, IObjectValue model) throws BOSException, EASBizException {
        FeishuConfigInfo info = (FeishuConfigInfo) model;
        //设置为启用
        info.setState(BaseItemStateEnum.ENABLE);
        FeishuConfigCollection feishuConfigCollection = getDefaultConfigs(ctx);
        if (feishuConfigCollection.isEmpty()) {
            //如果默认配置不存在，则设置为默认配置
            info.setDefaultConfig(true);
        }
        return super._addnew(ctx, model);
    }

    /**
     * 设置默认配置
     *
     * @param ctx
     * @param billId
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected void _setDefaultConfig(Context ctx, String billId) throws BOSException, EASBizException {
        //super._setDefaultConfig(ctx, billId);
        if (StringUtils.isBlank(billId)) {
            throw new BaseItemException(BaseItemException.CUSTOM_EXCEPTION, new Object[]{"单据id为空!"});
        } else if (billId.split(",").length > 1) {
            throw new BaseItemException(BaseItemException.CUSTOM_EXCEPTION, new Object[]{"只能设置一条默认应用配置!"});
        }
        //飞书应用配置
        FeishuConfigInfo info = getFeishuConfigInfo(ctx, new ObjectUuidPK(billId), this.getShrBaseItemSelector());
        if (!BaseItemStateEnum.ENABLE.equals(info.getState())) {
            throw new BaseItemException(BaseItemException.CUSTOM_EXCEPTION, new Object[]{"该应用配置未启用，请先启用"});
        }
        SelectorItemCollection updateSic = new SelectorItemCollection();
        updateSic.add("defaultConfig");
        try {
            FeishuConfigCollection defaultConfigCollection = getDefaultConfigs(ctx);
            if (!defaultConfigCollection.isEmpty()) {
                for (int i = 0; i < defaultConfigCollection.size(); i++) {
                    //将原有默认配置设置否
                    FeishuConfigInfo defaultConfigInfo = defaultConfigCollection.get(i);
                    defaultConfigInfo.setDefaultConfig(false);
                    updatePartial(ctx, defaultConfigInfo, updateSic);
                }
            }
            //是否默认配置
            info.setDefaultConfig(true);
            updatePartial(ctx, info, updateSic);
        } catch (ObjectNotFoundException e) {
            logger.error(e.getMessage(), e);
            throw new BaseItemException(BaseItemException.BASEITEM_NOT_EXIST);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new BaseItemException(BaseItemException.CUSTOM_EXCEPTION, new Object[]{e.getMessage()});
        }

    }

    /**
     * 获取默认配置
     *
     * @param ctx
     * @return
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected FeishuConfigCollection _getDefaultConfigs(Context ctx) throws BOSException, EASBizException {
        FilterInfo filterInfo = new FilterInfo();
        FilterItemCollection filterItems = filterInfo.getFilterItems();
        filterItems.add(new FilterItemInfo("defaultConfig", true));

        EntityViewInfo viewInfo = EntityViewInfo.getInstance(filterInfo, null, null);

        FeishuConfigCollection defaultConfigCollection = getFeishuConfigCollection(ctx, viewInfo);
        return defaultConfigCollection;
    }

    /**
     * 禁用
     * 默认配置不能为禁用
     *
     * @param ctx
     * @param id
     * @throws BOSException
     * @throws EASBizException
     */
    @Override
    protected void _disable(Context ctx, String id) throws BOSException, EASBizException {
        try {
            //飞书应用配置
            FeishuConfigInfo info = getFeishuConfigInfo(ctx, new ObjectUuidPK(id), this.getShrBaseItemSelector());
            //是否默认配置
            if (info.isDefaultConfig()) {
                throw new BaseItemException(BaseItemException.CUSTOM_EXCEPTION, new Object[]{"默认配置不能禁用！"});
            }
        } catch (ObjectNotFoundException var6) {
            throw new BaseItemException(BaseItemException.BASEITEM_DELETE_DISABLE_FAIL);
        }
        super._disable(ctx, id);
    }


    private SelectorItemCollection getShrBaseItemSelector() {
        SelectorItemCollection selector = new SelectorItemCollection();
        selector.add(new SelectorItemInfo("id"));
        selector.add(new SelectorItemInfo("name"));
        selector.add(new SelectorItemInfo("number"));
        selector.add(new SelectorItemInfo("shrBasicItem.id"));
        selector.add(new SelectorItemInfo("usePolicy"));
        selector.add(new SelectorItemInfo("isSysPreset"));
        selector.add(new SelectorItemInfo("state"));
        selector.add(new SelectorItemInfo("hrOrgUnit.id"));
        selector.add(new SelectorItemInfo("hrOrgUnit.number"));
        selector.add(new SelectorItemInfo("hrOrgUnit.name"));
        selector.add(new SelectorItemInfo("defaultConfig"));
        return selector;
    }
}