import { ref } from 'vue';
import { showToast, showConfirmDialog } from 'vant';
import api from '../../api';

export function usePrizeManage(activityId) {
  const prizes = ref([]);
  const showPrizeForm = ref(false);
  const showLevelPicker = ref(false);
  const showSourcePicker = ref(false);
  const prizeImage = ref([]);
  const prizeForm = ref({
    id: null,
    activityId: activityId.value,
    name: '',
    level: '',
    description: '',
    quantity: 1,
    sortOrder: 0,
    source: 'purchase',
    sponsor: '',
    image: null
  });

  const prizeLevels = ['特等奖', '一等奖', '二等奖', '三等奖', '四等奖', '参与奖', '伴手礼'];

  const loadPrizes = async () => {
    try {
      const { data } = await api.getActivity(activityId.value);
      prizes.value = data.prizes || [];
    } catch (error) {
      console.error('加载奖品失败:', error);
    }
  };

  const editPrize = (prize) => {
    prizeForm.value = {
      id: prize.id,
      activityId: activityId.value,
      name: prize.name,
      level: prize.level,
      description: prize.description || '',
      quantity: prize.quantity,
      sortOrder: prize.sortOrder || 0,
      source: prize.source || 'purchase',
      sponsor: prize.sponsor || '',
      image: prize.image
    };
    // 回显图片 - 需要使用完整URL
    if (prize.image) {
      const imageUrl = prize.image.startsWith('http') ? prize.image : 
        (import.meta.env.DEV ? `http://localhost:3000${prize.image}` : `https://mi.xyvan.cn${prize.image}`);
      prizeImage.value = [{ url: imageUrl }];
    } else {
      prizeImage.value = [];
    }
    showPrizeForm.value = true;
  };

  const onPrizeImageRead = (file) => {
    prizeForm.value.imageFile = file.file;
  };

  const selectLevel = (level) => {
    prizeForm.value.level = level;
    showLevelPicker.value = false;
  };

  const selectSource = (source) => {
    prizeForm.value.source = source;
    if (source === 'purchase') {
      prizeForm.value.sponsor = '';
    }
    showSourcePicker.value = false;
  };

  const submitPrize = async () => {
    if (!prizeForm.value.name || !prizeForm.value.level || !prizeForm.value.source) {
      showToast('请填写必填项');
      return;
    }

    if (prizeForm.value.source !== 'purchase' && !prizeForm.value.sponsor) {
      showToast('请填写赞助者名称');
      return;
    }

    const loadingToast = showToast({
      type: 'loading',
      message: '保存中...',
      forbidClick: true,
      duration: 0
    });

    try {
      const formData = new FormData();
      formData.append('activityId', activityId.value);
      formData.append('name', prizeForm.value.name);
      formData.append('level', prizeForm.value.level);
      formData.append('description', prizeForm.value.description);
      formData.append('quantity', prizeForm.value.quantity);
      formData.append('sortOrder', prizeForm.value.sortOrder);
      formData.append('source', prizeForm.value.source);
      if (prizeForm.value.sponsor) {
        formData.append('sponsor', prizeForm.value.sponsor);
      }

      if (prizeForm.value.imageFile) {
        formData.append('image', prizeForm.value.imageFile);
      } else if (prizeImage.value.length === 0 && prizeForm.value.image) {
        // 用户删除了图片
        formData.append('removeImage', 'true');
      }

      if (prizeForm.value.id) {
        await api.updatePrize(prizeForm.value.id, formData);
      } else {
        await api.addPrize(formData);
      }

      showToast('保存成功');
      showPrizeForm.value = false;
      resetPrizeForm();
      loadPrizes();
    } catch (error) {
      showToast('保存失败');
      console.error('保存奖品失败:', error);
    } finally {
      loadingToast.clear();
    }
  };

  const deletePrizeItem = async (id) => {
    try {
      await showConfirmDialog({
        title: '确认删除',
        message: '确定要删除这个奖品吗？'
      });

      await api.deletePrize(id);
      showToast('删除成功');
      await loadPrizes();
    } catch (error) {
      if (error !== 'cancel') {
        showToast('删除失败');
      }
    }
  };

  const resetPrizeForm = () => {
    prizeForm.value = {
      id: null,
      activityId: activityId.value,
      name: '',
      level: '',
      description: '',
      quantity: 1,
      sortOrder: 0,
      source: 'purchase',
      sponsor: '',
      image: null
    };
    prizeImage.value = [];
  };

  return {
    prizes,
    showPrizeForm,
    showLevelPicker,
    showSourcePicker,
    prizeImage,
    prizeForm,
    prizeLevels,
    loadPrizes,
    editPrize,
    onPrizeImageRead,
    selectLevel,
    selectSource,
    submitPrize,
    deletePrizeItem,
    resetPrizeForm
  };
}
