package com.yonge.cooleshow.biz.dal.sdk;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.huifu.adapay.model.Payment;
import com.huifu.adapay.model.PaymentConfirm;
import com.yonge.cooleshow.biz.dal.config.HuifuConfiguration;
import com.yonge.cooleshow.biz.dal.sdk.req.PaymentReq;
import com.yonge.cooleshow.biz.dal.service.impl.ImGroupMemberServiceImpl;
import com.yonge.cooleshow.common.constant.CommonConstants;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.exception.BizException;
import com.yonge.toolset.base.exception.ThirdpartyException;
import com.yonge.toolset.utils.collection.MapUtil;
import com.yonge.toolset.utils.http.HttpUtil;
import com.yonge.toolset.utils.string.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Component
public class PaymentSdk {
    private final static Logger log = LoggerFactory.getLogger(PaymentSdk.class);

    /**
     * 执行一个支付交易
     *
     * @return 创建的支付对象
     * @throws Exception 异常
     */
    public HttpResponseResult<Map<String, Object>> executePayment(PaymentReq paymentReq) {
        paymentReq.setApp_id(HuifuConfiguration.getHuifuProperties().getAppId());
        //创建分账对象
        Map<String, String> div_member = new HashMap<>();
        div_member.put("member_id", "0");
        div_member.put("amount", paymentReq.getPay_amt());
        div_member.put("fee_flag", "Y");
        List<Map<String, String>> div_members = Arrays.asList(div_member);
        paymentReq.setDiv_members(JSONObject.toJSONString(div_members));

        log.info("汇付[创建支付对象] Req：{}", JSONObject.toJSONString(paymentReq));
        //调用sdk方法，创建支付，得到支付对象
        Map<String, Object> paymentParams = MapUtil.populateMap(new HashMap<>(), paymentReq);
        Map<String, Object> res;
        try {
            res = Payment.create(paymentParams);
        } catch (BaseAdaPayException e) {
            return HttpResponseResult.failed(e.getMessage());
        }
        if (CollectionUtils.isEmpty(res)) {
            return HttpResponseResult.failed("请求失败");
        }
        log.info("汇付[创建支付对象] Resp：{}", res);
        String errorCode = (String) res.get("error_code");
        if (null != errorCode) {
            String errorMsg = (String) res.get("error_msg");
            return HttpResponseResult.failed(errorMsg);
        }
        return HttpResponseResult.succeed(res);
    }

    /**
     * 创建确认对象
     * 创建支付确认对象适用于延时分账的场景
     *
     * @return 查询的支付对象
     * @throws Exception 异常
     */
    public Map<String, Object> createConfirm(Map<String, Object> confirm) throws Exception {
        confirm = PaymentConfirm.create(confirm);

        String error_code = (String) confirm.get("error_code");
        if (null != error_code) {
            String errorMsg = (String) confirm.get("error_msg");
            throw new ThirdpartyException(errorMsg);
        }
        return confirm;
    }

    /**
     * 关闭一个支付交易
     *
     * @param paymentId 要关闭的支付id
     * @return 关闭的支付对象
     * @throws Exception 异常
     */
    public HttpResponseResult<Map<String, Object>> closePayment(String paymentId, String reason, String expend) {
        Map<String, Object> paymentParams = new HashMap<>(10);
        paymentParams.put("payment_id", paymentId);
        paymentParams.put("reason", reason);
        paymentParams.put("expend", expend);
        paymentParams.put("notify_url", HuifuConfiguration.getHuifuProperties().getNotifyUrl());

        Map<String, Object> res;
        try {
            res = Payment.close(paymentParams);
        } catch (BaseAdaPayException e) {
            return HttpResponseResult.failed(e.getMessage());
        }
        if (CollectionUtils.isEmpty(res)) {
            return HttpResponseResult.failed("请求失败");
        }
        log.info("汇付[创建支付对象] Resp：{}", res);
        String errorCode = (String) res.get("error_code");
        if (null != errorCode) {
            String errorMsg = (String) res.get("error_msg");
            return HttpResponseResult.failed(errorMsg);
        }
        return HttpResponseResult.succeed(res);
    }

