package com.jeequan.jeepay.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.entity.MchApplyment;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.CashierConfig;
import com.jeequan.jeepay.core.model.DBDefaultConfig;
import com.jeequan.jeepay.core.model.mchconfig.MchDivisionConfig;
import com.jeequan.jeepay.db.entity.MchAppEntity;
import com.jeequan.jeepay.db.entity.MchConfig;
import com.jeequan.jeepay.service.mapper.MchConfigMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商户配置表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2022-02-09
 */
@Service
public class MchConfigService extends ServiceImpl<MchConfigMapper, MchConfig> {

    @Autowired private SysConfigService configService;

    @Autowired private MchAppService mchAppService;

    public MchConfig getByMchNoAndConfigKey(String mchNo, String configKey) {
        return baseMapper.selectOne(MchConfig.gw()
                .eq(MchConfig::getMchNo, mchNo)
                .eq(MchConfig::getConfigKey, configKey)
        );
    }

    public MchConfig get(String mchNo, String mchAppId, String configKey) {
        return lambdaQuery().eq(MchConfig::getMchNo, mchNo)
                .eq(MchConfig::getMchAppId, mchAppId)
                .eq(MchConfig::getConfigKey, configKey)
                .one();
    }

    public MchConfig get(String mchNo, String mchAppId, String mchApplyId, String configKey) {
        return lambdaQuery().eq(MchConfig::getMchNo, mchNo)
                .eq(MchConfig::getMchAppId, mchAppId)
                .eq(MchConfig::getConfigKey, configKey)
                .eq(MchConfig::getMchApplyId, mchApplyId)
                .one();
    }

    /**
     * 电子围栏状态获取
     * @param mchApplyment 商户进件信息
     * @return  1，开启；0，未开启
     */
    public String getRegionLock(MchApplyment mchApplyment) {
        MchConfig config = lambdaQuery().eq(MchConfig::getMchNo, mchApplyment.getMchNo())
                .eq(MchConfig::getMchAppId, mchApplyment.getAutoConfigMchAppId())
                .eq(MchConfig::getMchApplyId, mchApplyment.getApplyId())
                .eq(MchConfig::getConfigKey, MchConfig.Option.REGION_LOCK_OFFLINE.getConfigKey())
                .one();

        if (config == null) {
            MchAppEntity mchApp = mchAppService.getById(mchApplyment.getAutoConfigMchAppId());

            if (mchApp.getRange() == 1) {
                return MchConfig.Option.REGION_LOCK_ONLINE.getDefVal();
            } else {
                return MchConfig.Option.REGION_LOCK_OFFLINE.getDefVal();
            }
        }

        return config.getConfigVal();
    }

    public int saveOrUpdateConfig(MchConfig mchConfig) {

        MchConfig dbMchConfig = this.getByMchNoAndConfigKey(mchConfig.getMchNo(), mchConfig.getConfigKey());

        int count;
        if(dbMchConfig != null) {
            count = baseMapper.update(mchConfig,
                    new LambdaUpdateWrapper<MchConfig>().eq(MchConfig::getConfigKey, mchConfig.getConfigKey()).eq(MchConfig::getMchNo, mchConfig.getMchNo()));
        }else {
            count = baseMapper.insert(mchConfig);
        }

        return count;
    }

    /**
     * @since 2024-04-09 新增应用号mchAppId，用户进件号mchApplyId
     */
    public int updateBatch(List<MchConfig> mchConfigList, String mchNo, String mchAppId, String mchApplyId, String groupKey) {
        int count = 0;

        if (!ObjUtil.isEmpty(mchApplyId)) {
            Assert.notNull(mchApplyId, "应用号[mchApplyId]不能为空");
        }

        for (MchConfig mchConfig : mchConfigList) {
            mchConfig.setMchNo(mchNo);
            mchConfig.setGroupKey(groupKey);
            mchConfig.setMchAppId(mchAppId);
            mchConfig.setMchApplyId(mchApplyId);
            checkData(mchConfig);
            count += this.saveOrUpdateConfig(mchConfig);
        }

        return count;
    }

    /**
     * 数据校验以及自动填充, 按需添加相关校验
     * @param mchConfigList 用户的配置数据
     */
    private void checkData(MchConfig mchConfig) {
        if ("mchApiEnt".equals(mchConfig.getConfigKey())) {
            // api接口权限，必须关联应用
            if (ObjUtil.isEmpty(mchConfig.getMchAppId())) {
                throw new BizException("配置应用接口权限必须传应用ID");
            }
        }
    }

