<template>
  <Dialog custom-show type="sm" :title="title" confirm-text="关联事件" confirm-class="common-btn-danger" @close="closeDialog" @confirm="submitEvent">
    <el-form ref="eventFormRef" :model="form" :rules="rules" label-width="190px">
      <el-form-item label="灾害事件" prop="event_title">
        <el-select
          v-model="form.event_title"
          placeholder="请选择事件"
          class="custom-select"
          size="large"
          popper-class="custom-select-popper"
          :teleported="false"
          clearable
          @change="selectEvent"
        >
          <el-option v-for="item in events" :key="item.event_id" :label="item.event_title" :value="item.event_title"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, toRefs, watch, onMounted } from 'vue';
import { editEvent, registeredEvent, getEventDetail, assEvent } from '@/api/duty/eventing';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';

const proxy = getCurrentInstance()?.proxy;
const router = useRouter();
const eventFormRef = ref();
const events = ref([]);
const route = useRoute();
const urlParams = new URLSearchParams(route.query);
const address = urlParams.get('address') || '';
const latitude = urlParams.get('latitude') || '';
const longitude = urlParams.get('longitude') || '';

interface Props {
  modelValue: boolean;
  eventId: string;
  title: string;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  eventId: '',
  title: ''
});

const emit = defineEmits(['update:modelValue', 'update:event-title']);

// 表单初始数据
const initFormData = {
  event_title: '', // 事件标题
  event_id: '',
  event_type: '', // 事件类型
  event_level: '', // 事件等级
  event_status: '0', // 事件状态
  address: address, // 地址
  latitude: latitude, // 纬度
  longitude: longitude // 经度
};

// 表单数据
const data = reactive({
  form: { ...initFormData },
  rules: {
    event_title: [{ required: true, message: '事件标题不能为空', trigger: 'blur' }]
  }
});

const { form, rules } = toRefs(data);

// 获取事件详情
const fetchEventDetail = async (id: string) => {
  try {
    const response = await getEventDetail({ event_id: id });
    if (response && response.data) {
      form.value = response.data;
    }
    console.log('Event detail:', form.value);
  } catch (error) {
    console.error('Failed to fetch event detail:', error);
  }
};

// 获取注册的事件列表
const fetchEvents = async () => {
  try {
    const response = await registeredEvent({});
    if (response && response.data && Array.isArray(response.data)) {
      events.value = response.data;
    }
  } catch (error) {
    console.error('Failed to fetch events:', error);
  }
};

// 初始化事件列表
onMounted(() => {
  fetchEvents();
});

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  async (newVal) => {
    if (newVal) {
      if (props.eventId) {
        await fetchEventDetail(props.eventId);
      } else {
        form.value = { ...initFormData };
        eventFormRef.value?.resetFields();
      }
    }
  },
  {
    immediate: true
  }
);

// 关闭对话框
const closeDialog = () => {
  emit('update:modelValue', false);
  if (eventFormRef.value) {
    eventFormRef.value.resetFields(); // 仅重置表单验证状态
  }
};

// 提交事件信息
const submitEvent = async () => {
  if (!form.value.event_title) {
    proxy?.$modal.msgError('请先选择一个事件');
    return;
  }
  try {
    // 关联事件信息
    const associateParams = {
      temp_event_id: props.eventId, // 页面上的临时事件ID
      event_id: form.value.event_id // 用户选择的事件ID
    };
    await assEvent(associateParams);
    console.log('Event associated successfully.');
    // 更新 modelValue 状态以关闭对话框
    emit('update:modelValue', false);
    // 发送事件名称到父组件
    emit('update:event-title', form.value.event_title);
    // 执行其他操作，如更新页面数据等
    refreshPageData();
  } catch (error) {
    console.error('Failed to associate event:', error);
    proxy?.$modal.msgError('提交表单失败，请检查您的输入');
  }
};

// 示例：更新页面数据的方法
const refreshPageData = () => {
  // 这里可以放置更新页面数据的逻辑
  console.log('页面数据已更新');
};

// 选择事件
const selectEvent = (eventTitle) => {
  const selectedItem = events.value.find((event) => event.event_title === eventTitle);
  if (selectedItem) {
    form.value.event_id = selectedItem.event_id; // 保存所选事件的ID
    form.value.event_title = selectedItem.event_title; // 确保事件名称被正确设置
    console.log('Selected Event ID:', form.value.event_id);
    console.log('Selected Event Title:', form.value.event_title);
  }
};
</script>

<style lang="scss" scoped>
.dialog-footer {
  height: 150px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
