package com.thinkgem.jeesite.modules.pay.alipay.service;

import com.alibaba.fastjson.JSONObject;
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.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradeOrderSettleRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradeOrderSettleResponse;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.modules.pay.alipay.config.AlipayConfig;
import com.thinkgem.jeesite.modules.pay.juhezhong.utils.MakeOrderNum;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.alipay.api.AlipayConstants.APP_ID;
import static com.alipay.api.AlipayConstants.CHARSET;

@Service
@Transactional
public class AlipayService {

    public JSONObject alipay(JSONObject dto) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",Global.getConfig("alipay.appid"),Global.getConfig("alipay.private.key"),"json","UTF-8",Global.getConfig("alipay.public.key"),"RSA2");
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"20150320010101001\"," +
                "\"seller_id\":\"2088102146225135\"," +
                "\"total_amount\":88.88," +
                "\"discountable_amount\":8.88," +
                "\"subject\":\"Iphone616G\"," +
                "\"body\":\"Iphone616G\"," +
                "\"buyer_id\":\"2088102146225135\"," +
                "\"goods_detail\":[{" +
                "\"goods_id\":\"apple-01\"," +
                "\"goods_name\":\"ipad\"," +
                "\"quantity\":1," +
                "\"price\":2000," +
                "\"goods_category\":\"34543238\"," +
                "\"body\":\"特价手机\"," +
                "\"show_url\":\"http://www.alipay.com/xxx.jpg\"" +
                "}]," +
                "\"operator_id\":\"Yx_001\"," +
                "\"store_id\":\"NJ_001\"," +
                "\"terminal_id\":\"NJ_T_001\"," +
                "\"extend_params\":{" +
                "\"sys_service_provider_id\":\"2088511833207846\"" +
                "}," +
                "\"timeout_express\":\"90m\"," +
                "\"business_params\":\"{\\\"data\\\":\\\"123\\\"}\"" +
                "}");
        AlipayTradeCreateResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

        return null;
    }


    public static void main(String[] args) throws AlipayApiException {
        AlipayService alipayService = new AlipayService();
//        dto.put("out_request_no", MakeOrderNum.makeOrderNum());// 结算请求流水号 开发者自行生成并保证唯一性
//        dto.put("trade_no",IdGen.randomBase62(64)); // 支付宝订单号
//        JSONObject royalty_parameters = new JSONObject();  // 分账明细信息
//        royalty_parameters.put("trans_out","2088101126765726");// 	分账支出方账户，类型为userId，本参数为要分账的支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字
//        royalty_parameters.put("trans_in","2088101126708402"); // 	分账收入方账户，类型为userId，本参数为要分账的支付宝账号对应的支付宝唯一用户号。以2088开头的纯16位数字。
//        royalty_parameters.put("amount","0.1"); // 分账的金额，单位为元
//        royalty_parameters.put("amount_percentage","100"); // 分账信息中分账百分比。取值范围为大于0，少于或等于100的整数。
//        royalty_parameters.put("desc","desc");
//        dto.put("operator_id","operator_id");// 	操作员id 可选
//        alipayService.alipay(dto);
        JSONObject dto = new JSONObject();
        dto.put("body",new HashMap<>());
        String payCode = IdGen.randomBase62(64);
        String amount = "0.01";

        dto.put("payCode",payCode);
        dto.put("amount",amount);
        dto.put("subject","subject");

        alipayService.aliPay(dto);

    }

    public String aliPay(JSONObject dto) throws AlipayApiException {
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",Global.getConfig("alipay.appid"), Global.getConfig("alipay.private.key") , "json", "UTF-8", Global.getConfig("alipay.public.key"), "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setPassbackParams(dto.get("body").toString());  //描述信息  添加附加数据
        model.setSubject(dto.getString("subject")); //商品标题
        model.setOutTradeNo(dto.getString("payCode")); //商家订单编号
        model.setTimeoutExpress(AlipayConfig.TIMEOUTEXPRESS); //超时关闭该订单时间
        model.setTotalAmount(dto.getString("amount"));  //订单总金额
        model.setProductCode("QUICK_MSECURITY_PAY"); //销售产品码，商家和支付宝签约的产品码，为固定值QUICK_MSECURITY_PAY
        request.setBizModel(model);
        request.setNotifyUrl(Global.getConfig("project.access.url")+"/api/pay/aliPayCallback");  //回调地址
        String orderStr = "";
        //这里和普通的接口调用不同，使用的是sdkExecute
        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
        orderStr = response.getBody();
        System.out.println(orderStr);//就是orderString 可以直接给客户端请求，无需再做处理。

        return orderStr;
    }
}
