package com.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.hai.common.exception.ErrorCode;
import com.hai.common.exception.ErrorHelp;
import com.hai.common.exception.SysCode;
import com.hai.common.pay.util.IOUtil;
import com.hai.common.pay.util.XmlUtil;
import com.hai.entity.*;
import com.hai.order.service.OrderPaySuccessService;
import com.hai.order.service.OrderService;
import com.hai.order.type.OrderPayType;
import com.hai.order.type.OrderStatus;
import com.hai.service.pay.NotifyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.SortedMap;

/**
 * @className: OrderPayNotifyController
 * @author: HuRui
 * @date: 2022/9/8
 **/
@Controller
@RequestMapping("/payNotify")
@Api(value = "订单支付")
public class OrderPayNotifyController {

    private static final Logger log = LoggerFactory.getLogger(OrderPayNotifyController.class);

    @Resource
    private NotifyService notifyService;

    @Resource
    private OrderService orderService;

    @Resource
    private OrderPaySuccessService paySuccessService;

    @RequestMapping(value = "/wechatPay", method = RequestMethod.POST)
    @ApiOperation(value = "微信支付 -> 异步回调")
    public void wechatPay(HttpServletRequest request, HttpServletResponse response) {
        try {
            log.info("===============微信支付回调start==================");
            String resXml = "";    // 反馈给微信服务器
            String notifyXml = null;    // 微信支付系统发送的数据（<![CDATA[product_001]]>格式）
            notifyXml = IOUtil.inputStreamToString(request.getInputStream(), "UTF-8");

            log.info("回调参数： " + notifyXml);
            SortedMap<String, String> map = XmlUtil.parseXmlToTreeMap(notifyXml, "UTF-8");
            log.info("开始处理订单： " + map.get("out_trade_no"));

            // 处理业务
            log.info("开始处理业务");

            // 查询交易订单
            HighOrder order = orderService.getOrderDetailByNo(map.get("out_trade_no"));
            if (order != null && order.getOrderStatus().equals(OrderStatus.STATUS1.getNumber())) {
                // 处理订单业务
                paySuccessService.orderPaySuccessHandle(map.get("out_trade_no"),
                        OrderPayType.PAY_TYPE2,
                        map.get("transaction_id"),
                        new BigDecimal(map.get("total_fee")).divide(new BigDecimal("100")),
                        null);
            }
            log.info("处理业务完成");

            // 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了
            resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";

            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            log.error("订单处理异常", e);
        } finally {
            log.info("===============微信支付回调end==================");
        }
    }

    @RequestMapping(value = "/unionPay", method = RequestMethod.POST)
    @ApiOperation(value = "银联支付 -> 异步回调")
    public void unionPay(@RequestBody String params, HttpServletRequest request, HttpServletResponse response) {
        try {
            log.info("===============银联支付回调start==================");
            log.info("回调参数： " + params);
            if (StringUtils.isNotBlank(params)) {
                // 参数解码
                String paramsStr = URLDecoder.decode(params,"utf-8");
                JSONObject body = JSONObject.parseObject(paramsStr.substring(0, paramsStr.length() - 1));
                log.info("开始处理订单： " + body.getString("tradetrace"));

                // 查询订单信息
                HighOrder order = orderService.getOrderDetailByNo(body.getString("tradetrace"));
                if (order != null && order.getOrderStatus().equals(OrderStatus.STATUS1.getNumber())) {
                    log.info("开始处理业务");
                    // 处理订单业务
                    paySuccessService.orderPaySuccessHandle(order.getOrderNo(),
                            OrderPayType.PAY_TYPE5,
                            body.getString("wtorderid"),
                            order.getPayPrice(),
                            null);
                }
                log.info("处理业务完成");
            }
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            JSONObject result = new JSONObject();
            result.put("resultcode", "00");
            out.write(result.toJSONString().getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            log.error("订单处理异常", e);
        } finally {
            log.info("===============银联支付回调end==================");
        }
    }

}
