package com.ruoyi.task.order;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import com.ruoyi.bst.device.service.DeviceIotService;
import com.ruoyi.bst.locationLog.domain.vo.LocationLogPositionVO;
import com.ruoyi.bst.locationLog.service.LocationLogService;
import com.ruoyi.bst.locationLog.utils.LocationLogUtil;
import com.ruoyi.bst.order.domain.OrderQuery;
import com.ruoyi.bst.order.domain.OrderVO;
import com.ruoyi.bst.order.domain.enums.OrderStatus;
import com.ruoyi.bst.order.mapper.OrderMapper;
import com.ruoyi.bst.order.service.OrderService;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.collection.CollectionUtils;
import com.ruoyi.iot.constants.IotConstants;
import com.ruoyi.iot.service.IotService;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class OrderTask implements ApplicationRunner {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private LocationLogService locationLogService;

    @Autowired
    private DeviceIotService deviceIotService;

    @Autowired
    private IotService iotService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 查询所有未支付的订单
        OrderQuery query = new OrderQuery();
        query.setStatusList(OrderStatus.unPayList());
        List<OrderVO> orderList = orderMapper.selectOrderList(query);

        for (OrderVO order : orderList) {
            try {
                orderService.cancelWhenExpired(order);
            } catch (Exception e) {
                log.error("取消订单失败，订单ID：{}", order.getId(), e);
            }
        }
    }

    /**
     * 处理超过最大可用时间的订单
     */
    public void handleExpireMaxTimeOrder() {
        // 查询超过最大可用时间的订单
        OrderQuery query = new OrderQuery();
        query.setStatusList(OrderStatus.inUse());
        query.setMaxTimeEnd(LocalDateTime.now());
        List<OrderVO> orderList = orderService.selectOrderList(query);

        if (CollectionUtils.isEmptyElement(orderList)) {
            log.info("没有超过最大可用时间的订单");
            return;
        }

        for (OrderVO order : orderList) {
            try {
                // OrderEndDTO dto = new OrderEndDTO();
                // dto.setReturnType(OrderReturnType.SYSTEM.getCode());
                // dto.setOrderId(order.getId());
                // dto.setEndReason("超时系统自动结束");
                // orderService.endOrder(dto);
            } catch (Exception e) {
                log.error("结束订单失败，订单ID：{}", order.getId(), e);
            }

        }
    }

    /**
     * 计算进行中的订单距离
     */
    public void calcInUseDistance() {
        // 查询进行中的订单ID列表
        OrderQuery query = new OrderQuery();
        query.setStatusList(OrderStatus.inUse());
        List<Long> orderIds = orderService.selectIdList(query);

        if (CollectionUtils.isEmptyElement(orderIds)) {
            log.info("暂无进行中的订单");
            return;
        }


        for (Long id : orderIds) {
            try {
                // 查询定位日志
                List<LocationLogPositionVO> logs = locationLogService.selectPositionListByOrderId(id);

                // 更新距离
                BigDecimal distance = LocationLogUtil.calcDistance(logs);
                int update = orderService.updateDisatance(id, distance);
                ServiceUtil.assertion(update != 1, "更新失败");
            } catch (Exception e) {
                log.error("更新ID为{}的订单距离失败：{}", id, e);
            }
        }

    }

    /**
     * 取消超时未支付的订单
     */
    public void cancelExpireUnPayOrder() {
        // 查询超时未支付的订单
        OrderQuery query = new OrderQuery();
        query.setStatusList(OrderStatus.unPayList());
        query.setPayExpireTimeEnd(LocalDateTime.now());
        List<Long> orderIds = orderService.selectIdList(query);

        if (CollectionUtils.isEmptyElement(orderIds)) {
            log.info("没有超时未支付的订单");
            return;
        }

        for (Long id : orderIds) {
            try {
                orderService.cancelOrder(id, "订单超时取消");
            } catch (Exception e) {
                log.error("取消订单失败，订单ID：{}", id, e);
            }
        }
    }

    /**
     * 自动退还押金
     */
    public void autoRefundDeposit() {
        // 查询未自动退款的订单
        OrderQuery query = new OrderQuery();
        query.setAutoRefunded(false);
        query.setStatus(OrderStatus.FINISHED.getCode());
        List<OrderVO> orderList = orderService.selectOrderList(query);

        if (CollectionUtils.isEmptyElement(orderList)) {
            log.info("没有未自动退款的订单");
            return;
        }

        for (OrderVO order : orderList) {
            try {
                orderService.refundRemainDeposit(order);
            } catch (Exception e) {
                log.error("自动退还押金失败，订单ID：{}", order.getId(), e);
            }
        }
    }

}