    /**
     * 查询一个支付交易
     *
     * @param paymentId 要查询的支付id
     * @return 查询的支付对象
     * @throws Exception 异常
     */
    public Map<String, Object> queryPayment(String paymentId) throws Exception {
        System.out.println("=======query payment begin=======");
        //查询支付对象的参数，全部参数请参考 https://docs.adapay.tech/api/04-trade.html#id7
        //调用sdk方法，查询支付交易，得到支付对象
        Map<String, Object> payment = new HashMap<>();
        try {
            System.out.println("支付查询请求参数：" + JSON.toJSONString(paymentId));
            payment = com.huifu.adapay.model.Payment.query(paymentId);
        } catch (ThirdpartyException e) {
            e.printStackTrace();
        }

        System.out.println("支付查询返回参数：" + JSON.toJSONString(payment));

        String error_code = (String) payment.get("error_code");
        if (null != error_code) {
            String error_msg = (String) payment.get("error_msg");
            System.out.println("error_code:" + error_code + "............." + error_msg);
        }
        System.out.println("=======query payment end=======");
        return payment;
    }

    /***
     * 获取openId
     * @author liweifan
     * @param: js_code
     * @updateTime 2022/4/8 15:49
     * @return: java.lang.Object
     */
    public HttpResponseResult<Map<String, String>> getOpenId(String js_code) {
        log.info("微信[获取用户openId] Req：{}", js_code);
        Map<String, Object> param = new HashMap<>();
        param.put("appid", HuifuConfiguration.getHuifuProperties().getWxAppid());
        param.put("secret", HuifuConfiguration.getHuifuProperties().getWxSecret());
        param.put("js_code", js_code);
        param.put("grant_type", CommonConstants.WECHAT_GRANT_TYPE);

        try {
            String res = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session", param);
            JSONObject jsonObject = JSONObject.parseObject(res);
            log.info("微信[获取用户openId] Res：{}", jsonObject.toJSONString());
            String errcode = jsonObject.getString("errcode");
            if (StringUtil.isEmpty(errcode) || "0".equals(errcode)) {
                Map<String, String> resMap = new HashMap<>();
                resMap.put("openid", jsonObject.getString("openid"));
                resMap.put("session_key", jsonObject.getString("session_key"));
                return HttpResponseResult.succeed(resMap);
            } else {
                return HttpResponseResult.failed(jsonObject.getString("errmsg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return HttpResponseResult.failed("请求失败");
        }
    }

/*
    public static Map<String, Object> queryList(Integer pageIndex, Long createdGte, Long createdLte) throws Exception {
        Map<String, Object> paymentParams = new HashMap<>();
        paymentParams.put("app_id", ConfigInit.appId);
        paymentParams.put("page_index", pageIndex);
        paymentParams.put("page_size", "20");
        paymentParams.put("created_gte", createdGte);
        paymentParams.put("created_lte", createdLte);
        Map<String, Object> payment = com.huifu.adapay.model.Payment.queryList(paymentParams);
        String error_code = (String) payment.get("error_code");
        if (null != error_code) {
            String errorMsg = (String) payment.get("error_msg");
            throw new ThirdpartyException(errorMsg);
        }
        return payment;
    }

    public static Map<String, Object> queryConfirmList(String paymentId) throws Exception {
        Map<String, Object> paymentParams = new HashMap<>();
        paymentParams.put("app_id", ConfigInit.appId);
        paymentParams.put("payment_id", paymentId);

        Map<String, Object> payment = com.huifu.adapay.model.Payment.queryConfirmList(paymentParams);
        String error_code = (String) payment.get("error_code");
        if (null != error_code) {
            String errorMsg = (String) payment.get("error_msg");
            throw new ThirdpartyException(errorMsg);
        }
        return payment;
    }


    public static Map<String, Object> getPayMap(BigDecimal amount, String orderNo, String notifyUrl, String returnUrl, String orderSubject, String orderBody) throws Exception {
        Map<String, Object> paymentParams = new LinkedHashMap<>();
        paymentParams.put("appId", ConfigInit.appId);
        paymentParams.put("amount", amount.setScale(2, BigDecimal.ROUND_HALF_UP));
        paymentParams.put("orderNo", orderNo);
//        paymentParams.put("notifyUrl", notifyUrl);
//        paymentParams.put("returnUrl", returnUrl);
        paymentParams.put("orderSubject", orderSubject);
        paymentParams.put("orderBody", orderBody);
        paymentParams.put("wxAppId", ConfigInit.wxAppId);

        String originalStr = JSONObject.toJSONString(paymentParams);
        String sign = DigestUtils.md5DigestAsHex(originalStr.getBytes());

        paymentParams.put("sign", sign);
        paymentParams.remove("appId");
        return paymentParams;
    }*/
}
