package com.duowenlvshi.duowenlszp.app.alPay;

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.response.AlipayTradeAppPayResponse;
import com.duowenlvshi.duowenlszp.model.Meal.server.MealServer;
import com.duowenlvshi.duowenlszp.model.Order.entity.Order;
import com.duowenlvshi.duowenlszp.model.Order.server.OrderServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yang fang yu
 * @since 2019/9/11 15:18
 */
@Slf4j
@Service
@RestController
@RequestMapping("/aiPay")
public class alPay {
    @Autowired
    MealServer mealServer;
    @Autowired
    OrderServer orderServer;

    @Value("${alPay.serverUrl}")
    private String serverUrl;

    @Value("${alPay.appId}")
    private String appId;

    @Value("${alPay.privateKey}")
    private String privateKey;

    @Value("${alPay.format}")
    private String format;

    @Value("${alPay.charset}")
    private String charset;

    @Value("${alPay.ailpayPublicKey}")
    private String ailpayPublicKey;

    @Value("${alPay.signType}")
    private String signType;

    @Value("${alPay.notifyUrl}")
    private String notifyUrl;

    @Value("${alPay.ailPublicKey}")
    private String ailPublicKey;


    public String pay(Map map)  {
        String order_info = "";
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl,appId,privateKey,format,charset,ailpayPublicKey,signType);
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(map.get("Body")+"");
        model.setSubject(map.get("Subject")+"");
        model.setOutTradeNo(map.get("OutTradeNo")+"");
        model.setTimeoutExpress("30m");
        model.setTotalAmount(map.get("TotalAmount")+"");
        model.setProductCode("QUICK_MSECURITY_PAY");
        request.setBizModel(model);
        request.setNotifyUrl(notifyUrl);
        try {
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
            order_info = response.getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return order_info;
    }


    @RequestMapping(value = "/Callback", method = {RequestMethod.POST, RequestMethod.GET})
    public void aliCallback(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException {
        log.info("支付宝回调+++++++++++++++++++++++++++++++++");
        try {
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator 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] + ",";
            }
            params.put(name, valueStr);
        }
        /*boolean flag = AlipaySignature.rsaCertCheckV1(params, ailPublicKey,"utf-8","RSA2");*/

            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
            //支付时间
            String gmt_payment = new String(request.getParameter("gmt_payment").getBytes("ISO-8859-1"),"UTF-8");


            log.info("订单号"+out_trade_no+",支付宝交易号"+trade_no+",支付宝交易状态"+trade_status);
            Order order =orderServer.selectByPrimaryKey(out_trade_no);
            if(order !=null){
                int i;
                if("TRADE_SUCCESS".equals(trade_status) && !"TRADE_SUCCESS".equals(order.getTradeNo())){
                    order.setTradeNo(trade_no);//设置支付宝交易号
                    order.setPaystate(trade_status);//设置支付状态
                    order.setOrderstate("1");//设置订单完成
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date dt = sdf.parse(gmt_payment);
                    Calendar rightNow = Calendar.getInstance();
                    rightNow.setTime(dt);
                    rightNow.add(Calendar.MONTH, order.getDuration());//加上套餐时长 月
                    Date dt1 = rightNow.getTime();
                    order.setEndTime(dt1);//设置套餐结束时间
                    order.setPaydate(dt);//设置套餐支付时间
                     i =orderServer.updateByPrimaryKeySelective(order);

                    Map map2 = new HashMap();
                    int num = mealServer.selectPurchaseNuml(order.getMealId());
                    ++num;
                    map2.put("num",num);
                    map2.put("id",order.getMealId());
                    mealServer.updatePurchaseNuml(map2);
                     if(i<1){
                         log.info("修改订单失败");
                     }
                }else if(!"TRADE_SUCCESS".equals(trade_status)){
                    order.setPaystate(trade_status);
                     i =orderServer.updateByPrimaryKeySelective(order);
                    if(i<1){
                        log.info("修改订单失败");
                    }
                }
                response.getWriter().write("success");
                response.flushBuffer();
            }else{
                response.getWriter().write("fail");
                response.flushBuffer();
                log.info("验证失败订单号"+out_trade_no+",支付宝交易号"+trade_no+",支付宝交易状态"+trade_status);
            }

        } catch (Exception e) {
            try {
                response.getWriter().write("fail");
                response.flushBuffer();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }

    }


}
