package com.ruoyi.bst.orderDevice.service.impl;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import com.github.pagehelper.PageHelper;
import com.ruoyi.bst.device.service.DeviceIotService;
import com.ruoyi.bst.device.service.DeviceService;
import com.ruoyi.bst.order.service.OrderService;
import com.ruoyi.bst.orderDevice.domain.OrderDevice;
import com.ruoyi.bst.orderDevice.domain.OrderDeviceQuery;
import com.ruoyi.bst.orderDevice.domain.OrderDeviceVO;
import com.ruoyi.bst.orderDevice.domain.enums.OrderDeviceStatus;
import com.ruoyi.bst.orderDevice.domain.enums.OrderDeviceType;
import com.ruoyi.bst.orderDevice.mapper.OrderDeviceMapper;
import com.ruoyi.bst.orderDevice.service.OrderDeviceService;
import com.ruoyi.common.utils.ServiceUtil;
import com.ruoyi.common.utils.collection.CollectionUtils;

/**
 * 订单设备Service业务层处理
 *
 * @author ruoyi
 * @date 2025-04-01
 */
@Service
public class OrderDeviceServiceImpl implements OrderDeviceService
{
    @Autowired
    private OrderDeviceMapper orderDeviceMapper;

    @Autowired
    private DeviceIotService deviceIotService;

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private OrderService orderService;

    /**
     * 查询订单设备
     *
     * @param id 订单设备主键
     * @return 订单设备
     */
    @Override
    public OrderDeviceVO selectOrderDeviceById(Long id)
    {
        return orderDeviceMapper.selectOrderDeviceById(id);
    }

    /**
     * 查询订单设备列表
     *
     * @param orderDevice 订单设备
     * @return 订单设备
     */
    @Override
    public List<OrderDeviceVO> selectOrderDeviceList(OrderDeviceQuery orderDevice)
    {
        return orderDeviceMapper.selectOrderDeviceList(orderDevice);
    }

    /**
     * 新增订单设备
     *
     * @param orderDevice 订单设备
     * @return 结果
     */
    @Override
    public int insertOrderDevice(OrderDevice orderDevice)
    {
        return orderDeviceMapper.insertOrderDevice(orderDevice);
    }

    /**
     * 修改订单设备
     *
     * @param orderDevice 订单设备
     * @return 结果
     */
    @Override
    public int updateOrderDevice(OrderDevice orderDevice)
    {
        return orderDeviceMapper.updateOrderDevice(orderDevice);
    }

    /**
     * 批量删除订单设备
     *
     * @param ids 需要删除的订单设备主键
     * @return 结果
     */
    @Override
    public int deleteOrderDeviceByIds(Long[] ids)
    {
        return orderDeviceMapper.deleteOrderDeviceByIds(ids);
    }

    /**
     * 删除订单设备信息
     *
     * @param id 订单设备主键
     * @return 结果
     */
    @Override
    public int deleteOrderDeviceById(Long id)
    {
        return orderDeviceMapper.deleteOrderDeviceById(id);
    }

    /**
     * 根据订单ID查询原始设备
     *
     * @param id 订单ID
     * @return 订单设备
     */
    @Override
    public OrderDeviceVO selectOriginByOrderId(Long orderId) {
        if (orderId == null) {
            return null;
        }
        OrderDeviceQuery query = new OrderDeviceQuery();
        query.setOrderId(orderId);
        query.setType(OrderDeviceType.ORIGINAL.getCode());
        return selectOne(query);
    }

    private OrderDeviceVO selectOne(OrderDeviceQuery query) {
        PageHelper.startPage(1, 1);
        List<OrderDeviceVO> list = orderDeviceMapper.selectOrderDeviceList(query);
        return CollectionUtils.firstElement(list);
    }

    @Override
    public int start(OrderDeviceVO orderDevice) {
        ServiceUtil.assertion(orderDevice == null, "订单设备不能为空");
        ServiceUtil.assertion(!OrderDeviceStatus.canStart().contains(orderDevice.getStatus()), "订单设备状态不允许开始");

        Integer result = transactionTemplate.execute(status -> {
            // 修改订单设备状态
            OrderDevice data = new OrderDevice();
            data.setStatus(OrderDeviceStatus.USING.getCode());
            data.setStartTime(LocalDateTime.now());
            OrderDeviceQuery query = new OrderDeviceQuery();
            query.setId(orderDevice.getId());
            query.setStatusList(OrderDeviceStatus.canStart());
            int rows = orderDeviceMapper.updateByQuery(data, query);

            // 修改订单信息
            int updateOrder = orderService.updateOrderDeviceId(orderDevice.getOrderId(), orderDevice.getId());
            ServiceUtil.assertion(updateOrder != 1, "更新订单信息失败");

            // 修改设备信息
            int updateDevice = deviceService.updateCurrentDeviceOrderId(orderDevice.getDeviceId(), orderDevice.getId());
            ServiceUtil.assertion(updateDevice != 1, "更新设备信息失败");

            return rows;
        });

        return result == null ? 0 : result;
    }

    @Override
    public List<OrderDeviceVO> selectOrderDeviceListByOrderId(Long orderId) {
        if (orderId == null) {
            return null;
        }
        OrderDeviceQuery query = new OrderDeviceQuery();
        query.setOrderId(orderId);
        return orderDeviceMapper.selectOrderDeviceList(query);
    }

    @Override
    public int finish(OrderDeviceVO orderDevice, String picture) {
        ServiceUtil.assertion(orderDevice == null, "订单设备不能为空");
        ServiceUtil.assertion(!OrderDeviceStatus.canFinish().contains(orderDevice.getStatus()), "订单设备状态不允许结束");
        
        Integer result = transactionTemplate.execute(status -> {
            // 修改状态
            OrderDevice data = new OrderDevice();
            data.setStatus(OrderDeviceStatus.FINISHED.getCode());
            data.setEndTime(LocalDateTime.now());
            data.setFinishPicture(picture);
            OrderDeviceQuery query = new OrderDeviceQuery();
            query.setId(orderDevice.getId());
            query.setStatusList(OrderDeviceStatus.canFinish());
            int rows = orderDeviceMapper.updateByQuery(data, query);

            // 清除设备当前订单设备ID
            int clear = deviceService.clearCurrentOrderDevice(orderDevice.getDeviceId(), orderDevice.getId());
            ServiceUtil.assertion(clear != 1, "清除设备当前订单ID失败");

            return rows;
        });

        return result == null ? 0 : result;
    }

    @Override
    public int start(Long id) {
        OrderDeviceVO orderDevice = selectOrderDeviceById(id);
        ServiceUtil.assertion(orderDevice == null, "ID为%s的订单设备不存在", id);
        return start(orderDevice);
    }

    @Override
    public OrderDeviceVO selectUsingByUserId(Long userId) {
        if (userId == null) {
            return null;
        }
        OrderDeviceQuery query = new OrderDeviceQuery();
        query.setOrderUserId(userId);
        query.setStatusList(OrderDeviceStatus.inUse());
        return selectOne(query);
    }
}
