package com.sqx.modules.pay.wuyou;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.pay.dao.CashOutDao;
import com.sqx.modules.pay.entity.WithdrawTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author GYJ
 */
@Service
public class WuyouPay {

    @Value("${pay.orderNotifyUrl}")
    private String notifyUrl = "";
    @Value("${pay.extractNotifyUrl}")
    private String extractNotifyUrl = "";
    @Value("${pay.h5BaseUrl}")
    private String h5BaseUrl = "";

    private final CashOutDao cashOutDao;
    private final CommonInfoService commonInfoService;


    private static final Logger logger = LoggerFactory.getLogger(WuyouPay.class);

    public WuyouPay(CashOutDao cashOutDao, CommonInfoService commonInfoService) {
        this.cashOutDao = cashOutDao;
        this.commonInfoService = commonInfoService;
    }

    public BaseResp payOrder(String orderNo, String amount, String userAgent, String allId, String payType) {
        String payConfig = commonInfoService.findOne(926).getValue();
        if (!"1".equals(payConfig)) {
            BaseResp baseResp = new BaseResp();
            baseResp.setErrorMsg("暂无支付渠道");
            return baseResp;
        }
        Map<String, Object> params = getBaseParams();
        params.put("type", "6001");
        params.put("is_code", "1");
        params.put("out_trade_no", orderNo);
        params.put("total", amount);
        params.put("notify_url", notifyUrl);

        String sign = Encrypt.getParamsSign(params);
        params.put("sign", sign);
        if ("h5".equals(payType)) {
            params.put("return_url", h5BaseUrl + allId);
        }

        // https://dj-h5.hnsiyao.cn/me/detail/detail?allId=1230-98688

        String body = request(Constants.PAY_URL, params, userAgent);

        return JSONObject.parseObject(body, BaseResp.class);
    }

    public BaseResp queryOrder(String orderNo, String amount, String userAgent) {
        Map<String, Object> params = getBaseParams();
        params.put("out_trade_no", orderNo);
        params.put("total", amount);

        String sign = Encrypt.getParamsSign(params);
        params.put("sign", sign);

        String body = request(Constants.QUERY_URL, params, userAgent);
        return JSONObject.parseObject(body, BaseResp.class);
    }

    public boolean checkCanCash(long userId, WithdrawTypeEnum type, BigDecimal money) {
        if (WithdrawTypeEnum.MANUAL.equals(type)) {
            // 查询当日体现次数
            Integer successCashCount = cashOutDao.selectTodayCashCount(userId, 1, DateUtil.today() + " 00:00:00");
            CommonInfo cashLimit = commonInfoService.findOne(922);
            if (cashLimit == null || StrUtil.isBlank(cashLimit.getValue())) {
                logger.warn("提现必要参数未配置，请联系管理员");
                return false;
            }

            if (successCashCount >= Integer.parseInt(cashLimit.getValue())) {
                logger.warn("体现次数超限，当前限制{}次, 已经体现{}次", cashLimit.getValue(), successCashCount);
                return false;

            }
            return checkCanCashByLimit(money);
        }
        return true;
    }

    public boolean checkCanCashByLimit(BigDecimal money) {
        CommonInfo info = commonInfoService.findOne(923);
        if (info == null || StrUtil.isBlank(info.getValue())) {
            logger.warn("未配置提现限制，请联系管理员配置");
            return false;
        }

        return money.compareTo(new BigDecimal(info.getValue())) <= 0;
    }

    /**
     * 提现
     *
     * @param account  支付宝账号
     * @param userName 支付宝名称
     */
    public BaseResp extractOrder(String outOrderNo, String amount, String account, String userName) {
        String payConfig = commonInfoService.findOne(927).getValue();
        if (!"1".equals(payConfig)) {
            BaseResp baseResp = new BaseResp();
            baseResp.setErrorMsg("暂无提现渠道");
            return baseResp;
        }
        Map<String, Object> params = getBaseParams();

        params.put("out_trade_no", outOrderNo);
        params.put("total", amount);
        params.put("bank_card", account);
        params.put("bank_account_name", userName);
        params.put("bank_name", "1");
        params.put("bank_branch", "1");
        params.put("province", "1");
        params.put("city", "1");
        params.put("notify_url", extractNotifyUrl);

        String sign = Encrypt.getParamsSign(params);
        params.put("sign", sign);

        params.put("business_type", 0);
        params.put("business_attr", "alipay");

        String body = request(Constants.EXTRACT_URL, params, "");
        return JSONObject.parseObject(body, BaseResp.class);
    }

    /**
     * 提现，人工审核使用，不收配置开关限制，直接提现
     *
     * @param account  支付宝账号
     * @param userName 支付宝名称
     */
    public BaseResp extractOrderForAudit(String outOrderNo, String amount, String account, String userName) {
        Map<String, Object> params = getBaseParams();

        params.put("out_trade_no", outOrderNo);
        params.put("total", amount);
        params.put("bank_card", account);
        params.put("bank_account_name", userName);
        params.put("bank_name", "1");
        params.put("bank_branch", "1");
        params.put("province", "1");
        params.put("city", "1");
        params.put("notify_url", extractNotifyUrl);

        String sign = Encrypt.getParamsSign(params);
        params.put("sign", sign);

        params.put("business_type", 0);
        params.put("business_attr", "alipay");

        String body = request(Constants.EXTRACT_URL, params, "");
        return JSONObject.parseObject(body, BaseResp.class);
    }

    public BaseResp queryExtractOrder(String outOrderNo, String amount) {
        Map<String, Object> params = getBaseParams();
        params.put("out_trade_no", outOrderNo);
        params.put("total", amount);

        String sign = Encrypt.getParamsSign(params);
        params.put("sign", sign);

        String body = request(Constants.EXTRACT_QUERY_URL, params, "");
        return JSONObject.parseObject(body, BaseResp.class);
    }

    private Map<String, Object> getBaseParams() {
        Map<String, Object> params = new HashMap<>();
        params.put("mch_id", Constants.MERCHANT_ID);
        params.put("timestamp", System.currentTimeMillis() / 1000);

        return params;
    }

    private String request(String url, Map<String, Object> params, String userAgent) {
        String body = HttpRequest.post(url)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .header("User-Agent", userAgent)
                .body(JSONObject.toJSONString(params))
                .execute()
                .body();

        logger.info("无忧支付 request url: {}, params: {}, response: {}", url, params, body);

        return body;
    }

    public static void main(String[] args) {
//        payOrder("20221118123456794", "0.1", "Mozilla/5.0", "1230-98688", "h5");
//        queryOrder("20221118123456791", "0.1", "Mozilla/5.0");

//        extractOrder("20221118123456793", "1", "1157756119@qq.com", "巩奕杰");
//        queryExtractOrder("20221118123456793", "1");

        System.out.println(DateUtil.today() + " 00:00:00");
    }
}
