import { ref, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { showImagePreview, showToast, showDialog } from 'vant';
import api from '../../api';

export function useActivityDetail() {
  const route = useRoute();
  const activity = ref({});
  const photos = ref([]);
  const videos = ref([]);
  const sponsors = ref([]);
  const prizes = ref([]);
  const registrations = ref([]);
  const expenses = ref([]);
  const venueImages = ref([]);
  const userMedia = ref([]);
  const showMapPopup = ref(false);
  const showLoginDialog = ref(false);
  const showExpenseVideoPopup = ref(false);
  const currentExpenseVideo = ref('');
  const loginForm = ref({ phone: '', carNumber: '' });
  const expandedTimelineIndex = ref(null);
  const expandedGameId = ref(null);
  const carLetter = ref('');
  const carDigits = ref('');
  const userRegistration = ref(null);
  const showPrizeSourcePopup = ref(false);
  const currentPrize = ref(null);
  let map = null;

  const handleLetterInput = (e) => {
    const value = e.target.value.toUpperCase().replace(/[^A-Z]/g, '');
    carLetter.value = value;
    loginForm.value.carNumber = value + carDigits.value;
    
    if (value.length === 1) {
      e.target.nextElementSibling?.nextElementSibling?.focus();
    }
  };

  const handleDigitsInput = (e) => {
    const value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '');
    carDigits.value = value;
    loginForm.value.carNumber = carLetter.value + value;
  };

  const toggleTimeline = (index) => {
    expandedTimelineIndex.value = expandedTimelineIndex.value === index ? null : index;
    expandedGameId.value = null;
  };

  const toggleGame = (gameId) => {
    expandedGameId.value = expandedGameId.value === gameId ? null : gameId;
  };

  const totalExpense = computed(() => {
    return expenses.value.reduce((sum, e) => sum + parseFloat(e.amount), 0).toFixed(2);
  });

  const totalPeople = computed(() => {
    return registrations.value
      .filter(r => r.status === 'approved')
      .reduce((sum, r) => sum + (r.peopleCount || 1), 0);
  });

  const isApproved = computed(() => {
    return userRegistration.value && userRegistration.value.status === 'approved';
  });

  const hasRegistered = computed(() => {
    return userRegistration.value !== null;
  });

  const prizesByLevel = computed(() => {
    const levels = ['特等奖', '一等奖', '二等奖', '三等奖', '四等奖', '参与奖', '伴手礼'];
    return levels.map(level => ({
      level,
      items: prizes.value.filter(p => p.level === level).sort((a, b) => a.sortOrder - b.sortOrder)
    })).filter(group => group.items.length > 0);
  });

  const showPrizeSource = (prize) => {
    if (prize.source === 'purchase') return;
    currentPrize.value = prize;
    showPrizeSourcePopup.value = true;
  };

  const showSponsorInfo = (prize) => {
    if (!prize.sponsor) return;
    
    let sourceText = '';
    if (prize.source === 'member') {
      sourceText = '群友赞助';
    } else if (prize.source === 'sponsor') {
      sourceText = '赞助商提供';
    } else {
      sourceText = '礼品来源';
    }
    
    showDialog({
      title: sourceText,
      message: prize.sponsor,
      confirmButtonText: '知道了',
      confirmButtonColor: '#FF6700',
      className: 'sponsor-dialog'
    });
  };

  const loadData = async () => {
    const { data } = await api.getActivity(route.params.id);
    activity.value = data.activity;
    
    const allMedia = data.photos || [];
    photos.value = allMedia.filter(m => m.type === 'image');
    videos.value = allMedia.filter(m => m.type === 'video');
    
    sponsors.value = data.sponsors;
    prizes.value = data.prizes || [];
    expenses.value = data.expenses || [];
    venueImages.value = data.venueImages || [];
    
    const { data: regs } = await api.getActivityRegistrations(route.params.id);
    registrations.value = regs;
    
    // 检查本地存储的报名信息
    const savedReg = localStorage.getItem(`user_reg_${route.params.id}`);
    if (savedReg) {
      const regData = JSON.parse(savedReg);
      // 验证报名是否还存在
      try {
        const { data: verifyData } = await api.getRegistration(regData.id);
        userRegistration.value = verifyData;
        // 更新本地存储
        localStorage.setItem(`user_reg_${route.params.id}`, JSON.stringify(verifyData));
      } catch (error) {
        // 报名不存在，清理本地存储
        if (error.response?.status === 404) {
          localStorage.removeItem(`user_reg_${route.params.id}`);
          userRegistration.value = null;
        } else {
          // 其他错误，保留本地数据
          userRegistration.value = regData;
        }
      }
    }
  };

  const formatDate = (date) => {
    if (!date) return '';
    
    // 处理带时区的时间格式 "2026-04-19 06:00:00.000 +00:00"
    let dateStr = date;
    if (typeof date === 'string') {
      // 移除时区部分，只保留日期时间
      dateStr = date.replace(/\s*\+\d{2}:\d{2}$/, '').replace(/\.\d{3}/, '');
    }
    
    const d = new Date(dateStr);
    if (isNaN(d.getTime())) return '';
    
    return d.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  };

  const previewImage = (url) => {
    showImagePreview([url]);
  };

  const playExpenseVideo = (url) => {
    currentExpenseVideo.value = url;
    showExpenseVideoPopup.value = true;
  };

  const showMap = () => {
    if (!activity.value.locationLat || !activity.value.locationLng) {
      showToast('暂无地图信息');
      return;
    }
    showMapPopup.value = true;
    setTimeout(() => {
      initMap();
    }, 300);
  };

  const initMap = async () => {
    try {
      const AMap = await window.loadAMap();
      
      if (map) {
        map.destroy();
      }
      
      const center = [activity.value.locationLng, activity.value.locationLat];
      map = new AMap.Map('amap-container', { zoom: 15, center });
      new AMap.Marker({ position: center, map, title: activity.value.location });
    } catch (e) {
      console.error('地图加载失败:', e);
      showToast('地图加载失败: ' + e.message);
    }
  };

  const uploadUserMedia = async (files) => {
    if (!isApproved.value) {
      showToast('请先登录并等待审核通过');
      return;
    }
    
    const loadingToast = showToast({
      type: 'loading',
      message: '上传中...',
      forbidClick: true,
      duration: 0
    });
    
    try {
      const formData = new FormData();
      formData.append('uploadedBy', userRegistration.value.name);
      
      if (Array.isArray(files)) {
        files.forEach(file => formData.append('photos', file.file));
      } else {
        formData.append('photos', files.file);
      }
      
      await api.uploadUserPhotos(route.params.id, formData);
      showToast('上传成功，等待审核');
      userMedia.value = [];
    } catch (error) {
      showToast('上传失败');
    } finally {
      loadingToast.clear();
    }
  };

  const handleLogin = () => {
    showLoginDialog.value = true;
  };

  const submitLogin = async () => {
    if (!loginForm.value.phone || !loginForm.value.carNumber) {
      showToast('请输入手机号和车牌号');
      return;
    }
    
    try {
      const carNumberWithPrefix = `闽${loginForm.value.carNumber}`;
      
      const { data } = await api.verifyUser(route.params.id, {
        phone: loginForm.value.phone,
        carNumber: carNumberWithPrefix
      });
      
      userRegistration.value = data.registration;
      localStorage.setItem(`user_reg_${route.params.id}`, JSON.stringify(data.registration));
      
      showLoginDialog.value = false;
      
      if (data.registration.status === 'approved') {
        showToast('登录成功');
      } else if (data.registration.status === 'pending') {
        showToast('您的报名正在审核中');
      } else {
        showToast('您的报名未通过审核');
      }
    } catch (error) {
      // 如果报名不存在（被删除），清理本地存储
      if (error.response?.status === 404 || error.response?.data?.error?.includes('不存在')) {
        localStorage.removeItem(`user_reg_${route.params.id}`);
        userRegistration.value = null;
        showToast('报名信息不存在，请重新报名');
      } else {
        showToast(error.response?.data?.error || '验证失败');
      }
    }
  };

  const handleShare = () => {
    const shareUrl = `${window.location.origin}/share/${route.params.id}`;
    
    if (navigator.share) {
      navigator.share({
        title: activity.value.title,
        text: `${activity.value.title} - 泉友米车友会`,
        url: shareUrl
      }).catch(() => {
        copyShareLink(shareUrl);
      });
    } else {
      copyShareLink(shareUrl);
    }
  };

  const copyShareLink = (url) => {
    navigator.clipboard.writeText(url).then(() => {
      showToast('分享链接已复制');
    }).catch(() => {
      showToast('复制失败，请手动复制：' + url);
    });
  };

  onMounted(loadData);

  return {
    activity,
    photos,
    videos,
    sponsors,
    prizes,
    prizesByLevel,
    registrations,
    expenses,
    venueImages,
    userMedia,
    showMapPopup,
    showLoginDialog,
    showExpenseVideoPopup,
    showPrizeSourcePopup,
    currentExpenseVideo,
    currentPrize,
    loginForm,
    carLetter,
    carDigits,
    userRegistration,
    expandedTimelineIndex,
    expandedGameId,
    totalExpense,
    totalPeople,
    isApproved,
    hasRegistered,
    formatDate,
    previewImage,
    playExpenseVideo,
    showMap,
    uploadUserMedia,
    handleLogin,
    handleLetterInput,
    handleDigitsInput,
    submitLogin,
    handleShare,
    toggleTimeline,
    toggleGame,
    showPrizeSource,
    showSponsorInfo
  };
}
