package com.hfkj.schedule;

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.entity.BsOrder;
import com.hfkj.entity.BsOrderRefund;
import com.hfkj.entity.BsOrderSettle;
import com.hfkj.model.order.OrderChildModel;
import com.hfkj.model.order.OrderModel;
import com.hfkj.service.discount.BsDiscountUserService;
import com.hfkj.service.order.*;
import com.hfkj.sysenum.order.*;
import org.apache.commons.collections4.MapUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单结算业务
 * @className: OrderSettleService
 * @author: HuRui
 * @date: 2024/6/25
 **/
@Component
public class OrderSchedule {
    @Resource
    private BsOrderService orderService;
    @Resource
    private BsOrderRefundService orderRefundService;
    @Resource
    private BsOrderChildService orderChildService;
    @Resource
    private BsOrderSettleService orderSettleService;
    @Resource
    private OrderRefundBusiness orderRefundBusiness;
    @Resource
    private BsDiscountUserService discountUserService;

    @Scheduled(cron="0 0/1 * * * ?")   //每分钟执行一次
    public void cancel() {
        List<Map<String, Object>> orderList = orderService.getNeedCancelOrderList();
        for (Map<String,Object> param : orderList) {
            try {
                // 取消订单
                orderService.cancel(MapUtils.getString(param, "orderNo"));

            } catch (Exception e) {
                System.out.println(MapUtils.getString(param, "orderNo")+"，取消订单失败！");
            }
        }
    }

    @Scheduled(cron="0 0/1 * * * ?")   //每分钟执行一次
    public void refund() {
        Map<String,Object> param = new HashMap<>();
        param.put("refundStatus", OrderRefundStatusEnum.status1.getCode());
        // 获取待退款订单
        List<BsOrderRefund> refundList = orderRefundService.getRefundList(param);
        for (BsOrderRefund orderRefund : refundList) {
            try {
                // 订单结算
                BsOrderSettle orderSettle = orderSettleService.getData(orderRefund.getOrderNo());
                if (orderSettle != null && orderSettle.getLedgerFlag().equals(true)) {
                    if (orderSettle.getLedgerStatus().equals(OrderSettleLedgerStatusEnum.status6.getCode())) {
                        // 分账撤销成功

                        // 资金退款
                        Boolean refundMoney = orderRefundService.refundMoney(orderRefund);
                        if (refundMoney != null) {
                            orderRefund.setRefundStatus(refundMoney?OrderRefundStatusEnum.status2.getCode():OrderRefundStatusEnum.status3.getCode());
                            orderRefundService.editData(orderRefund);
                        }

                        // 退款成功
                        if (orderRefund.getRefundStatus().equals(OrderRefundStatusEnum.status2.getCode())) {
                            OrderChildModel orderChild = orderChildService.getDetail(orderRefund.getOrderChildNo());
                            OrderModel order = orderService.getDetail(orderRefund.getOrderNo());

                            // 修改子订单可退数量、金额、积分
                            orderChild.setSurplusRefundCount(0);
                            orderChild.setSurplusRefundPrice(orderChild.getSurplusRefundPrice().subtract(orderRefund.getRefundPrice()));
                            orderChild.setSurplusRefundIntegral(orderChild.getSurplusRefundIntegral() - orderRefund.getRefundIntegral());
                            orderChild.setStatus(orderChild.getSurplusRefundCount()==0? OrderChildStatusEnum.status4.getCode():orderChild.getStatus());
                            orderChildService.editData(orderChild);

                            // 处理退款业务
                            if (orderChild.getProductType().equals(OrderChildProductTypeEnum.type1.getCode())) {
                                try {
                                    orderRefundBusiness.gasOrder(orderRefund);
                                } catch (BaseException e) {
                                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, e.getErrorMsg());
                                } catch (Exception e) {
                                    throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "退款失败");
                                }
                            }

                            // 查询子订单已全部退款
                            List<OrderChildModel> orderChildList = orderChildService.getOrderChildListByOrderNo(orderChild.getOrderNo());
                            if (orderChildList.size() == orderChildList.stream().filter(o->o.getStatus().equals(OrderChildStatusEnum.status4.getCode())).collect(Collectors.toList()).size()) {
                                order.setOrderStatus(OrderStatusEnum.status4.getCode());
                                order.setRefundTime(new Date());
                                orderService.editData(order);

                                if (order.getDeduction().getUserCouponDiscountId() != null) {
                                    // 退回优惠券
                                    discountUserService.revokeUserDiscount(order.getDeduction().getUserCouponDiscountId());
                                }
                            }
                        }

                        // 删除缓存
                        orderService.cacheDelete(orderRefund.getOrderNo());
                    }
                }
            } catch (Exception e) {

            }
        }

    }
}
