package com.izouma.dingdong.service;

import com.izouma.dingdong.domain.OrderInfo;
import com.izouma.dingdong.domain.OrderRefundApply;
import com.izouma.dingdong.enums.OrderStatus;
import com.izouma.dingdong.enums.RefundReason;
import com.izouma.dingdong.enums.RefundStatus;
import com.izouma.dingdong.exception.BusinessException;
import com.izouma.dingdong.repo.OrderInfoRepo;
import com.izouma.dingdong.repo.OrderRefundApplyRepo;
import com.izouma.dingdong.repo.UserRepo;
import com.izouma.dingdong.utils.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Service
@Slf4j
public class OrderRefundApplyService {

    @Autowired
    private OrderRefundApplyRepo orderRefundApplyRepo;

    @Autowired
    private OrderInfoRepo orderInfoRepo;

    @Autowired
    private UserRepo userRepo;

    private OrderStatus status;

    /**
     * 申请退款
     *
     * @param orderId 订单号
     * @param reason  退款缘由
     * @param remark  备注
     */
    public void apply(Long orderId, RefundReason reason, String remark) {
        OrderInfo order = orderInfoRepo.findById(orderId).orElseThrow(new BusinessException("无记录"));
        //记录原来的订单状态
        status = order.getStatus();
        switch (status) {
            case UNPAID:
                throw new BusinessException("暂未支付");
            case REFUNDED:
                throw new BusinessException("订单已退");
            case CANCELLED:
                throw new BusinessException("订单已取消");
            case REFUNDED_PENDING:
                return;
        }

        orderRefundApplyRepo.save(OrderRefundApply.builder()
                .status(RefundStatus.PENDING)
                .applyTime(LocalDateTime.now())
                .reason(reason)
                .remark(remark)
                .orderId(orderId)
                .report(false)
                .build());

        order.setStatus(OrderStatus.REFUNDED_PENDING);
        order.setReason(reason.toString());
        orderInfoRepo.save(order);
    }

    /**
     * 审核退款 线下退
     *
     * @param applyId 申请退款ID
     * @param consent 是否通过
     */
    public void audit(Long applyId, boolean consent) {
        OrderRefundApply apply = orderRefundApplyRepo.findById(applyId).orElseThrow(new BusinessException("无记录"));
        if (apply.getStatus() != RefundStatus.PENDING) {
            return;
        }


        userRepo.findById(apply.getOrderInfo().getUserId()).orElseThrow(new BusinessException("无用户"));
        if (consent) {

            String refundId = String.valueOf(new SnowflakeIdWorker(1, 1).nextId());
            apply.setStatus(RefundStatus.SUCCESS);

            if (StringUtils.isEmpty(apply.getRefundId())) {
                apply.setRefundId(refundId);
            }

        } else {


            apply.setStatus(RefundStatus.DENY);
            apply.getOrderInfo().setStatus((status != null) ? status : OrderStatus.PAID);
            //上报到后台
            apply.setReport(true);
        }
        apply.setAuditTime(LocalDateTime.now());
        orderInfoRepo.save(apply.getOrderInfo());
        orderRefundApplyRepo.save(apply);


    }

    /*
    取消退款
     */
    public void cancelRefundApply(Long orderId) {
        orderInfoRepo.findById(orderId).orElseThrow(new BusinessException("无订单"));
        OrderRefundApply apply = orderRefundApplyRepo.findByOrderIdAndStatus(orderId, RefundStatus.PENDING).orElseThrow(new BusinessException("未申请退款"));
        apply.setStatus(RefundStatus.CANCEL);
        apply.getOrderInfo().setStatus((status != null) ? status : OrderStatus.PAID);
        orderInfoRepo.save(apply.getOrderInfo());
        orderRefundApplyRepo.save(apply);
    }

    /*
    商家的所有退款订单
     */
    public List<OrderRefundApply> merchantRefund(Long id){
        return orderRefundApplyRepo.findAllByMerchantId(id);
    }
}
