package com.hotwj.platform.resourceManagement.vehicleChange.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hotwj.platform.driverManagement.driver.domain.HotDriver;
import com.hotwj.platform.driverManagement.driver.mapper.HotDriverMapper;
import com.hotwj.platform.resourceManagement.vehicleChange.domain.HotVehicleChange;
import com.hotwj.platform.resourceManagement.vehicleChange.domain.bo.HotVehicleChangeBo;
import com.hotwj.platform.resourceManagement.vehicleChange.domain.vo.HotVehicleChangeVo;
import com.hotwj.platform.resourceManagement.vehicleChange.mapper.HotVehicleChangeMapper;
import com.hotwj.platform.resourceManagement.vehicleChange.service.IHotVehicleChangeService;
import com.hotwj.platform.resourceManagement.vehicleManagement.domain.HotVehicle;
import com.hotwj.platform.resourceManagement.vehicleManagement.mapper.HotVehicleMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 车辆变更记录Service业务层处理
 *
 * @author shihongwei
 * @date 2025-12-19
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class HotVehicleChangeServiceImpl implements IHotVehicleChangeService {

    private final HotVehicleChangeMapper baseMapper;
    private static final Set<String> CLEAR_DRIVER_OPERATION_STATUS = new HashSet<>(Arrays.asList("3", "4", "5"));
    private final HotVehicleMapper vehicleMapper;
    private final HotDriverMapper driverMapper;

    /**
     * 查询车辆变更记录
     *
     * @param id 主键
     * @return 车辆变更记录
     */
    @Override
    public HotVehicleChangeVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询车辆变更记录列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 车辆变更记录分页列表
     */
    @Override
    public TableDataInfo<HotVehicleChangeVo> queryPageList(HotVehicleChangeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HotVehicleChange> lqw = buildQueryWrapper(bo);
        Page<HotVehicleChangeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的车辆变更记录列表
     *
     * @param bo 查询条件
     * @return 车辆变更记录列表
     */
    @Override
    public List<HotVehicleChangeVo> queryList(HotVehicleChangeBo bo) {
        LambdaQueryWrapper<HotVehicleChange> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HotVehicleChange> buildQueryWrapper(HotVehicleChangeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HotVehicleChange> lqw = Wrappers.lambdaQuery();
        lqw.orderByDesc(HotVehicleChange::getCreateTime);
        lqw.eq(bo.getCompanyId() != null, HotVehicleChange::getCompanyId, bo.getCompanyId());
        lqw.eq(bo.getVehicleId() != null, HotVehicleChange::getVehicleId, bo.getVehicleId());
        lqw.like(StringUtils.isNotBlank(bo.getPlateNumber()), HotVehicleChange::getPlateNumber, bo.getPlateNumber());
        lqw.eq(bo.getChangeDate() != null, HotVehicleChange::getChangeDate, bo.getChangeDate());
        lqw.eq(StringUtils.isNotBlank(bo.getChangeItem()), HotVehicleChange::getChangeItem, bo.getChangeItem());
        lqw.eq(StringUtils.isNotBlank(bo.getChangeReason()), HotVehicleChange::getChangeReason, bo.getChangeReason());
        lqw.eq(bo.getRecorderId() != null, HotVehicleChange::getRecorderId, bo.getRecorderId());
        lqw.like(StringUtils.isNotBlank(bo.getRecorderName()), HotVehicleChange::getRecorderName, bo.getRecorderName());
        lqw.eq(StringUtils.isNotBlank(bo.getChangeCertImageUrls()), HotVehicleChange::getChangeCertImageUrls, bo.getChangeCertImageUrls());
        lqw.eq(bo.getIsDeleted() != null, HotVehicleChange::getIsDeleted, bo.getIsDeleted());
        return lqw;
    }

    /**
     * 新增车辆变更记录
     *
     * @param bo 车辆变更记录
     * @return 是否新增成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(HotVehicleChangeBo bo) {
        HotVehicleChange add = MapstructUtils.convert(bo, HotVehicleChange.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
            syncVehicleStatusAndDriverBinding(bo);
        }
        return flag;
    }

    /**
     * 修改车辆变更记录
     *
     * @param bo 车辆变更记录
     * @return 是否修改成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(HotVehicleChangeBo bo) {
        HotVehicleChange update = MapstructUtils.convert(bo, HotVehicleChange.class);
        validEntityBeforeSave(update);
        boolean flag = baseMapper.updateById(update) > 0;
        if (flag) {
            syncVehicleStatusAndDriverBinding(bo);
        }
        return flag;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HotVehicleChange entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    private void syncVehicleStatusAndDriverBinding(HotVehicleChangeBo bo) {
        String vehicleId = String.valueOf(bo.getVehicleId());
        HotVehicle vehicle = vehicleMapper.selectById(vehicleId);
        if (vehicle == null) {
            throw new ServiceException("车辆不存在，无法同步运营状态");
        }
        Long operationStatus = Long.valueOf(bo.getChangeItem());
        Long vehicleStatus = "1".equals(bo.getChangeItem()) ? 1L : 2L;
        boolean needUnbindDriver = CLEAR_DRIVER_OPERATION_STATUS.contains(bo.getChangeItem());

        LambdaUpdateWrapper<HotVehicle> updateWrapper = new LambdaUpdateWrapper<HotVehicle>()
                .set(HotVehicle::getOperationStatus, operationStatus)
                .set(HotVehicle::getVehicleStatus, vehicleStatus)
                .eq(HotVehicle::getId, vehicleId)
                .eq(HotVehicle::getCompanyId, bo.getCompanyId());
        if (needUnbindDriver) {
            updateWrapper.set(HotVehicle::getCurrentDriver, null);
        }
        vehicleMapper.update(null, updateWrapper);

        if (needUnbindDriver && StringUtils.isNotBlank(vehicle.getCurrentDriver())) {
            List<String> driverIds = Arrays.stream(vehicle.getCurrentDriver().split(","))
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.toList());
            if (!driverIds.isEmpty()) {
                for (String driverId : driverIds) {
                    recalculateDriverVehicleRelations(driverId, bo.getCompanyId());
                }
            }
        }
    }

    private void recalculateDriverVehicleRelations(String driverId, Long companyId) {
        if (StringUtils.isBlank(driverId) || companyId == null) {
            return;
        }
        List<HotVehicle> vehicles = vehicleMapper.selectList(Wrappers.<HotVehicle>lambdaQuery()
                .eq(HotVehicle::getCompanyId, companyId)
                .eq(HotVehicle::getIsDeleted, 0L));
        List<String> vehicleIds = new ArrayList<>();
        List<HotVehicle> boundVehicles = new ArrayList<>();
        for (HotVehicle item : vehicles) {
            List<String> currentDrivers = Arrays.stream(StringUtils.defaultString(item.getCurrentDriver()).split(","))
                    .map(String::trim)
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.toList());
            if (!currentDrivers.contains(driverId)) {
                continue;
            }
            boundVehicles.add(item);
            vehicleIds.add(item.getId());
        }
        HotDriver driver = driverMapper.selectById(driverId);
        String primaryVehicleId = resolvePrimaryVehicleId(driver, vehicleIds);
        String primaryPlateNumber = resolvePrimaryPlateNumber(primaryVehicleId, boundVehicles);
        driverMapper.update(null, new LambdaUpdateWrapper<HotDriver>()
                .set(HotDriver::getVehicleId, primaryVehicleId)
                .set(HotDriver::getVehicleIds, joinCsv(vehicleIds))
                .set(HotDriver::getPlateNumber, primaryPlateNumber)
                .eq(HotDriver::getId, driverId)
                .eq(HotDriver::getCompanyId, companyId));
    }

    private String joinCsv(Collection<String> values) {
        if (values == null || values.isEmpty()) {
            return null;
        }
        return values.stream()
                .filter(StringUtils::isNotBlank)
                .distinct()
                .collect(Collectors.joining(","));
    }

    private String resolvePrimaryVehicleId(HotDriver driver, Collection<String> boundVehicleIds) {
        if (boundVehicleIds == null || boundVehicleIds.isEmpty()) {
            return null;
        }
        if (driver != null && StringUtils.isNotBlank(driver.getVehicleId()) && boundVehicleIds.contains(driver.getVehicleId())) {
            return driver.getVehicleId();
        }
        return boundVehicleIds.stream()
                .filter(StringUtils::isNotBlank)
                .findFirst()
                .orElse(null);
    }

    private String resolvePrimaryPlateNumber(String primaryVehicleId, Collection<HotVehicle> boundVehicles) {
        if (StringUtils.isBlank(primaryVehicleId) || boundVehicles == null || boundVehicles.isEmpty()) {
            return null;
        }
        return boundVehicles.stream()
                .filter(vehicle -> StringUtils.equals(primaryVehicleId, vehicle.getId()))
                .map(HotVehicle::getPlateNumber)
                .filter(StringUtils::isNotBlank)
                .findFirst()
                .orElse(null);
    }

    /**
     * 校验并批量删除车辆变更记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }
}
