package com.wteam.controller.payment;

import com.wteam.framework.common.enums.OrderStatusEnum;
import com.wteam.framework.common.enums.ResultCode;
import com.wteam.framework.common.enums.ResultUtil;
import com.wteam.framework.common.exception.ServiceException;
import com.wteam.framework.common.vo.ResultMessage;
import com.wteam.framework.modules.book.entity.Card;
import com.wteam.framework.modules.book.entity.OrderInfo;
import com.wteam.framework.modules.book.mapper.CardMapper;
import com.wteam.framework.modules.book.mapper.OrderInfoMapper;
import com.wteam.framework.modules.book.service.OrderInfoService;
import com.wteam.framework.modules.pay.entity.enums.PaymentMethodEnum;
import com.wteam.framework.modules.pay.serviceimpl.CashierSupport;
import com.wteam.framework.modules.pay.serviceimpl.RefundSupport;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.Date;

/**
 * @author doncic
 * @date 2023/10/10 20:13
 */
@Slf4j
@RestController
@Tag(name = "退款相关接口管理")
@RequestMapping("/v1/payment/refund")
public class CashierRefundController {


    @Autowired
    private CashierSupport cashierSupport;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private CardMapper cardMapper;


    //TODO：退款接口待办 实现的有点问题
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paymentMethod", value = "支付方式", paramType = "path", allowableValues = "WECHAT"),
    })
    @ApiOperation(value = "退款")
    @RequestMapping(value = "/refund/{paymentMethod}/{sn}", method = {RequestMethod.POST})
    public Object processRefund(HttpServletRequest request, @PathVariable String paymentMethod, @PathVariable String sn) {
        PaymentMethodEnum paymentMethodEnum = PaymentMethodEnum.valueOf(paymentMethod);
        try {
            return cashierSupport.refund(paymentMethodEnum, sn);
        } catch (ServiceException se) {
            log.info("支付异常", se);
            throw se;
        } catch (Exception e) {
            log.error("收银台支付错误", e);
        }
        return null;
    }


    @Operation(summary = "使用储值卡购买租场订场退款")
    @PostMapping("/cardRefund/{orderId}")
    @Transactional
    public ResultMessage cardRefund(@PathVariable String orderId) {
        try {
            OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
            if (orderInfo == null) {
                return ResultUtil.success();
            }

            Double orderPrice = orderInfo.getOrderPrice();
            Integer cardId = orderInfo.getCardId();
            Card card = cardMapper.selectById(cardId);

            if (card == null) {
                return ResultUtil.success();
            }

            //1、只有订场订单可以进行退款 24小时前退款
            long orderDate = orderInfo.getOrderDate().getTime();
            log.info("该订单的预约日期为：{}", orderDate);

            // 获取当前日期前一天的日期
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DAY_OF_YEAR, -1);
            Date oneDayBefore = calendar.getTime();
            long oneDayBeforeTime = oneDayBefore.getTime();
            log.info("当前日期的前一天为：{}", oneDayBeforeTime);


            long isOrderDateBeforeOneDayBefore = orderDate - oneDayBeforeTime;
            // 转换为天数
            long millisecondsInDay = 24 * 60 * 60 * 1000; // 1天有多少毫秒
            long daysDifference = isOrderDateBeforeOneDayBefore / millisecondsInDay;
            log.info("相减之后天数为：{}", daysDifference);

            //判断时间是否为24小时之内
            boolean isGreaterThanOneDay = daysDifference > 1;

            String orderState = orderInfo.getOrderState();
            //判断只有还未使用的订单才能够退款
            boolean isOrderStateValid = "WAITING_TO_USE".equals(orderState);

            log.info("此时的布尔值为：{},{}", isOrderStateValid, isGreaterThanOneDay);

            // 在订单日期前一天且订单状态符合要求时可以进行退款
            if (isGreaterThanOneDay && isOrderStateValid) {

                Double currentBalance = card.getCurrentBalance();
                double newBalance = currentBalance + orderPrice;
                card.setCurrentBalance(newBalance);
                cardMapper.updateById(card);

                orderInfo.setOrderState(String.valueOf(OrderStatusEnum.REFUNDED));
                orderInfoMapper.updateById(orderInfo);

                return ResultUtil.success();
            }
        } catch (Exception e) {
            // 处理异常，如数据库操作失败
            log.info("储值卡购买的租场订单退款错误为：{}", e.getMessage());
        }
        return ResultUtil.error(ResultCode.TIME_NOT_REFUND);
    }
}