package org.jeecg.modules.pay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.pay.config.AliPay;
import org.springframework.web.bind.annotation.RequestMapping;

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

@Slf4j
public class AlipayService {

    AlipayClient alipayClient;

    AliPay aliPay;

    final String web_notify_Url = "";
    final String web_retrun_Url = "";
    final String app_notify_Url = "";

    @RequestMapping("/webpay")
    public Object webpay() {
        String subject = "小李飞刀";
        String amount = "0.01";
        String body = "uid:9090";
        String orderNo = String.valueOf(System.currentTimeMillis());
        AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();
        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
        model.setOutTradeNo(orderNo);
        model.setSubject(subject);
        model.setTotalAmount(amount);
        model.setBody(body);
        model.setTimeoutExpress("5m");
        model.setProductCode("QUICK_WAP_PAY");
        alipay_request.setBizModel(model);
        alipay_request.setNotifyUrl(web_notify_Url);
        alipay_request.setReturnUrl(web_retrun_Url);

        try {
            return alipayClient.pageExecute(alipay_request).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return e.getErrMsg();
        }
    }

    @RequestMapping("/reback")
    public String webpayNotify() {
        return null;
    }










    @RequestMapping("apppay")
    public Object apppay(String subject, String clientIp, String productId, Integer price, String orderNo, String body){
        System.err.printf("create Order: \n{} \n{} \n{} \n{} \n{} \n{}", subject, clientIp, productId, price, orderNo, body);

        String amount = BigDecimal.valueOf(price/100).toString();
        //String amount = "0.01";
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setOutTradeNo(orderNo);
        model.setBody(body);
        model.setSubject(subject);
        model.setTimeoutExpress("15m");
        model.setTotalAmount(amount);
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(app_notify_Url);
        try {
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            return response.getBody();
        } catch (AlipayApiException alipayae) {
            alipayae.printStackTrace();
            return alipayae.getErrMsg();
        }
    }

    public AliPayNotifyResult appNotify(Map<String,String[]> requestParams) throws AlipayApiException {

        Map<String,String> params = new HashMap<>();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            if (name.equals("trade_status")) {
                System.out.println("交易状态为：" + valueStr);
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }

        //return new AliPayNotifyResult(params, aliPay.getAliPubilcKey());
        return new AliPayNotifyResult(params, "");
    }


    public JSONObject selectAlipayResult(String outTradeNo){

        try {
            //实例化客户端（参数：网关地址、商户appid、商户私钥、格式、编码、支付宝公钥、加密类型）
            AlipayTradeQueryRequest alipayTradeQueryRequest = new AlipayTradeQueryRequest();
            alipayTradeQueryRequest.setBizContent("{" + "\"out_trade_no\":\""+outTradeNo+"\"" + "}");
            AlipayTradeQueryResponse alipayTradeQueryResponse = alipayClient.execute(alipayTradeQueryRequest);
            if(alipayTradeQueryResponse.isSuccess()){

                switch (alipayTradeQueryResponse.getTradeStatus()) // 判断交易结果
                {
                    case "TRADE_FINISHED": // 交易结束并不可退款
                        break;
                    case "TRADE_SUCCESS": // 交易支付成功
                        break;
                    case "TRADE_CLOSED": // 未付款交易超时关闭或支付完成后全额退款
                        break;
                    case "WAIT_BUYER_PAY": // 交易创建并等待买家付款
                        break;
                    default:
                        break;
                }
                return null;

            } else {
                return null;
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;

    }










    @Data
    @ToString
    public static class AliPayNotifyResult {

        private String outTradeNo;
        private String tradeNo;
        private String authAppId;
        private String buyerLogonId;
        private String gmtPayment;
        private String invoiceAmount;
        private Boolean verifyResult = false;

        public AliPayNotifyResult(Map<String, String> params, String pubilcKey){
            this.outTradeNo = new String(params.get("out_trade_no"));
            this.tradeNo = new String(params.get("trade_no"));
            this.authAppId = new String(params.get("auth_app_id"));
            this.buyerLogonId = new String(params.get("buyer_logon_id"));
            this.gmtPayment = new String(params.get("gmt_payment"));
            this.invoiceAmount = new String(params.get("invoice_amount"));
            try {
                this.verifyResult = AlipaySignature.rsaCheckV1(params, pubilcKey, "UTF-8", "RSA2");
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
        }
    }
}