package com.cweb.controller.meal;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.channel.lakala.LaKaLaTradeService;
import com.hfkj.channel.tianque.service.TianQueTradeService;
import com.hfkj.common.exception.BaseException;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.config.CommonSysConst;
import com.hfkj.entity.*;
import com.hfkj.model.ResponseData;
import com.hfkj.service.BsMerPlatformNoService;
import com.hfkj.service.BsTradeOrderService;
import com.hfkj.service.meal.BsMealTableOrderService;
import com.hfkj.sysenum.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @className: BsMealShopCartController
 * @author: HuRui
 * @date: 2023/11/30
 **/
@Controller
@Api(value = "桌台订单管理")
@RequestMapping(value = "/mealTableOrderPay")
public class BsMealTableOrderPayController {

    Logger log = LoggerFactory.getLogger(BsMealTableController.class);

    @Resource
    private BsTradeOrderService tradeOrderService;
    @Resource
    private BsMealTableOrderService mealTableOrderService;
    @Resource
    private BsMerPlatformNoService merPlatformNoService;
    @Resource
    private LaKaLaTradeService laKaLaTradeService;
    @Resource
    private TianQueTradeService tianQueTradeService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(value="/payOrder",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "支付订单")
    public ResponseData payOrder(@RequestBody JSONObject body, HttpServletRequest request) {
        try {
            if (body == null || StringUtils.isBlank(body.getString("orderNo")) || StringUtils.isBlank(body.getString("payUserId"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 支付订单
            BsMealTableOrder tableOrder = mealTableOrderService.getTableOrderByOrderNo(body.getString("orderNo"));
            if (tableOrder == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的订单号");
            }
            if (!tableOrder.getStatus().equals(MealTableOrderStatusEnum.status1.getNumber())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "订单状态异常");
            }
            if (!tableOrder.getPayStatus().equals(MealTableOrderPayStatusEnum.status1.getNumber())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "小伙伴正在支付中或已支付");
            }
            String lockKey = "MEAL_ORDER_PAY_" + tableOrder.getOrderNo();
            try {
                Boolean lock = redisTemplate.opsForValue().setIfAbsent(lockKey, null);
                if(lock) {
                    // 加锁成功
                    // 查询交易渠道
                    BsMerPlatformNo merPlatform = merPlatformNoService.getCurrentPlatform(tableOrder.getMerId());
                    if (merPlatform == null) {
                        throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知交易渠道");
                    }
                    Map<String, Object> param = new HashMap<>();
                    param.put("payMode", TradeOrderPayModeEnum.WECHAT.getCode());
                    param.put("payUserId", body.getString("payUserId"));
                    param.put("transType", "JSAPI");
                    param.put("sub_appid", "wxff3cbb14f62d026d");

                    // 创建订单
                    Map<String, Object> orderMap = tradeOrderService.createOrder(TradeOrderCreateTypeEnum.type4, tableOrder.getStoreId(), tableOrder.getOrderAmount(), null, null, null, param, request);
                    if (merPlatform.getPlatformType().equals(PlatformTypeEnum.type1.getNumber())) {
                        try {
                            Map<String, Object> order = laKaLaTradeService.preorder(MapUtils.getString(orderMap, "outTradeNo"));
                            System.out.println("返回参数：" + JSONObject.toJSONString(order));
                            if (StringUtils.isNotBlank(MapUtils.getString(order, "order"))) {
                                // 设置支付状态
                                tableOrder.setPayOrderNo(MapUtils.getString(orderMap, "outTradeNo"));
                                tableOrder.setPayStatus(MealTableOrderPayStatusEnum.status2.getNumber());
                                mealTableOrderService.editData(tableOrder);


                                redisTemplate.delete(lockKey);
                                return ResponseMsgUtil.success(order);
                            }
                        } catch (Exception e) {
                            log.error("拉卡拉支付失败", e.getMessage());
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, e.getMessage());
                        }
                    } else if (merPlatform.getPlatformType().equals(PlatformTypeEnum.type5.getNumber())) {
                        try {
                            Map<String, Object> order = tianQueTradeService.preorder(MapUtils.getString(orderMap, "outTradeNo"));
                            System.out.println("返回参数：" + JSONObject.toJSONString(order));
                            if (StringUtils.isNotBlank(MapUtils.getString(order, "order"))) {
                                // 设置支付状态
                                tableOrder.setPayOrderNo(MapUtils.getString(orderMap, "outTradeNo"));
                                tableOrder.setPayStatus(MealTableOrderPayStatusEnum.status2.getNumber());
                                mealTableOrderService.editData(tableOrder);

                                redisTemplate.delete(lockKey);
                                return ResponseMsgUtil.success(order);
                            }
                        } catch (Exception e) {
                            log.error("随行付支付失败", e.getMessage());
                            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, e.getMessage());
                        }
                    }

                } else {
                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "小伙伴正在支付中...");
                }
            } catch (BaseException baseException) {
                redisTemplate.delete(lockKey);
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, baseException.getErrorMsg());

            } catch (Exception e) {
                redisTemplate.delete(lockKey);
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知错误");
            }
            throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "支付失败");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/cancelPay",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "取消支付")
    public ResponseData cancelPay(@RequestBody JSONObject body) {
        try {
            if (body == null || StringUtils.isBlank(body.getString("orderNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 支付订单
            BsMealTableOrder tableOrder = mealTableOrderService.getTableOrderByOrderNo(body.getString("orderNo"));
            if (tableOrder == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未知的订单号");
            }
            if (tableOrder.getStatus().equals(MealTableOrderStatusEnum.status2.getNumber())) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "取消失败，订单已结账");
            }
            tableOrder.setPayOrderNo(null);
            tableOrder.setPayStatus(MealTableOrderPayStatusEnum.status1.getNumber());
            mealTableOrderService.editData(tableOrder);

            return ResponseMsgUtil.success("取消成功");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResponseMsgUtil.exception(e);
        }
    }

}


