package com.cpop.pay.framewok.handler.wxPay;

import com.alibaba.fastjson.JSONObject;
import com.cpop.common.utils.ServletUtils;
import com.cpop.common.utils.StringUtils;
import com.cpop.core.base.exception.ServiceException;
import com.cpop.core.utils.SecurityUtils;
import com.cpop.core.utils.SpringUtils;
import com.cpop.pay.framewok.config.wxPay.WxPayConfiguration;
import com.github.binarywang.wxpay.bean.ecommerce.SignatureHeader;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.service.WxPayService;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author DB
 * @createTime 2023/10/27 15:47
 * @description
 */
@Component
@Slf4j
public class WxPayHandler {

    @Autowired
    private WxPayService wxPayService;

    /**
     * @descriptions 获取微信支付service
     * @author DB
     * @date 2023/10/27 15:53
     * @return: com.github.binarywang.wxpay.service.WxPayService
     */
    public WxPayService getWxPayService(){
        //查询当前登陆用户所在品牌的商户id
        JSONObject loginUserInfo = SecurityUtils.getInstance().getLoginUserInfo();
        if (loginUserInfo == null) {
            //直接返回
            return wxPayService;
        }
        String brandId = loginUserInfo.getString("brandId");
        Row brand = Db.selectOneByQuery("cp_sys_brand", QueryWrapper.create().where("id = ?", brandId));
        if (brand.isEmpty() || StringUtils.isBlank(brand.getString("wxMchId"))) {
            throw new ServiceException("当前品牌暂未开通微信支付,请联系相关客服");
        }
        //检查是否开启分账
        if (!brand.getBoolean("isOpenSharing")) {
            throw new ServiceException("当前商户暂未开启分账,请联系相关客服");
        }
        WxPayConfig payConfig = wxPayService.getConfig();
        //子商户信息
        payConfig.setSubMchId(StringUtils.trimToNull(brand.getString("wxMchId")));
        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }

    /**
     * @descriptions 根据商户appid或商户号获取对应微信支付接口
     * @author DB
     * @date 2023/10/18 10:34
     * @param subAppId 子商户appid
     * @param subMchId 子商户id
     * @return: com.github.binarywang.wxpay.service.WxPayService
     */
    public WxPayService getWxPayService(String subAppId, String subMchId) {
        WxPayConfig payConfig = wxPayService.getConfig();
        //子商户信息
        payConfig.setSubAppId(StringUtils.trimToNull(subAppId));
        payConfig.setSubMchId(StringUtils.trimToNull(subMchId));
        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }

    /**
     * 根据商户appid或商户号获取对应微信支付接口
     * @author DB
     * @since 2023/10/18 10:34
     * @param subAppId 子商户appid
     * @param subMchId 子商户id
     * @param notifyUrl 通知地址
     * @return com.github.binarywang.wxpay.service.WxPayService
     */
    public WxPayService getWxPayService(String subAppId, String subMchId, String notifyUrl) {
        WxPayConfig payConfig = wxPayService.getConfig();
        //子商户信息
        payConfig.setSubAppId(StringUtils.trimToNull(subAppId));
        payConfig.setSubMchId(StringUtils.trimToNull(subMchId));
        payConfig.setNotifyUrl(notifyUrl);
        // 可以指定是否使用沙箱环境
        payConfig.setUseSandboxEnv(false);
        wxPayService.setConfig(payConfig);
        return wxPayService;
    }

    /**
     * 获取子商户
     * @author DB
     * @since 2023/12/21
     * @param brandId 品牌id
     * @param storeId 校区id
     * @return String
     */
    public String getSubMchId(String brandId, String storeId) {
        String wxMchId;
        if (StringUtils.isNotEmpty(storeId)){
            //先查校区
            Row store = Db.selectOneByQuery("cp_sys_store", QueryWrapper.create().where("id = ?", storeId));
            if (store != null && StringUtils.isNotBlank(store.getString("wxMchId"))){
                wxMchId = store.getString("wxMchId");
            } else {
                //查询品牌
                Row brand = Db.selectOneByQuery("cp_sys_brand", QueryWrapper.create().where("id = ?", brandId));
                if (brand != null && StringUtils.isNotBlank(brand.getString("wxMchId"))){
                    wxMchId = brand.getString("wxMchId");
                }else {
                    wxMchId = null;
                }
            }
        } else {
            //查询品牌
            Row brand = Db.selectOneByQuery("cp_sys_brand", QueryWrapper.create().where("id = ?", brandId));
            if (brand != null && StringUtils.isNotBlank(brand.getString("wxMchId"))){
                wxMchId = brand.getString("wxMchId");
            }else {
                wxMchId = null;
            }
        }
        return wxMchId;
    }

    /**
     * 获取签约头
     * @author DB
     * @since 2024/1/20
     * @return SignatureHeader
     */
    public SignatureHeader getSignatureHeader() {
        HttpServletRequest request = ServletUtils.getRequest();
        SignatureHeader signatureHeader = new SignatureHeader();
        signatureHeader.setSigned(request.getHeader("Wechatpay-Signature"));
        signatureHeader.setNonce(request.getHeader("Wechatpay-Nonce"));
        signatureHeader.setSerialNo(request.getHeader("Wechatpay-Serial"));
        signatureHeader.setTimeStamp(request.getHeader("Wechatpay-Timestamp"));
        log.info("微信支付分回调ID:{}",request.getHeader("Request-ID"));
        return signatureHeader;
    }

}
