package cn.pluss.platform.controller.home;

import cn.pluss.platform.ali.AliPayNotifyService;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.deviceMerchantBuy.DeviceMerchantBuyService;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.pay.ApiPayService;
import cn.pluss.platform.util.*;
import cn.pluss.platform.wap.HttpUrlConnection;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yuchen
 *
 * @Description 授权应用获取token控制器
 */
@Controller
@RequestMapping("aliPay")
public class AliPayController {

    @Setter(onMethod_ = {@Autowired})
    private AliPayNotifyService aliPayNotifyService;

    private static final Logger logger = LoggerFactory.getLogger(AliPayController.class);

    @Setter(onMethod_ = {@Autowired})
    private HttpServletRequest request;

    @Setter(onMethod_ = {@Autowired})
    private DeviceMerchantBuyService deviceMerchantBuyService;

    /**
     * base64编码
     */
    final static Base64.Encoder encoder = Base64.getEncoder();

    @Resource
    private ApiPayService apiPayService;


    @GetMapping("/index")
    public String index() throws UnsupportedEncodingException {
        String userId = request.getParameter("userId");
        if (userId == null) {
            return "aliPay/fail";
        }
        byte[] textByte = userId.getBytes("UTF-8");
        String returnUrl = ParametersUtil.ALI_RETURN_URL;
        userId = encoder.encodeToString(textByte);
        StringBuffer sb = new StringBuffer();
        sb.append("https://openauth.alipay.com/oauth2/appToAppBatchAuth.htm?");
        sb.append("app_id=" + ParametersUtil.ALI_APP_ID);
        sb.append("&application_type=WEBAPP,MOBILEAPP");
        sb.append("&redirect_uri=" + returnUrl);
        sb.append("&state=" + userId);
        request.setAttribute("returnUrl", sb);
        return "aliPay/aliPay";
    }

    @GetMapping("/returnUrl")
    public String returnUrl(String orderNumber){
        request.setAttribute("orderNumber",orderNumber);
        request.setAttribute("appId",ParametersUtil.ZY_ALI_APP_ID);
        return "th_alipay";
    }


