package com.xindazhou.vehicle.service.impl;

import com.xindazhou.framework.common.exception.util.ServiceExceptionUtil;
import com.xindazhou.vehicle.api.dto.VehicleRespDTO;
import com.xindazhou.vehicle.api.dto.bind.VehicleBindReqDTO;
import com.xindazhou.vehicle.api.dto.bind.VehicleBindRespDTO;
import com.xindazhou.vehicle.api.dto.bind.VehicleCreateAndBindReqDTO;
import com.xindazhou.vehicle.convert.binding.UserVehicleBindingConvert;
import com.xindazhou.vehicle.convert.vehicle.VehicleConvert;
import com.xindazhou.vehicle.dal.dataobject.binding.UserVehicleBindingDO;
import com.xindazhou.vehicle.dal.dataobject.vehicle.VehicleDO;
import com.xindazhou.vehicle.dal.mysql.binding.UserVehicleBindingMapper;
import com.xindazhou.vehicle.dal.mysql.vehicle.VehicleMapper;
import com.xindazhou.vehicle.service.VehicleBindService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

import static com.xindazhou.vehicle.enums.ErrorCodeConstants.VEHICLE_BINDING_NOT_EXISTS;
import static com.xindazhou.vehicle.enums.ErrorCodeConstants.VEHICLE_ALREADY_BOUND;

/**
 * 车辆绑定 Service 实现类
 *
 * @author xindazhou
 */
@Service
@Slf4j
public class VehicleBindServiceImpl implements VehicleBindService {

    @Resource
    private UserVehicleBindingMapper userVehicleBindingMapper;

