import { ref, computed, watch } from 'vue';
import request from '@/utils/request';
import car1 from '../assets/images/car1.png';
import car2 from '../assets/images/car2.png';
import car3 from '../assets/images/car3.png';
import car4 from '../assets/images/car4.png';
import useVehicleDisplayStore from '@/store/modules/vehicleDisplay';

export function useVehicle() {
  // 车辆数据
  const vehicleData = ref([]);
  const vehicleDisplayStore = useVehicleDisplayStore();

  

  // 过滤条件
  const filters = ref({
    searchText: '',
    vehicleType: '',
    vehicleStatus: ''
  });

  const vehicleStats = ref([
    { title: '车辆总数', count: vehicleData.value.length },
    { title: '在线', count: vehicleData.value.filter(v => v.status === '在线').length },
    { title: '任务中', count: vehicleData.value.filter(v => v.routeStatus === '任务中').length },
    { title: '故障', count: vehicleData.value.filter(v => v.status === '故障').length },
    { title: '离线', count: vehicleData.value.filter(v => v.status === '离线').length }
  ]);

  async function fetchVehicleStats() {
    try {
      const res = await request({
        url: '/api/vehicle-manager/vehicles/summary',
        method: 'get'
      });
      const data = res && res.data !== undefined ? res.data : res || {};
      const inTask = vehicleData.value.filter(v => v.routeStatus === '任务中').length;
      vehicleStats.value = [
        { title: '车辆总数', count: Number(data.totalCount ?? vehicleData.value.length) },
        { title: '在线', count: Number(data.onlineCount ?? 0) },
        { title: '任务中', count: inTask },
        { title: '故障', count: Number(data.faultCount ?? 0) },
        { title: '离线', count: Number(data.offlineCount ?? 0) }
      ];
    } catch (e) {
      vehicleStats.value = [
        { title: '车辆总数', count: vehicleData.value.length },
        { title: '在线', count: vehicleData.value.filter(v => v.status === '在线').length },
        { title: '任务中', count: vehicleData.value.filter(v => v.routeStatus === '任务中').length },
        { title: '故障', count: vehicleData.value.filter(v => v.status === '故障').length },
        { title: '离线', count: vehicleData.value.filter(v => v.status === '离线').length }
      ];
    }
  }

  fetchVehicleStats();

  function mapStatus(s, isFault) {
    if (s === 'fault' || isFault) return '故障';
    if (s === 'offline') return '离线';
    if (s === 'online') return '在线';
    return '在线';
  }

  function formatTime(ms) {
    if (!ms) return '--';
    const d = new Date(Number(ms));
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hh = String(d.getHours()).padStart(2, '0');
    const mm = String(d.getMinutes()).padStart(2, '0');
    const ss = String(d.getSeconds()).padStart(2, '0');
    return `${y}-${m}-${day} ${hh}:${mm}:${ss}`;
  }

  function coalesce(...vals) {
    for (const v of vals) {
      if (v !== undefined && v !== null) return v;
    }
    return undefined;
  }

  function formatLocation(row) {
    const p = row?.position || {};
    const lon = coalesce(p?.y, p?.longitude, row?.longitude, row?.lng, row?.lon, row?.x);
    const lat = coalesce(p?.x, p?.latitude, row?.latitude, row?.lat, row?.y);
    if (lon === undefined || lat === undefined) return '--';
    const ln = Number(lon);
    const lt = Number(lat);
    const lonStr = Number.isFinite(ln) ? ln : lon;
    const latStr = Number.isFinite(lt) ? lt : lat;
    return `经度${lonStr},纬度${latStr}`;
  }

  function mapRow(row) {
    const loc = formatLocation(row);
    const route = row?.currentTask ? '任务中' : '待命中';
    const status = mapStatus(row?.status, row?.isFault);
    const socVal = row?.batteryLevel;
    const socStr = typeof socVal === 'number' ? `${Math.round(socVal)}%` : (socVal ?? '--');
    const id = row?.vehicleId;
    const overrideType = vehicleDisplayStore.getVehicleTypeOverride(id);
    const typeText = overrideType || row?.vehicleType || '';
    return {
      id,
      carId: id,
      type: typeText,
      brand: '',
      organization: '',
      routeStatus: route,
      status,
      chargeStatus: '',
      voltage: '',
      current: '',
      soc: socStr,
      lastTime: formatTime(row?.lastSeenAt),
      batteryLevel: row?.batteryLevel ?? '--',
      location: loc,
      contactPhone: '',
      number: row?.isFault ? 1 : 0
    };
  }

  function createVirtualVehicle(id, overrideType) {
    const typeText = overrideType || ''
    return {
      id,
      carId: id,
      type: typeText,
      brand: '',
      organization: '',
      routeStatus: '待命中',
      status: '在线',
      chargeStatus: '',
      voltage: '',
      current: '',
      soc: '--',
      lastTime: '--',
      batteryLevel: '--',
      location: '--',
      contactPhone: '',
      number: 0
    }
  }

  function mergeVirtualVehicles(baseList) {
    const base = Array.isArray(baseList) ? baseList : []
    const seen = new Set(base.map((v) => v?.id).filter(Boolean))
    const overrides = vehicleDisplayStore.vehicleTypeOverrides || {}
    const extra = []
    Object.keys(overrides).forEach((id) => {
      if (!id || seen.has(id)) return
      const t = String(overrides[id] || '').toUpperCase()
      if (t !== 'UNMANNED_VEHICLE' && t !== 'SPECIAL_VEHICLE') return
      extra.push(createVirtualVehicle(id, overrides[id]))
    })
    return [...base, ...extra]
  }

  async function fetchVehicles(params = { pageNum: 1, pageSize: 100 }) {
    try {
      const res = await request({
        url: '/api/vehicle-manager/vehicles',
        method: 'get',
        params
      });
      const data = res && res.data !== undefined ? res.data : res || {};
      const rows = data?.rows || data?.data?.rows || [];
      vehicleData.value = mergeVirtualVehicles(rows.map(mapRow));
    } catch (e) {
      vehicleData.value = mergeVirtualVehicles([]);
    }
  }

  fetchVehicles();

  watch(
    () => vehicleDisplayStore.vehicleTypeOverrides,
    () => {
      vehicleData.value = mergeVirtualVehicles(vehicleData.value)
    },
    { deep: true }
  )

  // 筛选后的数据
  const filteredVehicleData = computed(() => {
    let filtered = [...vehicleData.value];
    
    if (filters.value.searchText) {
      const searchText = filters.value.searchText.toLowerCase();
      filtered = filtered.filter(item => 
        item.id?.toString().toLowerCase().includes(searchText) ||
        item.carId?.toLowerCase().includes(searchText) ||
        item.type?.toLowerCase().includes(searchText) ||
        item.organization?.toLowerCase().includes(searchText)
      );
    }
    
    if (filters.value.vehicleStatus) {
      filtered = filtered.filter(item => item.status === filters.value.vehicleStatus);
    }
    
    if (filters.value.vehicleType) {
      filtered = filtered.filter(item => item.type === filters.value.vehicleType);
    }
    
    return filtered;
  });

  // 获取行驶状态对应的类型
  function getRouteStatusType(status) {
    switch (status) {
      case '任务中':
        return 'success';
      case '待命中':
        return '';
      case '充电中':
        return 'warning';
      case '等待中':
        return 'info';
      default:
        return '';
    }
  }

  // 更新过滤条件
  function updateFilters(newFilters) {
    filters.value = { ...filters.value, ...newFilters };
  }

  // 重置过滤条件
  function resetFilters() {
    filters.value = {
      searchText: '',
      vehicleType: '',
      vehicleStatus: ''
    };
  }

  // 导出数据
  function exportData() {
    // 实现导出逻辑
    console.log('导出数据', filteredVehicleData.value);
  }

  return {
    vehicleData,
    vehicleStats,
    fetchVehicleStats,
    fetchVehicles,
    filters,
    filteredVehicleData,
    getRouteStatusType,
    updateFilters,
    resetFilters,
    exportData
  };
} 
