package com.jeequan.jeepay.mgr.ctrl.payconfig;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.components.mq.model.ResetIsvMchAppInfoConfigMQ;
import com.jeequan.jeepay.components.mq.vender.IMQSender;
import com.jeequan.jeepay.core.aop.MethodLog;
import com.jeequan.jeepay.core.constants.ApiCodeEnum;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.oauth2.Oauth2Params;
import com.jeequan.jeepay.core.utils.StringKit;
import com.jeequan.jeepay.db.entity.PayInterfaceConfig;
import com.jeequan.jeepay.db.entity.RateConfig;
import com.jeequan.jeepay.mgr.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.MchAppService;
import com.jeequan.jeepay.service.impl.PayInterfaceConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/***
 * oauth2配置
 *
 * @author terrfly
 *
 * @date 2022/11/9 17:01
 */
@RestController
@RequestMapping("/api/payOauth2Config")
public class PayOauth2ConfigController extends CommonCtrl {

    @Autowired
    private MchAppService mchAppService;
    @Autowired
    private PayInterfaceConfigService payInterfaceConfigService;
    @Autowired
    private IMQSender mqSender;


    /**
     * 查询已经配置的参数信息
     **/
    @GetMapping(value = "/savedConfigs")
    public ApiRes interfaceSavedConfigs() {

        String ifCode = getValStringRequired("ifCode"); // ifCode
        String infoId = getValStringRequired("infoId"); // infoId
        String configMode = getValStringRequired("configMode"); // 设置类型

        String infoType = null;

        // 运营平台 配置服务商信息  --》
        if (RateConfig.CONFIG_MODE_MGRISV.equals(configMode)) {
            infoType = CS.SYS_ROLE_TYPE.ISV_OAUTH2;

        } else // 运营平台 配置商户应用信息

            if (RateConfig.CONFIG_MODE_MGRMCH.equals(configMode)) {
                infoType = CS.SYS_ROLE_TYPE.MCH_APP_OAUTH2;
            }

        // 查询已经配置的信息
        PayInterfaceConfig payInterfaceConfig = payInterfaceConfigService.getByInfoIdAndIfCode(infoType, infoId, ifCode);

        if (payInterfaceConfig == null) {
            payInterfaceConfig = new PayInterfaceConfig();
        }

        // 处理脱敏数据
        if (StringUtils.isNotEmpty(payInterfaceConfig.getIfParams())) {
            Oauth2Params isvParams = Oauth2Params.factory(ifCode, payInterfaceConfig.getIfParams());
            if (isvParams != null) {
                payInterfaceConfig.setIfParams(isvParams.deSenData());
            }
        }
        return ApiRes.ok(payInterfaceConfig);
    }


    /**
     * 更新支付参数
     **/
    @PostMapping("/configParams")
    @MethodLog(remark = "更新oauth2参数")
    public ApiRes saveOrUpdate() {

        PayInterfaceConfig payInterfaceConfig = getObject(PayInterfaceConfig.class);

        String configMode = payInterfaceConfig.extv().getString("configMode");  // 设置类型

        String infoType = null;

        // 运营平台 配置服务商信息  --》
        if (RateConfig.CONFIG_MODE_MGRISV.equals(configMode)) {
            infoType = CS.SYS_ROLE_TYPE.ISV_OAUTH2;

        } else // 运营平台 配置商户应用
            if (RateConfig.CONFIG_MODE_MGRMCH.equals(configMode)) {
                infoType = CS.SYS_ROLE_TYPE.MCH_APP_OAUTH2;
            }

        payInterfaceConfig.setInfoType(infoType);

        //添加更新者信息
        Long userId = getCurrentUser().getSysUser().getSysUserId();
        String realName = getCurrentUser().getSysUser().getRealname();
        payInterfaceConfig.setUpdatedUid(userId);
        payInterfaceConfig.setUpdatedBy(realName);

        //根据 服务商号、接口类型 获取商户参数配置
        PayInterfaceConfig dbRecord = payInterfaceConfigService.getByInfoIdAndIfCode(payInterfaceConfig.getInfoType(), payInterfaceConfig.getInfoId(), payInterfaceConfig.getIfCode());
        //若配置存在，为saveOrUpdate添加ID，第一次配置添加创建者
        if (dbRecord != null) {
            payInterfaceConfig.setId(dbRecord.getId());

            // 合并支付参数
            payInterfaceConfig.setIfParams(StringKit.marge(dbRecord.getIfParams(), payInterfaceConfig.getIfParams(), dbRecord.getIfCode()));
        } else {
            payInterfaceConfig.setCreatedUid(userId);
            payInterfaceConfig.setCreatedBy(realName);
        }

        boolean result = payInterfaceConfigService.saveOrUpdate(payInterfaceConfig);
        if (!result) {
            return ApiRes.fail(ApiCodeEnum.SYSTEM_ERROR, "配置失败");
        }


        // 推送mq到目前节点进行更新数据

        // 运营平台 配置服务商信息  --》
        if (RateConfig.CONFIG_MODE_MGRISV.equals(configMode)) {

            // 获取到原始 isvId
            String infoId = payInterfaceConfig.getInfoId();
            if (infoId.indexOf("_LIST_") > 0) {
                infoId = infoId.split("_LIST_")[0];
            }

            mqSender.send(ResetIsvMchAppInfoConfigMQ.build(ResetIsvMchAppInfoConfigMQ.RESET_TYPE_ISV_INFO, infoId, null, null));
        }

        return ApiRes.ok();
    }


