package com.jeequan.jeepay.mch.ctrl.merchant;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.DBDefaultConfig;
import com.jeequan.jeepay.db.entity.MchConfig;
import com.jeequan.jeepay.db.entity.MchInfo;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.service.impl.MchConfigService;
import com.jeequan.jeepay.service.impl.MchInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商户配置管理类
 *
 * @author zx
 *
 * @date 2021-06-16 09:15
 */
@RestController
@RequestMapping("/api/mchConfig")
public class MchConfigController extends CommonCtrl {

    @Autowired private MchConfigService mchConfigService;
    @Autowired private MchInfoService mchInfoService;

    /**
     * @Author: zx
     * @Description: 查询商户配置
     * @Date: 9:59 2021/6/16
    */
    @GetMapping
    public ApiRes list() {

        String groupKey = getValString("groupKey");

        String mchNo = getCurrentMchNo();
        String mchAppId = getValString("mchAppId");
        String mchApplyId = getValString("mchApplyId");

        LambdaQueryWrapper<MchConfig> queryWrapper = MchConfig.gw()
                .eq(MchConfig::getMchNo, mchNo)
                .eq(!ObjUtil.isEmpty(mchAppId), MchConfig::getMchAppId, mchAppId)
                .eq(!ObjUtil.isEmpty(mchApplyId), MchConfig::getMchApplyId, mchApplyId);

        List<MchConfig> list = mchConfigService.list(queryWrapper);
        return ApiRes.ok(list);
    }

    /**
     * @Author: zx
     * @Description: 根据configKey查询商户配置
     * @Date: 9:59 2021/6/16
     */
    @GetMapping("/{configKey}")
    public ApiRes get(@PathVariable("configKey") String configKey) {

        MchConfig mchConfig = mchConfigService.getOne(MchConfig.gw().eq(MchConfig::getMchNo, getCurrentMchNo()).eq(MchConfig::getConfigKey, configKey));
        return ApiRes.ok(mchConfig);
    }

    /**
     * @Author: zx
     * @Description: 根据configKey更新商户配置信息
     * @Date: 10:11 2021/6/16
    */
    @PreAuthorize("hasAuthority('ENT_MCH_CONFIG_EDIT')")
    @MethodLog(remark = "更新商户配置")
    @PutMapping("/updateById/{configKey}")
    public ApiRes updateByConfigKey(@PathVariable("configKey") String configKey) {
        MchConfig mchConfig = getObject(MchConfig.class);
        mchConfig.setConfigKey(configKey);
        mchConfig.setMchNo(getCurrentMchNo());

        if (MchConfig.NOT_ALLOW_MCH_EDIT.contains(configKey)) {
            return ApiRes.fail(ApiCodeEnum.SYS_PERMISSION_ERROR);
        }

        int count = mchConfigService.saveOrUpdateConfig(mchConfig);
        if(count <= 0) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_UPDATE);
        }
        return ApiRes.ok();
    }

    /**
     * @author: zx
     * @Description: 批量更新商户配置信息
     * @Date: 10:11 2021/6/16
     */
    @PreAuthorize("hasAuthority('ENT_MCH_CONFIG_EDIT')")
    @MethodLog(remark = "批量更新商户配置信息")
    @PutMapping("/{groupKey}")
    public ApiRes updateBatch(@PathVariable("groupKey") String groupKey) {

        String params = getValStringRequired("configData");

        List<MchConfig> mchConfigList = JSONArray.parseArray(params, MchConfig.class);

        mchConfigList.removeIf(mchConfig -> MchConfig.NOT_ALLOW_MCH_EDIT.contains(mchConfig.getConfigKey()));

        String mchNo = getValStringRequired("mchNo");
        String mchAppId = getValString("mchAppId");
        String mchApplyId = getValString("mchApplyId");

        int update = mchConfigService.updateBatch(mchConfigList, mchNo, mchAppId, mchApplyId, groupKey);
        if(update <= 0) {
            return ApiRes.fail(ApiCodeEnum.SYS_OPERATION_FAIL_UPDATE);
        }

        return ApiRes.ok();
    }


    @MethodLog(remark = "更改商户级别")
    @PutMapping("/mchLevel")
    public ApiRes updateMchLevel() {

        String mchLevel = getValStringRequired("mchLevel");

        MchInfo mchInfo = new MchInfo();
        mchInfo.setMchNo(getCurrentMchNo());
        mchInfo.setMchLevel(mchLevel);

        mchInfoService.updateById(mchInfo);
        return ApiRes.ok();
    }

    @MethodLog(remark = "更改支付密码")
    @PutMapping("/mchSipw")
    public ApiRes updateMchSipw() {

        String confirmPwd = Base64.decodeStr(getValStringRequired("confirmPwd"));

        // 验证原密码
        MchInfo dbMchInfo = mchInfoService.getById(getCurrentMchNo());
        if(StringUtils.isNotEmpty(dbMchInfo.getSipw())){
            //当前旧密码
            String originalPwd = Base64.decodeStr(getValStringRequired("originalPwd"));
            if(!new BCryptPasswordEncoder().matches(originalPwd, dbMchInfo.getSipw())){
                throw new BizException("原支付验证失败！");
            }
        }

        MchInfo mchInfo = new MchInfo();
        mchInfo.setMchNo(getCurrentMchNo());
        mchInfo.setSipw(new BCryptPasswordEncoder().encode(confirmPwd));
        mchInfoService.updateById(mchInfo);
        return ApiRes.ok();
    }



    /** 是否设置了支付密码 **/
    @GetMapping("/hasSipwValidate")
    public ApiRes hasSipwValidate() {

        MchInfo dbMchInfo = mchInfoService.getById(getCurrentMchNo());
        if(StringUtils.isNotEmpty(dbMchInfo.getSipw())){
            return ApiRes.ok(true);
        }
        return ApiRes.ok(false);
    }

    /** 验证支付密码是否正确 **/
    @PostMapping("/mchSipwValidate")
    public ApiRes mchSipwValidate() {

        //当前旧密码
        String originalPwd = Base64.decodeStr(getValStringRequired("originalPwd"));

        // 验证原密码
        MchInfo dbMchInfo = mchInfoService.getById(getCurrentMchNo());
        if(StringUtils.isNotEmpty(dbMchInfo.getSipw())){
            if(!new BCryptPasswordEncoder().matches(originalPwd, dbMchInfo.getSipw())){
                return ApiRes.ok(false);
            }
        }

        return ApiRes.ok(true);
    }

    /** 会员最大储值余额 **/
    @GetMapping("/mbrMaxBalance")
    public ApiRes getMbrMaxBalance() {

        MchConfig mbrMaxBalanceConfig = mchConfigService.getByMchNoAndConfigKey(getCurrentMchNo(), MchConfig.SELF_MEMBER_MAX_BALANCE);
        if (mbrMaxBalanceConfig != null && StringUtils.isNotBlank(mbrMaxBalanceConfig.getConfigVal()) && !MchConfig.NO.equals(mbrMaxBalanceConfig.getConfigVal())) {
            return ApiRes.ok(mbrMaxBalanceConfig.getConfigVal());
        }

        DBDefaultConfig defaultConfig = sysConfigService.getDBDefaultConfig();
        if (defaultConfig != null && defaultConfig.getMchMbrMaxBalance() != null && defaultConfig.getMchMbrMaxBalance() != 0L) {
            return ApiRes.ok(defaultConfig.getMchMbrMaxBalance());
        }

        return ApiRes.ok(CS.NO);
    }


}
