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.areaSub.domain.AreaSubVO;
import com.ruoyi.bst.device.service.DeviceService;
import com.ruoyi.bst.order.domain.enums.OrderReturnMode;
import com.ruoyi.bst.order.domain.vo.OrderInParkingVO;
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.OrderDeviceAssembler;
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 TransactionTemplate transactionTemplate;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDeviceAssembler orderDeviceAssembler;

    /**
     * 查询订单设备
     *
     * @param id    订单设备主键
     * @param scope
     * @return 订单设备
     */
    @Override
    public OrderDeviceVO selectOrderDeviceById(Long id, boolean scope)
    {
        if (id == null) {
            return null;
        }
        OrderDeviceQuery query = new OrderDeviceQuery();
        query.setId(id);
        query.setScope(scope);
        return this.selectOne(query);
    }

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

    /**
     * 新增订单设备
     *
     * @param orderDevice 订单设备
     * @return 结果
     */
    @Override
    public int insertOrderDevice(OrderDevice orderDevice)
    {
        Integer result = transactionTemplate.execute(status -> {

            int rows = orderDeviceMapper.insertOrderDevice(orderDevice);

            if (rows > 0) {
                // 修改订单信息
                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;
    }

    /**
     * 修改订单设备
     *
     * @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 = this.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);

            // if (rows > 0 ) {
            //     // 更新设备最后一次使用的用户ID
            //     int update = deviceService.updateLastUserId(orderDevice.getDeviceId(), orderDevice.getOrderUserId());
            //     ServiceUtil.assertion(update != 1, "更新设备最后一次使用的用户ID失败");
            // }

            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, OrderInParkingVO inParkingVO) {
        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);
            // 还车数据
            if (inParkingVO != null) {
                if (inParkingVO.getActualAreaSub() != null) {
                    AreaSubVO areaSub = inParkingVO.getActualAreaSub();
                    data.setEndAreaSubId(areaSub.getId());
                    data.setEndAreaSubName(areaSub.getName());
                }
                data.setReturnLon(inParkingVO.getActualLon());
                data.setReturnLat(inParkingVO.getActualLat());
                if (inParkingVO.getDeviceInArea() != null) {
                    data.setReturnMode(OrderReturnMode.DEVICE.getCode());
                } else {
                    data.setReturnMode(OrderReturnMode.MOBILE.getCode());
                }
            }
            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);
    }
}
