package com.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.BsOrder;
import com.hfkj.model.ResponseData;
import com.hfkj.model.order.OrderModel;
import com.hfkj.service.order.BsOrderService;
import com.hfkj.sysenum.order.OrderPayChannelEnum;
import com.hfkj.sysenum.order.OrderPayTypeEnum;
import com.hfkj.sysenum.order.OrderStatusEnum;
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 org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: OrderPayNotifyController
 * @author: HuRui
 * @date: 2024/5/7
 **/
@Controller
@RequestMapping(value="/notify")
@Api(value="通知业务")
public class OrderPayNotifyController {
    Logger log = LoggerFactory.getLogger(OrderPayNotifyController.class);
    @Resource
    private BsOrderService orderService;

    @RequestMapping(value="/huipay",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "【惠支付】主扫通知")
    public void huipay(@RequestBody String body, HttpServletResponse response) {
        try {
            log.info("===============惠支付回调start==================");
            JSONObject dataObject = JSONObject.parseObject(body);
            // 处理业务
            log.info("开始处理业务");
            log.info("惠支付-回调参数: " + dataObject);

            // 查询交易订单
            OrderModel order = orderService.getDetail(dataObject.getString("outTradeNo"));
            if (order != null && order.getOrderStatus().equals(OrderStatusEnum.status1.getCode())) {
                // 支付方式 微信：WECHAT 支付宝：ALIPAY 银联：UQRCODEPAY
                String payMode = dataObject.getString("payMode");
                if ("WECHAT".equals(payMode)) {
                    order.setPayType(OrderPayTypeEnum.type1.getCode());

                } else if ("ALIPAY".equals(payMode)) {
                    order.setPayType(OrderPayTypeEnum.type2.getCode());
                }
                order.setPayChannel(OrderPayChannelEnum.type1.getCode());
                order.setPayTime(new Date(dataObject.getLong("payTime")));
                order.setPaySerialNo(dataObject.getString("accTradeNo"));
                orderService.orderPaySuccessHandle(order);
            }
            log.info("处理业务完成");
            log.info("============回调任务End=============");

            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer= response.getWriter();

            JSONObject postJson = new JSONObject();
            postJson.put("code" ,"SUCCESS");
            postJson.put("message" ,"执行成功");
            writer.write(postJson.toJSONString());
            writer.flush();
            writer.close();

        } catch (Exception e) {
            log.error("订单处理异常", e);
        } finally {
            log.info("===============微信支付回调end==================");
        }
    }

    @RequestMapping(value = "/huiftPay", method = RequestMethod.POST)
    @ApiOperation(value = "贵行V家园小程序支付 -> 异步回调")
    public void huiftPay(@RequestBody String params, HttpServletRequest request, HttpServletResponse response) {
        try {
            log.info("===============贵行V家园小程序支付回调start==================");
            log.info("回调参数： " + params);
            if (StringUtils.isNotBlank(params)) {
                // 参数解码
                String paramsStr = URLDecoder.decode(params,"utf-8");
                JSONObject body = JSONObject.parseObject(paramsStr);
                log.info("开始处理订单： " + body.getString("outTradeNo"));

                // 查询订单信息
                OrderModel order = orderService.getDetail(body.getString("outTradeNo"));
                if (order != null && order.getOrderStatus().equals(OrderStatusEnum.status1.getCode())) {
                    log.info("开始处理业务");
                    // 处理订单业务
                    order.setPayChannel(OrderPayChannelEnum.type3.getCode());
                    order.setPayType(OrderPayTypeEnum.type3.getCode());
                    order.setPayTime(new Date(body.getLong("payTime")));
                    order.setPaySerialNo(body.getString("bankTraceNo"));
                    orderService.orderPaySuccessHandle(order);
                }
                log.info("处理业务完成");
            }
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            JSONObject result = new JSONObject();
            result.put("messagecode", "0");
            result.put("message", "回调成功");
            out.write(result.toJSONString().getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            log.error("订单处理异常", e);
        } finally {
            log.info("===============贵行V家园小程序支付回调end==================");
        }
    }
}
