package com.gree.mall.manager.logic.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.gree.mall.manager.constant.SybConstants;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.plus.entity.WebsitSalesPayOrder;
import com.gree.mall.manager.utils.ArithUtils;
import com.gree.mall.manager.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Component
@Slf4j
public class AllInPayLogic {

    @Value("${allIn.payment.notifyUrl}")
    private String notifyUrl;
    @Value("${share.mall.appid}")
    private String mallAppid;

    @Resource
    CommonLogic commonLogic;


    /**
     * 通联支付
     */
    public Map<String, String> serviceUnifiedOrder(WebsitSalesPayOrder order, String payType)
            throws RemoteServiceException {
        Map<String, String> reqMap = new HashMap<>();
        reqMap.put("orgid", order.getOrgId());
        reqMap.put("cusid", order.getMchNo());
        reqMap.put("appid", order.getAppid());
        if (SybConstants.PAY_TYPE_W06.equals(payType)) {
            reqMap.put("acct", order.getOpenid());
            reqMap.put("sub_appid", mallAppid);
        }
        reqMap.put("notify_url", this.notifyUrl);
        reqMap.put("trxamt", (int) ArithUtils.mul(order.getPayValue().doubleValue(), 100) + "");
        reqMap.put("reqsn", order.getOrderNo());
        reqMap.put("body", order.getWebsitName());
        reqMap.put("paytype", payType);
        reqMap.put("remark", order.getOrderId());

        HashMap<String, String> heads = new HashMap();
        String token = commonLogic.getInfToken();
        if (StringUtils.isEmpty(token)) {
            throw new RemoteServiceException("获取接口令牌失败");
        }
        heads.put("authorization_token", token);

        String content = HttpUtils.requestPostBody(commonLogic.getInfUrl() + "/pay/csb/qrcode", JSON.toJSONString(reqMap), heads);

        Map<String, Object> resMap = JSON.parseObject(content, new TypeReference<HashMap<String, Object>>() {});

        if (!Optional.ofNullable(resMap.get("message")).orElse("error").toString().equals("success")) {
            log.error("通联统一支付接口执行失败: {}>>>{}", order.getOrderId(), resMap);
            throw new RemoteServiceException("通联统一支付接口执行失败：" + resMap.get("message"));
        }

        return (Map<String, String>) resMap.get("data");
    }

    /**
     * 通联支付查询订单
     */
    public Map<String, String> serviceQueryOrder(WebsitSalesPayOrder order) throws RemoteServiceException {
        Map<String, String> reqMap = new HashMap<>();
        if (StringUtils.isNotBlank(order.getOrgId())) {
            reqMap.put("orgid", order.getOrgId());
        }
        reqMap.put("cusid", order.getOrderNo());
        reqMap.put("appid", order.getAppid());
        reqMap.put("reqsn", order.getOutTradeNo());
        reqMap.put("trxid", order.getOrderNo());

        HashMap<String, String> heads = new HashMap();
        String token = commonLogic.getInfToken();
        if (StringUtils.isEmpty(token)) {
            throw new RemoteServiceException("获取接口令牌失败");
        }
        heads.put("authorization_token", token);

        String content = HttpUtils.requestPostBody(commonLogic.getInfUrl() + "/pay/csb/order/query", JSON.toJSONString(reqMap), heads);

        Map<String, Object> resMap = JSON.parseObject(content, new TypeReference<HashMap<String, Object>>() {});

        if (!Optional.ofNullable(resMap.get("message")).orElse("error").toString().equals("success")) {
            log.error("通联交易查询接口执行失败: {}", resMap);
            throw new RemoteServiceException("通联交易查询接口执行失败：" + resMap.get("message"));
        }

        return (Map<String, String>) resMap.get("data");
    }

    /**
     * 通联支付退款
     */
    public Map<String, String> serviceRefundOrder(WebsitSalesPayOrder order, String refundOrderId, BigDecimal refundValue) throws RemoteServiceException {
        Map<String, String> reqMap = new HashMap<>();
        if (StringUtils.isNotBlank(order.getOrgId())) {
            reqMap.put("orgid", order.getOrgId());
        }
        reqMap.put("appid", order.getAppid());
        reqMap.put("cusid", order.getMchNo());
        reqMap.put("trxamt", (int) ArithUtils.mul(refundValue.doubleValue(), 100) + ""); // 退款金额 单位：分
        reqMap.put("reqsn", StringUtils.isNotBlank(refundOrderId) ? refundOrderId : LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"))); // 商户的退款订单号
        reqMap.put("oldreqsn", order.getOutTradeNo()); // 原交易的商户订单号
        reqMap.put("trxid", order.getOrderNo()); // 原交易的收银宝平台流水

        HashMap<String, String> heads = new HashMap();
        String token = commonLogic.getInfToken();
        if (StringUtils.isEmpty(token)) {
            throw new RemoteServiceException("获取接口令牌失败");
        }
        heads.put("authorization_token", token);

        String content = HttpUtils.requestPostBody(commonLogic.getInfUrl() + "/pay/csb/order/refund", JSON.toJSONString(reqMap), heads);

        Map<String, Object> resMap = JSON.parseObject(content, new TypeReference<HashMap<String, Object>>() {});

        if (!Optional.ofNullable(resMap.get("message")).orElse("error").toString().equals("success")) {
            log.error("通联交易退款接口执行失败: {}", resMap);
            throw new RemoteServiceException("通联交易退款接口执行失败：" + resMap.get("message"));
        }

        return (Map<String, String>) resMap.get("data");
    }

    /**
     * 通联支付关闭
     */
    public Map<String, String> serviceCloseOrder(WebsitSalesPayOrder payRecord) throws RemoteServiceException {
        Map<String, String> reqMap = new HashMap<>();
        if (StringUtils.isNotBlank(payRecord.getMchNo())) {
            reqMap.put("orgid", payRecord.getMchNo());
        }
        reqMap.put("appid", payRecord.getAppid());
        reqMap.put("cusid", payRecord.getSubMchNo());
        reqMap.put("reqsn", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"))); // 商户的退款订单号
        reqMap.put("oldreqsn", payRecord.getOutTradeNo()); // 原交易的商户订单号
        reqMap.put("oldtrxid", payRecord.getOrderNo()); // 原交易的收银宝平台流水
        reqMap.put("trxid", payRecord.getOrderNo());

        HashMap<String, String> heads = new HashMap();
        String token = commonLogic.getInfToken();
        if (StringUtils.isEmpty(token)) {
            throw new RemoteServiceException("获取接口令牌失败");
        }
        heads.put("authorization_token", token);

        String content = HttpUtils.requestPostBody(commonLogic.getInfUrl() + "/pay/csb/order/close", JSON.toJSONString(reqMap), heads);

        Map<String, Object> resMap = JSON.parseObject(content, new TypeReference<HashMap<String, Object>>() {});

        String message = Optional.ofNullable(resMap.get("message")).orElse("error").toString();
        if (message.equals("success") || message.equals("交易已关闭")) {
            return (Map<String, String>) resMap.get("data");
        }
        log.error("通联交易关闭接口执行失败: {}", resMap);
        throw new RemoteServiceException("通联交易关闭接口执行失败：" + resMap.get("message"));
    }
}