    @Resource
    private VehicleMapper vehicleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public VehicleRespDTO createVehicleAndBind(VehicleCreateAndBindReqDTO reqDTO) {
        // 1. 检查车辆是否已存在（通过vin或deviceSn）
        VehicleDO existingVehicle = vehicleMapper.selectByVin(reqDTO.getVin());
        if (existingVehicle == null) {
            existingVehicle = vehicleMapper.selectByDeviceSn(reqDTO.getDeviceSn());
        }

        Long vehicleId;
        if (existingVehicle != null) {
            // 车辆已存在，使用现有车辆ID
            vehicleId = existingVehicle.getId();
        } else {
            // 2. 如果不存在，创建vehicle记录
            VehicleDO vehicle = VehicleDO.builder()
                    .vin(reqDTO.getVin())
                    .deviceSn(reqDTO.getDeviceSn())
                    .bluetoothMac(reqDTO.getBluetoothMac())
                    .nickname(reqDTO.getName())
                    .ownerUserId(reqDTO.getUserId())
                    .modelId(reqDTO.getModelId())
                    .status(1) // 启用状态
                    .build();
            vehicleMapper.insert(vehicle);
            vehicleId = vehicle.getId();
        }

        // 3. 检查是否已绑定
        UserVehicleBindingDO existingBinding = userVehicleBindingMapper.selectByUserIdAndVehicleId(
                reqDTO.getUserId(), vehicleId);
        if (existingBinding != null && !existingBinding.getDeleted()) {
            throw ServiceExceptionUtil.exception(VEHICLE_ALREADY_BOUND);
        }

        // 4. 创建user_vehicle_binding关系记录
        UserVehicleBindingDO binding = UserVehicleBindingDO.builder()
                .userId(reqDTO.getUserId())
                .vehicleId(vehicleId)
                .userType(reqDTO.getUserType())
                .bindTime(LocalDateTime.now())
                .isDefault(0) // 默认不是默认车辆，后续逻辑会处理
                .build();
        userVehicleBindingMapper.insert(binding);

        // 5. 如果是用户的第一台车辆，设置为默认车辆
        List<UserVehicleBindingDO> userBindings = userVehicleBindingMapper.selectListByUserId(reqDTO.getUserId());
        if (userBindings.size() == 1) {
            // 这是第一台车辆，设置为默认
            binding.setIsDefault(1);
            userVehicleBindingMapper.updateById(binding);
        }

        // 返回车辆信息
        VehicleDO vehicle = vehicleMapper.selectById(vehicleId);
        return VehicleConvert.INSTANCE.convert(vehicle);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long bindVehicle(VehicleBindReqDTO reqDTO) {
        // 检查是否已绑定
        UserVehicleBindingDO existing = userVehicleBindingMapper.selectByUserIdAndVehicleId(
                reqDTO.getUserId(), reqDTO.getVehicleId());
        if (existing != null && !existing.getDeleted()) {
            throw ServiceExceptionUtil.exception(VEHICLE_ALREADY_BOUND);
        }

        // 创建绑定关系
        UserVehicleBindingDO binding = UserVehicleBindingDO.builder()
                .userId(reqDTO.getUserId())
                .vehicleId(reqDTO.getVehicleId())
                .userType(reqDTO.getUserType())
                .bindTime(LocalDateTime.now())
                .isDefault(0) // 默认不是默认车辆，后续逻辑会处理
                .build();
        userVehicleBindingMapper.insert(binding);

        // 如果是用户的第一台车辆，设置为默认车辆
        List<UserVehicleBindingDO> userBindings = userVehicleBindingMapper.selectListByUserId(reqDTO.getUserId());
        if (userBindings.size() == 1) {
            // 这是第一台车辆，设置为默认
            binding.setIsDefault(1);
            userVehicleBindingMapper.updateById(binding);
        }

        return binding.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unbindVehicle(Long userId, Long vehicleId) {
        UserVehicleBindingDO binding = userVehicleBindingMapper.selectByUserIdAndVehicleId(userId, vehicleId);
        if (binding == null || binding.getDeleted()) {
            throw ServiceExceptionUtil.exception(VEHICLE_BINDING_NOT_EXISTS);
        }

        boolean wasDefault = binding.getIsDefault() != null && binding.getIsDefault() == 1;

        // 软删除
        userVehicleBindingMapper.deleteById(binding.getId());

        // 如果解绑的是默认车辆，需要处理默认车辆逻辑
        if (wasDefault) {
            // 查找用户的其他车辆，将第一个设置为默认
            List<UserVehicleBindingDO> remainingBindings = userVehicleBindingMapper.selectListByUserId(userId);
            if (!remainingBindings.isEmpty()) {
                UserVehicleBindingDO firstBinding = remainingBindings.get(0);
                firstBinding.setIsDefault(1);
                userVehicleBindingMapper.updateById(firstBinding);
            }
        }
    }

    @Override
    public List<VehicleBindRespDTO> listBindByVehicleId(Long vehicleId) {
        List<UserVehicleBindingDO> bindings = userVehicleBindingMapper.selectListByVehicleId(vehicleId);
        return UserVehicleBindingConvert.INSTANCE.convertList(bindings);
    }

    @Override
    public List<VehicleBindRespDTO> listBindByUserId(Long userId, Integer userType) {
        List<UserVehicleBindingDO> bindings = userVehicleBindingMapper.selectListByUserId(userId);
        return UserVehicleBindingConvert.INSTANCE.convertList(bindings);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDefaultVehicle(Long userId, Long vehicleId) {
        // 验证绑定关系是否存在
        UserVehicleBindingDO binding = userVehicleBindingMapper.selectByUserIdAndVehicleId(userId, vehicleId);
        if (binding == null || binding.getDeleted()) {
            throw ServiceExceptionUtil.exception(VEHICLE_BINDING_NOT_EXISTS);
        }
        
        // 取消用户所有车辆的默认状态
        List<UserVehicleBindingDO> allBindings = userVehicleBindingMapper.selectListByUserId(userId);
        for (UserVehicleBindingDO b : allBindings) {
            if (b.getIsDefault() != null && b.getIsDefault() == 1) {
                b.setIsDefault(0);
                userVehicleBindingMapper.updateById(b);
            }
        }
        
        // 设置指定车辆为默认车辆
        binding.setIsDefault(1);
        userVehicleBindingMapper.updateById(binding);
    }

}

