package com.yonge.cooleshow.portal.controller;

import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huifu.adapay.core.AdapayCore;
import com.huifu.adapay.core.util.AdapaySign;
import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.exception.BizException;
import com.yonge.cooleshow.mall.common.enums.OrderCacheEnum;
import com.yonge.cooleshow.portal.dto.OrderPayRes;
import com.yonge.cooleshow.portal.service.OmsPortalOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: liweifan
 * @Data: 2022/3/11 18:16
 */
@RestController
@RequestMapping("/payment")
@Api(value = "付款接口", tags = "付款接口")
public class PaymentController extends BaseController {
    private final static Logger log = LoggerFactory.getLogger(PaymentController.class);

    @Autowired
    private SysUserFeignService sysUserFeignService;

    @Autowired
    private OmsPortalOrderService orderService;

    @Autowired
    private RedissonClient redissonClient;

    // 调用管乐迷里的
    // @ApiOperation(value = "订单付款")
    // @PostMapping("/orderPay")
    public HttpResponseResult<OrderPayRes> orderPay(@Valid @RequestBody Map payReq, HttpServletRequest request) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null || null == user.getId()) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        String orderNo = MapUtil.getStr(payReq,"orderNo");

        RLock lock = redissonClient.getLock(OrderCacheEnum.LOCK_ORDER_NO_MALL.getRedisKey(orderNo));
        try {
            boolean b = lock.tryLock(60, TimeUnit.SECONDS);
            if (b) {
                return orderService.orderPay(payReq);
            }
            return failed("请求超时");
        } catch (BizException e) {
            return failed(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return failed("付款失败");
        } finally {
            if (lock.getHoldCount()>0) {
                lock.unlock();
            }
        }
    }


    /***
     * 支付回调
     * @author liweifan
     * @param: request
     * @updateTime 2022/3/11 18:35
     */
    @RequestMapping("/callback")
    public Object callback( HttpServletRequest request) {
        try {
            // 验签请参data
            String data = request.getParameter("data");
            // 验签请参sign
            String sign = request.getParameter("sign");

            log.info("callback request param:{}", data);

            // 验签
            if (AdapaySign.verifySign(data, sign, AdapayCore.PUBLIC_KEY)) {

                JSONObject dataObj = JSON.parseObject(data);

                String transType = request.getParameter("type");


                RLock lock = redissonClient.getLock(OrderCacheEnum.LOCK_ORDER_NO_MALL.getRedisKey(dataObj.getString("order_no")));
                try {
                    boolean b = lock.tryLock(60, TimeUnit.SECONDS);

                    if (b) {

                        switch (transType) {
                            case "payment.succeeded":// 支付成功

                                orderService.paymentSucceededHandle(dataObj.getString("order_no"),
                                                   dataObj.getBigDecimal("pay_amt"),dataObj.getString("pay_channel"));

                                break;

                            case "payment.failed":// 支付失败

                                Map<String,Object> notifyMap = new HashMap<>();

                                notifyMap.put("channelType", dataObj.getString("pay_channel"));
                                notifyMap.put("tradeState", "0");
                                notifyMap.put("totalMoney", dataObj.getString("pay_amt"));
                                notifyMap.put("merOrderNo", dataObj.getString("order_no"));
                                orderService.paymentFailedHandle(dataObj.getString("order_no"),notifyMap);

                                break;

                            default:
                                break;
                        }
                    } else {
                        return failed("请求超时");
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    return failed("请求超时");
                }
            } else {
                return "验签失败";
            }
        } catch (Exception e) {
            return e.getMessage();
        }

        return "succeeded";
    }

}
