package com.zsElectric.boot.business.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsElectric.boot.business.converter.UserVehicleConverter;
import com.zsElectric.boot.business.mapper.UserVehicleMapper;
import com.zsElectric.boot.business.model.entity.UserVehicle;
import com.zsElectric.boot.business.model.form.UserVehicleForm;
import com.zsElectric.boot.business.model.query.UserVehicleQuery;
import com.zsElectric.boot.business.model.vo.UserVehicleVO;
import com.zsElectric.boot.business.service.UserVehicleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 用户车辆信息服务实现类
 *
 * @author zsElectric
 * @since 2026-03-03
 */
@Service
@RequiredArgsConstructor
public class UserVehicleServiceImpl extends ServiceImpl<UserVehicleMapper, UserVehicle> implements UserVehicleService {

    private final UserVehicleConverter userVehicleConverter;

    /**
     * 获取用户车辆分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<UserVehicleVO>} 用户车辆分页列表
     */
    @Override
    public IPage<UserVehicleVO> getUserVehiclePage(UserVehicleQuery queryParams) {
        LambdaQueryWrapper<UserVehicle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(queryParams.getUserId() != null, UserVehicle::getUserId, queryParams.getUserId())
                .like(StrUtil.isNotBlank(queryParams.getLicensePlate()), UserVehicle::getLicensePlate, queryParams.getLicensePlate())
                .like(StrUtil.isNotBlank(queryParams.getBrand()), UserVehicle::getBrand, queryParams.getBrand())
                .eq(queryParams.getVehicleType() != null, UserVehicle::getVehicleType, queryParams.getVehicleType())
                .orderByDesc(UserVehicle::getIsDefault)
                .orderByDesc(UserVehicle::getCreateTime);

        Page<UserVehicle> page = this.page(new Page<>(queryParams.getPageNum(), queryParams.getPageSize()), queryWrapper);
        
        Page<UserVehicleVO> pageVO = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        pageVO.setRecords(userVehicleConverter.toVOList(page.getRecords()));
        return pageVO;
    }

    /**
     * 获取用户车辆表单数据
     *
     * @param id 车辆ID
     * @return 车辆表单数据
     */
    @Override
    public UserVehicleForm getUserVehicleFormData(Long id) {
        UserVehicle entity = this.getById(id);
        return userVehicleConverter.toForm(entity);
    }

    /**
     * 新增用户车辆
     *
     * @param formData 车辆表单对象
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveUserVehicle(UserVehicleForm formData) {
        UserVehicle entity = userVehicleConverter.toEntity(formData);
        
        // 如果设置为默认车辆，先清除该用户其他车辆的默认状态
        if (entity.getIsDefault() != null && entity.getIsDefault() == 1) {
            this.baseMapper.clearUserDefaultVehicle(entity.getUserId());
        }
        
        // 如果是用户的第一辆车，自动设为默认
        long count = this.count(new LambdaQueryWrapper<UserVehicle>()
                .eq(UserVehicle::getUserId, entity.getUserId()));
        if (count == 0) {
            entity.setIsDefault(1);
        }
        
        return this.save(entity);
    }

    /**
     * 更新用户车辆
     *
     * @param id       车辆ID
     * @param formData 车辆表单对象
     * @return 是否修改成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserVehicle(Long id, UserVehicleForm formData) {
        UserVehicle entity = userVehicleConverter.toEntity(formData);
        entity.setId(id);
        
        // 如果设置为默认车辆，先清除该用户其他车辆的默认状态
        if (entity.getIsDefault() != null && entity.getIsDefault() == 1) {
            UserVehicle existingVehicle = this.getById(id);
            if (existingVehicle != null) {
                this.baseMapper.clearUserDefaultVehicle(existingVehicle.getUserId());
            }
        }
        
        return this.updateById(entity);
    }

    /**
     * 删除用户车辆
     *
     * @param ids 车辆ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteUserVehicles(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的车辆数据为空");
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

    /**
     * 获取用户的车辆列表
     *
     * @param userId 用户ID
     * @return 车辆列表
     */
    @Override
    public List<UserVehicleVO> getUserVehicleList(Long userId) {
        LambdaQueryWrapper<UserVehicle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserVehicle::getUserId, userId)
                .orderByDesc(UserVehicle::getIsDefault)
                .orderByDesc(UserVehicle::getCreateTime);
        List<UserVehicle> list = this.list(queryWrapper);
        return userVehicleConverter.toVOList(list);
    }

    /**
     * 设置默认车辆
     *
     * @param userId    用户ID
     * @param vehicleId 车辆ID
     * @return 是否设置成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setDefaultVehicle(Long userId, Long vehicleId) {
        // 验证车辆是否属于该用户
        UserVehicle vehicle = this.getById(vehicleId);
        Assert.isTrue(vehicle != null && vehicle.getUserId().equals(userId), "车辆不存在或不属于该用户");
        
        // 清除该用户所有车辆的默认状态
        this.baseMapper.clearUserDefaultVehicle(userId);
        
        // 设置新的默认车辆
        vehicle.setIsDefault(1);
        return this.updateById(vehicle);
    }

    /**
     * 获取用户默认车辆
     *
     * @param userId 用户ID
     * @return 默认车辆信息
     */
    @Override
    public UserVehicleVO getDefaultVehicle(Long userId) {
        LambdaQueryWrapper<UserVehicle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserVehicle::getUserId, userId)
                .eq(UserVehicle::getIsDefault, 1)
                .last("LIMIT 1");
        UserVehicle vehicle = this.getOne(queryWrapper);
        return vehicle != null ? userVehicleConverter.toVO(vehicle) : null;
    }
}