    /**
     * 查询oauth2列表 diyList
     **/
    @GetMapping(value = "/diyList")
    public ApiRes diyList() {

        String infoId = getValStringRequired("infoId"); // infoId
        String configMode = getValStringRequired("configMode"); // 设置类型

        String infoType = null;

        // 运营平台 配置服务商信息  --》 ( oauth2页面 只支持该类型)
        if (RateConfig.CONFIG_MODE_MGRISV.equals(configMode)) {
            infoType = CS.SYS_ROLE_TYPE.ISV_OAUTH2;
        }

        // 示例： V1650963022_LIST_20220109105300
        String infoIdLike = infoId + "_LIST_";

        List<PayInterfaceConfig> result =
                payInterfaceConfigService.list(PayInterfaceConfig.gw()
                        .select(PayInterfaceConfig::getId, PayInterfaceConfig::getInfoId, PayInterfaceConfig::getRemark)
                        .like(PayInterfaceConfig::getInfoId, infoIdLike).eq(PayInterfaceConfig::getInfoType, infoType));

        // infoId - remark(名称)  （作用： 去重）
        Map<String, String> nameMap = new HashMap<>();
        for (PayInterfaceConfig payInterfaceConfig : result) {
            if (StringUtils.isNotBlank(payInterfaceConfig.getRemark())) {
                nameMap.put(payInterfaceConfig.getInfoId(), payInterfaceConfig.getRemark());
            }
        }

        // 改为最终的返回结果
        List<PayInterfaceConfig> apiResult = new ArrayList<>();
        for (String s : nameMap.keySet()) {
            PayInterfaceConfig p = new PayInterfaceConfig();
            p.setInfoId(s);
            p.setRemark(nameMap.get(s));
            apiResult.add(p);
        }

        return ApiRes.ok(apiResult);
    }


    /**
     * 新增一个
     **/
    @PostMapping(value = "/diyList")
    public ApiRes diyListAdd() {

        String infoId = getValStringRequired("infoId"); // infoId
        String configMode = getValStringRequired("configMode"); // 设置类型
        String remark = getValStringRequired("remark"); // 名称


        // 示例： V1650963022_LIST_20220109105300
        String infoIdAddId = infoId + "_LIST_" + DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN);

        String infoType = null;

        // 运营平台 配置服务商信息  --》 (只支持该类型)
        if (RateConfig.CONFIG_MODE_MGRISV.equals(configMode)) {
            infoType = CS.SYS_ROLE_TYPE.ISV_OAUTH2;
        }

        if (payInterfaceConfigService.count(PayInterfaceConfig.gw().eq(PayInterfaceConfig::getInfoId, infoIdAddId).eq(PayInterfaceConfig::getInfoType, infoType)) > 0) {
            throw new BizException(infoIdAddId + "已存在, 不能重复添加");
        }

        PayInterfaceConfig payInterfaceConfig = new PayInterfaceConfig();
        payInterfaceConfig.setInfoType(infoType);
        payInterfaceConfig.setInfoId(infoIdAddId);
        payInterfaceConfig.setIfCode(CS.IF_CODE.WXPAY);
        payInterfaceConfig.setIfParams(new JSONObject().toJSONString());
        payInterfaceConfig.setState(CS.YES);
        payInterfaceConfig.setRemark(remark);
        payInterfaceConfig.setCreatedUid(getCurrentUser().getSysUserId());
        payInterfaceConfig.setCreatedBy(getCurrentUser().getSysUser().getRealname());
        payInterfaceConfigService.save(payInterfaceConfig);

        return ApiRes.ok();
    }

}
