package com.ics.controller.mobile.meeting;

import cn.hutool.core.lang.Assert;
import com.google.gson.Gson;
import com.ics.admin.domain.meeting.Reservation;
import com.ics.admin.service.meeting.IReservationService;
import com.ics.controller.mobile.pay.wx.WxPayCallbackUtil;
import com.ics.controller.mobile.pay.wx.WxPayCommon;
import com.ics.controller.mobile.pay.wx.dto.WxChatBasePayDto;
import com.ics.controller.mobile.pay.wx.dto.WxChatPayDto;
import com.ics.admin.service.meeting.ICustomerTicketService;
import com.ics.common.core.controller.BaseController;
import com.ics.common.core.domain.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付
 */
@RestController
@RequestMapping("/meeting/wxPay")
public class WxPayController extends BaseController {

    @Autowired
    ICustomerTicketService customerTicketService;

    @Autowired
    WxPayCommon wxPayCommon;

    @Autowired
    WxPayCallbackUtil wxPayCallbackUtil;

    @Autowired
    private IReservationService reservationService;


    /**
     * 下载
     */
    @PostMapping("paySign")
    public R paySign(@RequestBody Reservation reservation) {
//        String prepayId = wxPayCommon.wxJsApiPay(wxChatBasePayDto);
        WxChatPayDto wxChatPayDto = wxPayCommon.wxPayCall(reservation.getPrepayId());
        return R.data(wxChatPayDto);
    }


    /**
     * 订单支付后回调
     */
    @PostMapping("orderCallBack")
    public HashMap orderCallBack(HttpServletRequest request, HttpServletResponse response) {
        HashMap<String, String> returnParam = new HashMap<>();
        try {
            Map<String, String> parseParam = wxPayCallbackUtil.wxChatPayCallback(request, response);
            // 交易状态
            // SUCCESS：支付成功
            // REFUND：转入退款
            // NOTPAY：未支付
            // CLOSED：已关闭
            // REVOKED：已撤销（付款码支付）
            // USERPAYING：用户支付中（付款码支付）
            // PAYERROR：支付失败(其他原因，如银行返回失败)
            String trade_state = parseParam.get("trade_state");
            // 商户订单号
            String out_trade_no = parseParam.get("out_trade_no");
            // 微信订单号
            String transaction_id = parseParam.get("transaction_id");
            //
            //支付成功
            if (trade_state.equals("SUCCESS")){
                //编写支付成功后逻辑
                System.out.println("订单支付后回调");
                Gson gson = new Gson();
                System.out.println(gson.toJson(parseParam));
                Reservation reservation =  reservationService.selectByOrderNumber(out_trade_no);
                Assert.isTrue(reservation != null, "订单不存在");
                if (reservation.getStauts().equals(Reservation.Status.TO_BE_PAID)){
                    reservation.setStauts(Reservation.Status.APPOINTMENT);
                    reservation.setOrderTime(new Date());
                    int i = reservationService.updateReservation(reservation);
                    Assert.isTrue(i == 1, "更新失败");
                }
            }
            //响应微信
            returnParam.put("code", "SUCCESS");
            returnParam.put("message", "成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnParam;
    }


    /**
     * 商户订单号查询订单
     */
    @PostMapping("wxMerchantOrderQuery")
    public HashMap wxMerchantOrderQuery(@RequestBody Map<String , String> paramMap) {
        HashMap<String, String> resultMap = wxPayCommon.wxMerchantOrderQuery(paramMap.get("outTradeNo"));

        HashMap<Object, Object> map = new HashMap<>();
        // 商户订单号
        String out_trade_no = resultMap.get("out_trade_no");
        // 微信支付订单号
        String transaction_id = resultMap.get("transaction_id");
        Reservation reservation =  reservationService.selectByOrderNumber(out_trade_no);

        // 交易状态
        // * SUCCESS：支付成功
        // * REFUND：转入退款
        // * NOTPAY：未支付
        // * CLOSED：已关闭
        // * REVOKED：已撤销（仅付款码支付会返回）
        // * USERPAYING：用户支付中（仅付款码支付会返回）
        // * PAYERROR：支付失败（仅付款码支付会返回）
        String trade_state = resultMap.get("trade_state");
        if (trade_state.equals("SUCCESS")){
            //更新数据库
            Assert.isTrue(reservation != null, "订单不存在");
            reservation.setStauts(Reservation.Status.APPOINTMENT);
            reservation.setOrderTime(new Date());
            int i = reservationService.updateReservation(reservation);
            Assert.isTrue(i == 1, "更新失败");
            map.put("code", 200);
            map.put("msg", "支付成功");
        }else if (trade_state.equals("REFUND")){
            map.put("code", 500);
            map.put("msg", "转入退款");
        }else if (trade_state.equals("NOTPAY")){
            map.put("code", 500);
            map.put("msg", "未支付");
        }else if (trade_state.equals("CLOSED")){
            map.put("code", 500);
            map.put("msg", "已关闭");
        }else if (trade_state.equals("REVOKED")){
            map.put("code", 500);
            map.put("msg", "已撤销");
        }else if (trade_state.equals("USERPAYING")){
            map.put("code", 500);
            map.put("msg", "用户支付中");
        }else if (trade_state.equals("PAYERROR")){
            map.put("code", 500);
            map.put("msg", "支付失败");
        }else {
            map.put("code", 500);
            map.put("msg", "支付失败");
        }

        return map;
    }


}
