package com.xunwang.payment.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xunwang.commonutils.JwtUtils;
import com.xunwang.commonutils.R;
import com.xunwang.payment.entity.OrderInfo;
import com.xunwang.payment.entity.dto.MyOrder;
import com.xunwang.payment.entity.dto.MyOrderDetail;
import com.xunwang.payment.enums.OrderStatus;
import com.xunwang.payment.feign.MsgFeign;
import com.xunwang.payment.feign.UserFeign;
import com.xunwang.payment.mapper.OrderInfoMapper;
import com.xunwang.payment.service.OrderInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @author Long
 * @since 2023-02-23
 */
@Api("订单管理")
@RestController
@RequestMapping("/payment/order-info")
public class OrderInfoController {

    @Resource
    private OrderInfoService orderInfoService;

    @Resource
    private UserFeign userFeign;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private OrderInfoMapper orderInfoMapper;

    @ApiOperation("根据openId返回订单列表")
    @GetMapping("/list/{openId}")
    public R list(@PathVariable String openId) {
        List<OrderInfo> orderInfos = orderInfoService.listOrderByCreateTimeDesc(openId);
        return R.ok().data("list", orderInfos);
    }

    @ApiOperation("生成订单")
    @GetMapping("/generate/order/{inviteId}")
    public R generateOrder(@PathVariable String inviteId) {
        OrderInfo orderInfo = orderInfoService.createOrderByInviteId(inviteId);
        return R.ok().data("info", orderInfo);
    }

    @ApiOperation("根据uid返回订单列表")
    @GetMapping("/list/uid")
    public R listByUid(HttpServletRequest request) {
        String uid = JwtUtils.getUIdByJwtToken(request);
        R openIdByUid = userFeign.getOpenIdByUid(uid);
        String openid = (String) openIdByUid.getData().get("openid");
        List<MyOrder> myOrderList = orderInfoMapper.getMyOrderList(openid);
        return R.ok().data("list", myOrderList);
    }

    @ApiOperation("获取订单倒计时")
    @GetMapping("/getCountDown")
    public R getCountDown(HttpServletRequest request) {
        String orderId = request.getParameter("orderId");
        Long expire = stringRedisTemplate.opsForValue().getOperations().getExpire("countdown:" + orderId);
        return R.ok().data("time", expire);
    }

    @ApiOperation("根据订单号获取订单信息")
    @GetMapping("/getOrderInfoByOrderId")
    public R getOrderInfoByOrderId(HttpServletRequest request) {
        String orderId = request.getParameter("orderId");
        OrderInfo one = orderInfoService.getOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderId, orderId));
        MyOrderDetail myOrderDetail = new MyOrderDetail();
        BeanUtils.copyProperties(one, myOrderDetail);
        return R.ok().data("one", myOrderDetail);
    }

    @GetMapping("/queryOrderStatus")
    @ApiOperation("查询支付中本地订单状态")
    public R queryOrderStatus(HttpServletRequest request) {
        String orderId = request.getParameter("orderId");
        if (!"".equals(orderId)) {
            return orderInfoService.queryOrderStatus(orderId);
        }
        return R.error();
    }

    @GetMapping("/queryIsRefundOrder")
    @ApiOperation("查询是否退款订单")
    public R queryIsRefundOrder(HttpServletRequest request) {
        String orderId = request.getParameter("orderId");
        if (!"".equals(orderId)) {
            return orderInfoService.queryIsRefundOrder(orderId);
        }
        return R.error();
    }

    @ApiOperation("更改申请退款状态")
    @GetMapping("/updateIsRefund/{orderId}")
    public boolean updateIsRefund(@PathVariable String orderId) throws ParseException {
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getOrderId, orderId);
        OrderInfo one = orderInfoService.getOne(wrapper);
        // 下单时间
        String datetime = one.getDatetime();
        String[] s = datetime.split(" ");
        DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate time = LocalDate.parse(s[0], pattern);
        LocalDate localDate = time.plusDays(5);
        // 当前时间
        LocalDate now = LocalDate.now();
        boolean before = localDate.isBefore(now);
        if (!before) {
            OrderInfo orderInfo = new OrderInfo().setIsRefund(1);
            orderInfoService.update(orderInfo, wrapper);
            return true;
        }
        return false;
    }

    @ApiOperation("根据 推荐uid，返回订单列表, 未提现")
    @GetMapping("/list/recommendUidNotWithdraw")
    public R listByRecommendUidNotWithdraw(HttpServletRequest request) {
        String uid = JwtUtils.getUIdByJwtToken(request);
        List<OrderInfo> myOrderList = orderInfoMapper.getNotWithdrawOrderListByRecommendUid(uid);
        return R.ok().data("list", myOrderList);
    }

    @ApiOperation("根据 推荐uid，返回订单列表, 已提现")
    @GetMapping("/list/recommendUidWithdraw")
    public R listByRecommendUidWithdraw(HttpServletRequest request) {
        String uid = JwtUtils.getUIdByJwtToken(request);
        List<OrderInfo> myOrderList = orderInfoMapper.getWithdrawOrderListByRecommendUid(uid);
        return R.ok().data("list", myOrderList);
    }

}
