package org.example.Entity.Attributes;


import org.example.Api.BaseHandler;
import org.example.Impl.BaseImpl;
import org.example.Impl.VerifyImpl;
import org.example.Utils.CacheUtil;
import org.example.Utils.JSON;
import org.example.Utils.LanguageUtil;
import org.example.Utils.WebConfigUtil_web;

import java.time.Duration;
import java.util.function.Supplier;

import static org.example.Utils.NativeExtensionUtils.isNullOrEmpty;
import static org.example.Utils.NativeExtensionUtils.toBoolean;

/**
 * 功能描述：RequestCheckAttribute
 * 创 建 者：wzy
 * 创建日期：2017-01-05 22:33:06
 */
public class RequestCheckAttribute implements Attribute {
    /**
     * 是否检查登录信息
     */
    public Boolean CheckLogin = true;

    /**
     * 是否向客户端回写
     */
    public Boolean WriteRespose = true;

    /**
     * 检查request的字段是否为空
     */
    public String CheckParams = "";

    public boolean Log = true;

    public boolean Verify = true;

    public boolean Cache = false;
    /// <summary>
    /// 缓存失效时间，默认30分钟
    /// </summary>
    public int ExpirationPeriod = 10;

    public String Name;

    public String Desp;


    private VerifyImpl _verifyimpl;
    private BaseImpl _bImpl;

    private VerifyImpl getVerifyImpl() {
        if (_verifyimpl == null) {
            _verifyimpl = new VerifyImpl();
        }
        return _verifyimpl;
    }

    public BaseImpl getBImpl() {
        if (_bImpl == null) {
            _bImpl = new BaseImpl();
        }
        return _bImpl;
    }

    public void setBImpl(BaseImpl bImpl) {
        this._bImpl = bImpl;
    }

    /**
     * 验证参数是否有效
     *
     * @param errMsg 检查参数配置
     * @return 验证结果数组，第一个元素为是否有效，第二个元素为错误信息
     */
    public Boolean validParams(String[] errMsg) {
        errMsg[0] = "";
        if (!isValid()) {
            return false;
        }

        if (isNullOrEmpty(CheckParams)) {
            return true;
        }

        String[] pamNames = CheckParams.split(",");
        for (String pamName : pamNames) {
            if (pamName == null || pamName.isEmpty()) {
                continue;
            }

            String[] orPamNames = pamName.split("\\|"); // 转义|符号
            if (orPamNames.length == 1) {
                if (getBImpl().Request(pamName) == null || getBImpl().Request(pamName).isEmpty()) {
                    errMsg[0] = String.format("%s:%s", LanguageUtil.InvalidParameter, pamName);
                    return false;
                }
            } else {
                boolean hasVal = false;
                for (String orName : orPamNames) {
                    if (getBImpl().Request(orName) != null && !getBImpl().Request(orName).isEmpty()) {
                        hasVal = true;
                        break;
                    }
                }

                if (!hasVal) {
                    errMsg[0] = String.format("%s:%s", LanguageUtil.InvalidParameter, pamName.replace("|", "或"));
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * 获取缓存值
     *
     * @param handler       基础处理器
     * @param getCacheValue 获取缓存值的供应商
     * @return 缓存值或新生成的值
     */
    public Object getCacheVal(BaseHandler handler, Supplier<Object> getCacheValue) {
        if (Cache && toBoolean(WebConfigUtil_web.get("Cache", ""))) {
            String key = String.valueOf((handler.getClass().getName()
                    + "_" + getBImpl().getUser().UserId
                    + "_" + getBImpl().getUser().UserName
                    + "_" + JSON.Encode(getBImpl().getAllRequest())).hashCode());

            // 将Supplier转换为Function<Void, Object>
            return CacheUtil.getCacheItem(key,
                    (Void v) -> getCacheValue.get(),  // 适配Function接口
                    Duration.ofMinutes(ExpirationPeriod),
                    null, null);
        }
        return getCacheValue.get();
    }

    public boolean isValid() {
        return validVerify();
    }

    public boolean validVerify() {
        if (!Verify) {
            return true;
        } else {
            return getVerifyImpl().verify().isSuccess();
        }
    }

}