package com.icloud.server.payutils.alipay;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.icloud.server.payutils.AbstractPayCodeMapping;
import com.icloud.server.payutils.PayCommonResult;
import com.icloud.server.payutils.dto.PayOrderUnifiedReqDTO;
import com.icloud.server.utils.JsonUtils;
import com.icloud.server.web.err.pay.PayChannelEnum;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Objects;

/**
 * 支付宝【手机网站】的 PayClient 实现类
 * 文档：https://opendocs.alipay.com/apis/api_1/alipay.trade.wap.pay
 *
 * @author
 */
@Slf4j
public class AlipayWapPayClient extends AbstractAlipayClient {
//    public AlipayWapPayClient(Long channelId, String channelCode, AlipayPayClientConfig config, AbstractPayCodeMapping codeMapping) {
//        super(channelId, channelCode, config, codeMapping);
//    }
//
//    @Override
//    protected PayCommonResult<?> doUnifiedOrder(PayOrderUnifiedReqDTO reqDTO) throws Throwable {
//        return null;
//    }


    public AlipayWapPayClient(Long channelId, AlipayPayClientConfig config) {
        super(channelId, PayChannelEnum.ALIPAY_WAP.getCode(), config, new AlipayPayCodeMapping());
    }

    public PayCommonResult<AlipayTradeWapPayResponse> doUnifiedOrder1(PayOrderUnifiedReqDTO reqDTO) {
        // 构建 AlipayTradeWapPayModel 请求
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(reqDTO.getMerchantOrderId());
        model.setSubject(reqDTO.getSubject());
        model.setBody(reqDTO.getBody());
//        HashMap<String, String> map = new HashMap<>();
//        map.put("attach",reqDTO.getChannelExtras().get("attach"));
//        String attach = JsonUtils.toJsonString(map);
//        model.setBusinessParams(attach);
        model.setTotalAmount(calculateAmount(reqDTO.getAmount()).toString());
        model.setProductCode("QUICK_WAP_PAY"); //
        model.setQuitUrl(reqDTO.getReturnUrl());

        // https://opendocs.alipay.com/apis/api_1/alipay.trade.wap.pay
        //model.setSellerId("2088102147948060");
        model.setTimeoutExpress("30m");
//        model.setTimeExpire(DateUtil.format(reqDTO.getExpireTime(),"yyyy-MM-dd HH:mm:ss"));
        // TODO ：userIp
        // 构建 AlipayTradeWapPayRequest
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setBizModel(model);
        System.out.println("最后计算的回调地址:"+reqDTO.getNotifyUrl());
        String r_url="";
        try {
            r_url=URLEncoder.encode(reqDTO.getNotifyUrl(),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        request.setNotifyUrl(r_url);
//        request.setReturnUrl(reqDTO.getReturnUrl());
        System.out.println("最后计算的返回地址:"+reqDTO.getReturnUrl());

        try {
            r_url=URLEncoder.encode(reqDTO.getReturnUrl(),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        request.setReturnUrl(r_url);
        // 执行请求
        AlipayTradeWapPayResponse response;
        try {
            response = client.pageExecute(request);
        } catch (AlipayApiException e) {
            return PayCommonResult.build(e.getErrCode(), e.getErrMsg(), null, codeMapping);
        }

//         TODO ：sub Code
        if(response.isSuccess() && Objects.isNull(response.getCode()) && Objects.nonNull(response.getBody())){
            //成功alipay wap 成功 code 为 null , body 为form 表单
            return PayCommonResult.build("-9999", "Success", response, codeMapping);
        }else {
            return PayCommonResult.build(response.getCode(), response.getMsg(), response, codeMapping);
        }


        //实例化客户端
//        AlipayClient alipayClient1 = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", "","", "json","", "RSA2");
//实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay

//        AlipayTradeWapPayRequest request1 = new AlipayTradeWapPayRequest();
////SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
//        AlipayTradeWapPayModel model1 = new AlipayTradeWapPayModel();
//        model1.setBody(reqDTO.getBody());
//        model1.setSubject(reqDTO.getSubject());
//        model1.setOutTradeNo(reqDTO.getMerchantOrderId());
//        model1.setTimeoutExpress("30m");
//        model1.setTotalAmount(calculateAmount(reqDTO.getAmount()).toString());
//        model1.setProductCode("QUICK_WAP_PAY");
//        request1.setBizModel(model1);
//        request1.setNotifyUrl(reqDTO.getNotifyUrl());
//        request1.setReturnUrl("https://www.baidu.com");
//        AlipayTradeWapPayResponse response1 = null;
//        try {
//            //这里和普通的接口调用不同，使用的是sdkExecute AlipayTradeWapPayResponse
//             response1 = client.sdkExecute(request1);
//            return PayCommonResult.build(response1.getCode(), response1.getMsg(), response1, codeMapping);
////            System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
////            return response1;
//        } catch (AlipayApiException e) {
//            return PayCommonResult.build("-9999", "Success", response1, codeMapping);
//        }


    }


    public PayCommonResult<AlipayTradeWapPayResponse> doUnifiedOrder2(PayOrderUnifiedReqDTO reqDTO) {
        // 构建 AlipayTradeWapPayModel 请求
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(reqDTO.getMerchantOrderId());
        model.setSubject(reqDTO.getSubject());
        model.setBody(reqDTO.getBody());
        HashMap<String, String> map = new HashMap<>();
        map.put("attach",reqDTO.getChannelExtras().get("attach"));
        String attach = JsonUtils.toJsonString(map);
        model.setBusinessParams(attach);
        model.setTotalAmount(calculateAmount(reqDTO.getAmount()).toString());
        model.setProductCode("QUICK_WAP_PAY"); //
        model.setQuitUrl(reqDTO.getReturnUrl());

        // https://opendocs.alipay.com/apis/api_1/alipay.trade.wap.pay
        //model.setSellerId("2088102147948060");
        model.setTimeExpire(DateUtil.format(reqDTO.getExpireTime(),"yyyy-MM-dd HH:mm:ss"));
        // TODO ：userIp
        // 构建 AlipayTradeWapPayRequest
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setBizModel(model);
        request.setNotifyUrl(reqDTO.getNotifyUrl());
        request.setReturnUrl("www.baidu.com");

        // 执行请求
        AlipayTradeWapPayResponse response;
        try {
            response = client.pageExecute(request);
        } catch (AlipayApiException e) {
            return PayCommonResult.build(e.getErrCode(), e.getErrMsg(), null, codeMapping);
        }

        // TODO ：sub Code
        if(response.isSuccess() && Objects.isNull(response.getCode()) && Objects.nonNull(response.getBody())){
            //成功alipay wap 成功 code 为 null , body 为form 表单
            return PayCommonResult.build("-9999", "Success", response, codeMapping);
        }else {
            return PayCommonResult.build(response.getCode(), response.getMsg(), response, codeMapping);
        }
    }




    @Override
    public PayCommonResult<AlipayTradeWapPayResponse> doUnifiedOrder(PayOrderUnifiedReqDTO reqDTO) {
        // 构建 AlipayTradeWapPayModel 请求
        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(reqDTO.getMerchantOrderId());
        model.setSubject(reqDTO.getSubject());
        model.setBody(reqDTO.getBody());
        HashMap<String, String> map = new HashMap<>();
        map.put("attach",reqDTO.getChannelExtras().get("attach"));
        String attach = JsonUtils.toJsonString(map);
        model.setBusinessParams(attach);
        model.setTotalAmount(calculateAmount(reqDTO.getAmount()).toString());
        model.setProductCode("QUICK_WAP_PAY"); //
        model.setQuitUrl(reqDTO.getReturnUrl());

        // https://opendocs.alipay.com/apis/api_1/alipay.trade.wap.pay
        //model.setSellerId("2088102147948060");
        model.setTimeExpire(DateUtil.format(reqDTO.getExpireTime(),"yyyy-MM-dd HH:mm:ss"));
        // TODO ：userIp
        // 构建 AlipayTradeWapPayRequest
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setBizModel(model);
        request.setNotifyUrl(reqDTO.getNotifyUrl());
        request.setReturnUrl(reqDTO.getReturnUrl());

        // 执行请求
        AlipayTradeWapPayResponse response;
        try {
            response = client.pageExecute(request);
        } catch (AlipayApiException e) {
            return PayCommonResult.build(e.getErrCode(), e.getErrMsg(), null, codeMapping);
        }

        // TODO ：sub Code
        if(response.isSuccess() && Objects.isNull(response.getCode()) && Objects.nonNull(response.getBody())){
            //成功alipay wap 成功 code 为 null , body 为form 表单
            return PayCommonResult.build("-9999", "Success", response, codeMapping);
        }else {
            return PayCommonResult.build(response.getCode(), response.getMsg(), response, codeMapping);
        }
    }







}