    public void initConfig(String mchNo) {

        List<MchConfig> list = new LinkedList<>();

        for (Map<String, String> map : MchConfig.configList) {
            MchConfig mchConfig = new MchConfig();
            mchConfig.setMchNo(mchNo)
                    .setConfigKey(map.get("configKey"))
                    .setConfigName(map.get("configName"))
                    .setConfigVal(map.get("configVal"))
                    .setGroupKey(map.get("groupKey"))
                    .setType(map.get("type"));

            // 便捷收银台时修改状态
            if (MchConfig.SELF_CASHIER_STATE.equals(mchConfig.getConfigKey())) {
                // 系统配置商户便捷收银台状态是否开启。如果开启便捷收银台配置，更新商户便捷收银台配置为开启
                DBDefaultConfig defaultConfig = configService.getDBDefaultConfig();
                if (defaultConfig != null && defaultConfig.getMchRegisterSelfCashierState() != null
                        && defaultConfig.getMchRegisterSelfCashierState() == CS.YES) {

                    // 开启默认配置
                    mchConfig.setConfigVal(MchConfig.YES);
                }
            }
            // WEB收银台时修改状态
            if (MchConfig.WEB_CASHIER_STATE.equals(mchConfig.getConfigKey())) {
                // 系统配置商户便捷收银台状态是否开启。如果开启便捷收银台配置，更新商户便捷收银台配置为开启
                DBDefaultConfig defaultConfig = configService.getDBDefaultConfig();
                if (defaultConfig != null && defaultConfig.getMchRegisterWebCashierState() != null
                        && defaultConfig.getMchRegisterWebCashierState() == CS.YES) {

                    // 开启默认配置
                    mchConfig.setConfigVal(MchConfig.YES);
                }
            }

            // 会员模块开关
            if (MchConfig.SELF_MEMBER_MODEL_STATE.equals(mchConfig.getConfigKey())) {
                // 系统配置商户便捷收银台状态是否开启。如果开启便捷收银台配置，更新商户便捷收银台配置为开启
                DBDefaultConfig defaultConfig = configService.getDBDefaultConfig();
                if (defaultConfig != null && defaultConfig.getMchRegisterMemberState() != null
                        && defaultConfig.getMchRegisterMemberState() != CS.YES) {

                    // 关闭默认配置
                    mchConfig.setConfigVal(MchConfig.NO);
                }
            }
            // 会员支付开关
//            if (MchConfig.SELF_MEMBER_PAY_STATE.equals(mchConfig.getConfigKey())) {
//                // 系统配置商户便捷收银台状态是否开启。如果开启便捷收银台配置，更新商户便捷收银台配置为开启
//                DBDefaultConfig defaultConfig = configService.getDBDefaultConfig();
//                if (defaultConfig != null && defaultConfig.getMchRegisterMemberState() != null
//                        && defaultConfig.getMchRegisterMemberState() != CS.YES) {
//
//                    // 关闭默认配置
//                    mchConfig.setConfigVal(MchConfig.NO);
//                }
//            }
            // 会员充值自定义金额开关
//            if (MchConfig.SELF_MEMBER_CUSTOM_AMOUNT_STATE.equals(mchConfig.getConfigKey())) {
//                // 系统配置商户便捷收银台状态是否开启。如果开启便捷收银台配置，更新商户便捷收银台配置为开启
//                DBDefaultConfig defaultConfig = configService.getDBDefaultConfig();
//                if (defaultConfig != null && defaultConfig.getMchRegisterMemberState() != null
//                        && defaultConfig.getMchRegisterMemberState() != CS.YES) {
//
//                    // 关闭默认配置
//                    mchConfig.setConfigVal(MchConfig.NO);
//                }
//            }

            list.add(mchConfig);
        }

        this.saveBatch(list);
    }

    /** 查询商户的分账规则配置 **/
    public MchDivisionConfig queryMchDivisionConfigByDefault(String mchNo){

        MchConfig mchConfig = getByMchNoAndConfigKey(mchNo, "divisionConfig");

        if(mchConfig != null && StringUtils.isNotBlank(mchConfig.getConfigVal())){
            return JSON.parseObject(mchConfig.getConfigVal(), MchDivisionConfig.class);
        }

        // 默认
        MchDivisionConfig result = new MchDivisionConfig();
        result.setOverrideAutoFlag(CS.NO); //默认不全局分账
        result.setMchDivisionEntFlag(CS.YES); //默认： 商户拥有分账管理权限

        // 默认分账规则
        MchDivisionConfig.AutoDivisionRule autoDivisionRule = new MchDivisionConfig.AutoDivisionRule();
        autoDivisionRule.setAmountLimit(0L);
        autoDivisionRule.setDelayTime(120);
        result.setAutoDivisionRules(autoDivisionRule);
        return result;

    }