    /**
     * aliCallBack:(设备订单支付宝回调通知). <br/>
     *
     * @param request
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @PostMapping("/aliCallBack")
    public String aliCallBack(HttpServletRequest request) {
        Map<String, Object> srcParam = HttpUrlConnection.convertRequestParamsToMap(this.request);
        Map<String, String> params = new HashMap<>();

        for (Map.Entry<String, Object> entry : srcParam.entrySet()) {
            params.put(entry.getKey(), (String) entry.getValue());
        }

        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(params, ParametersUtil.ZY_PUB, "UTF-8", "RSA2");
            if (signVerified) {
                String tradeStatus = params.get("trade_status");
                logger.info("=====tradeStatus=====" + tradeStatus);
                if ("TRADE_SUCCESS".equals(tradeStatus)) {
                    String tradeNumber = params.get("trade_no");
                    String orderNumber = params.get("out_trade_no");// 商家订单号
                    String consumTime = params.get("gmt_payment");// 交易付款时间
                    DeviceMerchantBuy deviceMerchantBuy = new DeviceMerchantBuy();
                    deviceMerchantBuy.setOrderNo(orderNumber);
                    deviceMerchantBuy = deviceMerchantBuyService.queryDeviceMerchantBuy(deviceMerchantBuy);
                    if ("1".equals(deviceMerchantBuy.getStatus())) {
                        return "success";
                    }
                    deviceMerchantBuy.setStatus("1");
                    deviceMerchantBuy.setTransNo(tradeNumber);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    deviceMerchantBuy.setTransDt(sdf.parse(consumTime));
                    deviceMerchantBuyService.updateDeviceMerchantBuy(deviceMerchantBuy);
                }
                return "success";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "failure";
        }
        return "failure";
    }

    /**
     * aliCallBack:(设备订单支付宝回调通知). <br/>
     *
     * @param request
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @PostMapping("/aliCallBackV2")
    public String aliCallBackV2(HttpServletRequest request) {
        Map<String, Object> param = HttpUrlConnection.convertRequestParamsToMap(request);
        try {
            aliPayNotifyService.commonPayNotify(param);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "failure";
        }
    }

    @PostMapping("/app/getAuthOpenId")
    @ResponseBody
    public Result<Object> getAuthOpenId(@RequestBody JSONObject params) {
        String authCode = params.getString("authCode");
        if(StringUtil.isEmpty(authCode)){
            return ResultGenerator.genFailResult("获取授权信息失败！");
        }
        String privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCEWqqQVjebxhtnuGC9yBUFnFJ7R4ZYKJ/110WYdww/N2YDQPmOqYLW5d4BSDtjZmYlMwG/QFO2NIf5tMz1vtN4/Px9PUIlEFYkdTNAr4kQeQ/cEpj+jymZZ1cpGnZnFBiGYuSsovGIe5CmeegYBMKreuTzjZP5tsGMH2UQ9bEsc4q2y74VGV8j0ealA5Z9fh9aIF+CSi0SfftGuc3n0SSDIWB/ZOFVEkcuVbO/qbIM+2xFkS2RbKKlDW88cdHr9cSPY9A4b8c9aiaHUHWHCHRCKMZsgY8ANGrvCRC4sgMaX96UKk+0Ioy5lI0lkdHr5Yal/NExyWRwTZEugIaSMWF5AgMBAAECggEAR61iWbCXhQEQrmcn3R+SYut5r9HYa730gwsGYb93HnU+Bd0WSbB7by4lwMQBhZ9bCiJJe+22aCKi0RSdOykRFaDMjHa0b6YdQLlH/GwT6pvlfuWDfbjCapWQmm3+WWyEq6K6/NNxwtxIRiAXFYrecken3k56KO5UezI1Za3pOYzB2kRaIoJ0/jqpQPUBhbdIQ8CkztHmXmWb57CmuvlKHjc5YlxGS+vRTdRY6ifSbwFr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pjYAHPBGakMNfOOZgFO6PDeMvnJtRhSrw0fIRK+S382Xx3kg9TXa2NW6J4tJ+limKEv4HKEH3a0ocNdVtjmyl5CoPlhuZVtktuan+3DVMLdHDXABOyRad447DWJkExpKqu79lAcvySzzgRwXPgDnvbOGrAiPIMJ0esp+aw9gGraais+EcYnptMTvbwlFiADcgPEyVf7htIVdxyZtBLiZl1ltYX9W69Fk6prP7/wYccy4uOyu2uhHS0AmMQrbXZg4EmpAUoY7ckUOqplP0+/nJlJLB1jMxkXWzDqnCanU9pEL3sQIDAQAB";
        //实例化客户端 参数：正式环境URL,Appid,商户私钥 PKCS8格式,字符编码格式,字符格式,支付宝公钥,签名方式
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do","2021003101623191",privateKey,"json","GBK",publicKey,"RSA2");
        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
        // 值为authorization_code时，代表用code换取
        request.setGrantType("authorization_code");
        //授权码，用户对应用授权后得到的
        request.setCode(authCode);
        AlipaySystemOauthTokenResponse response = null;
        try {
            response = alipayClient.execute(request);
            //刷新令牌，上次换取访问令牌时得到。见出参的refresh_token字段
            request.setRefreshToken(response.getAccessToken());
            //返回成功时 就将唯一标识返回
            if(response.isSuccess()){
                return ResultGenerator.genSuccessResult("获取成功",response.getUserId());
            } else {
                return ResultGenerator.genFailResult("授权失败");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return ResultGenerator.genFailResult("授权失败");
    }

    @PostMapping("/orderPay")
    @ResponseBody
    public Result<Object> orderPay(String authCode,String orderNumber) {
        if(StringUtil.isEmpty(authCode)){
            return ResultGenerator.genFailResult("授权码信息为空");
        }
        if(StringUtil.isEmpty(orderNumber)){
            return ResultGenerator.genFailResult("订单号为空");
        }
        AlipaySystemOauthTokenResponse tokenResponse = AliUtil.getAliUserIdV2(authCode, ParametersUtil.ZY_PRI, ParametersUtil.ZY_PUB, ParametersUtil.ZY_ALI_APP_ID);
        return apiPayService.orderPay(tokenResponse.getUserId(),orderNumber);
    }

    public static void main(String[] args) {
        String openid = "o_q_P5bPxk3JvvfGEHrDcDYxbl3o";
        JSONObject result = new JSONObject(10);
        result.put("merchantCode","M800202107223018811");
        result.put("method","trans_wap_pay");
        result.put("subject","测试123");
        result.put("ip","127.0.0.1");
        result.put("payWay","ZFBZF");
        result.put("paySource","01");
        result.put("mercOrderNo",StringUtil.getBillno());
        result.put("payAmt","0.20");
        result.put("notifyUrl","https://www.baici.com");
//        String str = SignUtils.getSignContent(result) +"&key=efaa811e9f004429b5dc070c410405c8";
        String str =  SignUtils.getSignContent(result) +"&key=4c8d277b0f274604af68e590cc0b3e6b";
        String ckeckSign = MD5Util.MD5Encode(str, "UTF-8");
        result.put("sign",ckeckSign);
        System.out.println("支付参数:"+result.toJSONString());

    }
}
