package com.lightinit.hsdataportal.controller.open;

import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.lightinit.hsdataportal.common.AlipayConfig;
import com.lightinit.hsdataportal.dictionary.DicOrderState;
import com.lightinit.hsdataportal.entity.Order;
import com.lightinit.hsdataportal.model.ResultState;
import com.lightinit.hsdataportal.service.IAlipayService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author: sunxiang
 * @Date: 2018/10/27 0:14
 * @Description:
 **/
@Controller
@RequestMapping(value = "/alipay/")
public class AliPayController {

    public static final Logger logger= LoggerFactory.getLogger(AlipayConfig.class);
    @Value("${alipay.url}")
    private String url;
    @Value("${alipay.app_id}")
    private String app_id;
    @Value("${alipay.app_private_key}")
    private  String app_private_key;
    @Value("${alipay.alipay_public_key}")
    private String alipay_public_key;
    @Value("${alipay.format}")
    private String format;
    @Value("${alipay.charset}")
    private String charset;
    @Value("${alipay.sign_type}")
    private String sign_type;
    @Autowired
    private IAlipayService alipayService;

    //获取默认支付对象
    private DefaultAlipayClient getInstance(){
        return new DefaultAlipayClient(url, app_id, app_private_key, format, charset, alipay_public_key, sign_type);
    }

    @RequestMapping(value="index.htm/{orderNumber}/{orderAmount}")
    public String index(@PathVariable String orderNumber,@PathVariable BigDecimal orderAmount){
        return "open/pay/userPay";
    }
    /*
    *@Description 用户下订单，付款
    *@Param     orderNumber:订单号
    *@Date 2018/10/27
    *@return
    **/
    @RequiresAuthentication
    @RequestMapping(value="/pay.action/{orderNumber}")
    public  void tradePage(HttpServletRequest httpRequest,HttpServletResponse httpResponse,@PathVariable String orderNumber) throws AlipayApiException, IOException {
        Order order=alipayService.queryUserOrderByOrderNumber(orderNumber);
        if(order==null){//订单号不存在
            return;
        }
        //设置请求参数   必填:商户订单号,付款金额,订单名称，销售产品码 || 可选：商品描述
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        String basePath = httpRequest.getScheme()+"://"+httpRequest.getServerName();
        if(httpRequest.getServerPort()>0){
            basePath=basePath+":"+httpRequest.getServerPort();
        }
        alipayRequest.setReturnUrl(basePath+"/alipay/success.action");
        alipayRequest.setNotifyUrl(basePath+"/alipay/notice.action");

        String message="{\"out_trade_no\":\""+ order.getOrderNumber() +"\","
                + "\"total_amount\":\""+ order.getOrderAmount().toString() +"\","
                + "\"subject\":\""+ "支付费用" +"\","
                + "\"body\":\""+ order.getRemark() +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}";
        alipayRequest.setBizContent(message);
        //请求
        String form = AlipayConfig.getInstance().pageExecute(alipayRequest).getBody();
        //输出
        httpResponse.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
        httpResponse.getWriter().write(form);//直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

    /*
    *@Description 支付宝返回同步参数，可以返回自己网站的页面
    *@Param
    *@Date 2018/10/27
    *@return
    **/
    @RequestMapping(value="/success.action",method = RequestMethod.GET)
    public ModelAndView successPage(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws AlipayApiException, IOException {
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> httpRequestParams = httpRequest.getParameterMap();
        for (Iterator<String> iter = httpRequestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) httpRequestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE);
        ModelAndView modelAndView = new ModelAndView("open/pay/feedback");//支付完跳转的页面
        if(signVerified) {
            //商户订单号
            String orderNumber = new String(httpRequest.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            modelAndView.addObject("message","支付成功："+orderNumber);
            //TODO:暂时修改同步问题为同步改变状态，以后需要删除此代码：
            Order order = alipayService.queryUserOrderByOrderNumber(orderNumber);
            ResultState<String> resultState = alipayService.updateUserOderByOrderNumber(order.getId(),order.getOrderNumber());
            if(resultState.getStateCode()!=200){
                logger.error(resultState.getMsg());
            }
        }else {
            modelAndView.addObject("message","验签失败,交易错误，请联系商家");
        }
       return modelAndView;
    }

    /*
    *@Description 支付宝异步通知交易完成情况通知
    *@Param
    *@Date 2018/10/27
    *@return
    **/
    @RequestMapping(value="/notice.action",method = RequestMethod.POST)
    public void tradeNotice(HttpServletRequest httpRequest,HttpServletResponse httpResponse) throws AlipayApiException, IOException {
        System.out.println("j---------------接受到异步请求----------------------------------");
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = httpRequest.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE);
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(httpRequest.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //支付宝交易号
            String trade_no = new String(httpRequest.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //订单的实际金额
            String total_amount = new String(httpRequest.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
            // 订单的app_id
            String app_id = new String(httpRequest.getParameter("app_id").getBytes("ISO-8859-1"), "UTF-8");
            //交易状态
            String trade_status = new String(httpRequest.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
            //根据订单号查询数据库
            Order order = alipayService.queryUserOrderByOrderNumber(out_trade_no);
            //1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号
            //2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
            //3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
            //4、验证app_id是否为该商户本身。
            if (order != null && out_trade_no.equals(order.getOrderNumber()) && total_amount.equals(order.getOrderAmount().toString())
                    && app_id.equals(AlipayConfig.APP_ID) && !DicOrderState.PAY_SUCCESS.equals(order.getOrderState())) {
                if (trade_status.equals("TRADE_FINISHED")) {
                    //判断该笔订单是否在商户网站中已经做过处理
                    logger.info("订单：" + out_trade_no + "已经支付过或已过退款时间");
                    //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                } else if (trade_status.equals("TRADE_SUCCESS")) {
                    //修改数据库付款状态
                    ResultState<String> resultState = alipayService.updateUserOderByOrderNumber(order.getId(),order.getOrderNumber());
                    if(resultState.getStateCode()!=200){
                        logger.error(resultState.getMsg());
                    }
                   /* ResultState<String> paymentResultState = alipayService.insertBizOrderPayment(order, resultState.getStateCode());
                    if(paymentResultState.getStateCode()!=200){
                        logger.error(resultState.getMsg());
                    }*/
                }
            }
            //必须写出"success"，不然支付宝会轮询发送状态
            httpResponse.getWriter().println("success");
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
            return;
        }
        //验证失败
        String fail_out_trade_no=new String(httpRequest.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");;
        //调试用，写文本函数记录程序运行情况是否正常
        String sWord = AlipaySignature.getSignCheckContentV1(params);
        AlipayConfig.logResult(sWord);
        logger.info("验证失败:订单号:"+fail_out_trade_no);
        httpResponse.getWriter().println("fail");
    }

    /*
    *@Description 查询支付情况 暂时不开通此功能
    *@Param
    *@Date 2018/10/27
    *@return
    **/
   /* @RequestMapping(value="/querynotice")
    public void queryNotice(HttpServletRequest httpRequest,HttpServletResponse httpResponse) throws AlipayApiException, IOException {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"8\"," +
                "\"trade_no\":\"2018102722001448580500455544\"" +
                "  }");
        AlipayTradeQueryResponse response = AlipayConfig.getInstance().execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }*/

}