    /** 查询商户通知类型， 默认 POST_BODY **/
    public String queryMchNotifyTypeConfigDefaultPOSTBody(String mchNo){

        MchConfig mchConfig = this.getByMchNoAndConfigKey(mchNo, "mchNotifyPostType");
        if(mchConfig != null &&
                (CS.NOTIFY_POST_TYPE.POST_QUERYSTRING.equals(mchConfig.getConfigVal()) ||
                 CS.NOTIFY_POST_TYPE.POST_BODY.equals(mchConfig.getConfigVal()) ||
                 CS.NOTIFY_POST_TYPE.POST_JSON.equals(mchConfig.getConfigVal()))
        ){
            return mchConfig.getConfigVal();
        }

        return CS.NOTIFY_POST_TYPE.POST_BODY; //默认 POST_BODY
    }


    /** 查询商户是否有该接口权限 **/
    public boolean queryMchHasApiEnt(String mchNo, String apiName){

        MchConfig mchConfig = this.getByMchNoAndConfigKey(mchNo, "mchApiEntList");
        if(mchConfig == null || StringUtils.isEmpty(mchConfig.getConfigVal())){
            return false; // 空表示 无权限
        }

        JSONArray array = JSON.parseArray(mchConfig.getConfigVal());
        return array.contains(apiName);
    }

    /** 查询商户是否有该接口权限 **/
    public boolean queryMchAppHasApiEnt(String mchNo, String mchAppId, String apiName){

        MchConfig mchConfig = this.get(mchNo, mchAppId, "mchApiEntList");
        if(mchConfig == null || StringUtils.isEmpty(mchConfig.getConfigVal())){
            return false; // 空表示 无权限
        }

        JSONArray array = JSON.parseArray(mchConfig.getConfigVal());
        return array.contains(apiName);
    }


    /** 查询配置：  自定义类型  **/
    public <T> T getConfigValByMchNoAndKey(String mchNo, String configKey, Class<T> cls) {

        MchConfig result = baseMapper.selectOne(MchConfig.gw().select(MchConfig::getConfigVal)
                .eq(MchConfig::getMchNo, mchNo)
                .eq(MchConfig::getConfigKey, configKey)
        );

        return result == null ? null : Convert.convert(cls, result.getConfigVal());
    }

    /** 查询配置：  返回String类型  **/
    public String getConfigValByMchNoAndKey(String mchNo, String configKey) {
        return getConfigValByMchNoAndKey(mchNo, configKey, String.class);
    }


    /** 查询商户收银台配置信息 （ 包括了默认配置项目 ） **/
    public CashierConfig queryMchCashierConfigByDefault(String mchNo, String groupKey){

        CashierConfig result = new CashierConfig();
        result.setState(CS.NO); // 默认关闭
        result.setSiteInfoType(CashierConfig.SELF_CASHIER_SITEINFO_TYPE_DEFAULT);  // 默认使用全局logo
        result.setWxH5PaywayList(Arrays.asList(CS.PAY_WAY_CODE.WX_H5)); // 默认使用微信H5支付方式
        result.setAliwapPaywayList(Arrays.asList(CS.PAY_WAY_CODE.ALI_WAP)); // 默认使用支付宝wap支付方式

        List<MchConfig> list = baseMapper.selectList(MchConfig.gw()
                .select(MchConfig::getConfigKey, MchConfig::getConfigVal)
                .eq(MchConfig::getMchNo, mchNo)
                .eq(MchConfig::getGroupKey, groupKey)
        );

        for (MchConfig mchConfig : list) {

            // 配置为空， 直接用默认值
            if(StringUtils.isEmpty(mchConfig.getConfigVal())){
                continue;
            }

            // 开关
            if(MchConfig.SELF_CASHIER_STATE.equals(mchConfig.getConfigKey()) || MchConfig.WEB_CASHIER_STATE.equals(mchConfig.getConfigKey()) ){
                result.setState(Byte.parseByte(mchConfig.getConfigVal()));
            }

            // logo
            if(MchConfig.SELF_CASHIER_SITEINFO_TYPE.equals(mchConfig.getConfigKey()) || MchConfig.WEB_CASHIER_SITEINFO_TYPE.equals(mchConfig.getConfigKey()) ){
                result.setSiteInfoType(mchConfig.getConfigVal());
            }

            // 微信配置
            if(MchConfig.SELF_CASHIER_WXH5_CONFIG.equals(mchConfig.getConfigKey()) || MchConfig.WEB_CASHIER_WXH5_CONFIG.equals(mchConfig.getConfigKey()) ){
                result.setWxH5PaywayList(JSON.parseArray(mchConfig.getConfigVal(), String.class));
            }

            // 支付宝配置
            if(MchConfig.SELF_CASHIER_ALIWAP_CONFIG.equals(mchConfig.getConfigKey()) || MchConfig.WEB_CASHIER_ALIWAP_CONFIG.equals(mchConfig.getConfigKey()) ){
                result.setAliwapPaywayList(JSON.parseArray(mchConfig.getConfigVal(), String.class));
            }

        }

        return result;
    }


}
