<template xmlns="">
  <div class="app-container">
    <transition name="fade">
      <div v-show="showSearch" class="mb-[20px]">
        <el-form ref="queryFormRef" :model="queryParams">
          <el-row :gutter="10">
            <!-- 第一行 -->
            <el-col :span="6">
              <el-form-item label="事件类型" prop="eventType">
                <el-select v-model="queryParams.eventType" placeholder="全部" clearable>
                  <el-option label="全部" value=""></el-option>
                  <el-option
                    v-for="item in data.eventTypeSelection"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="事件等级" prop="eventLevel">
                <el-select v-model="queryParams.eventLevel" placeholder="全部" clearable>
                  <el-option label="全部" value=""></el-option>
                  <el-option
                    v-for="item in data.eventLevelSelection"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="事件状态" prop="eventStatus">
                <el-select v-model="queryParams.eventStatus" placeholder="全部" clearable>
                  <el-option label="全部" value=""></el-option>
                  <el-option
                    v-for="item in data.eventStatusSelection"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="行政区划" prop="regionCode">
                <el-select v-model="queryParams.regionCode" placeholder="全部" clearable>
                  <el-option label="全部" value=""></el-option>
                  <el-option v-for="item in data.regionSelection" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10" class="mt-[10px]">
            <el-col :span="6">
              <el-form-item label="事发时间" prop="eventTime">
                <el-date-picker v-model="queryParams.eventTime" type="datetime" placeholder="选择事发时间"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item>
                <el-input v-model="queryParams.subject" placeholder="请输入事件标题/事件地点" clearable @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-row>
        </el-form>
      </div>
    </transition>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增事件</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete(selectedRow)">删除事件 </el-button>
      </el-col>
    </el-row>

    <!-- 表格组w件 -->
    <el-table v-loading="loading" :data="eventList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="事件编号" align="center" prop="eventId" />
      <el-table-column label="事件标题" align="center" prop="eventTitle" />
      <el-table-column label="事件类型" align="center" prop="eventType" />
      <el-table-column label="事件等级" align="center" prop="eventLevel" />
      <el-table-column label="事件地点" align="center" prop="address" />
      <el-table-column label="事件状态" align="center" prop="eventStatus" />
      <el-table-column label="事件时间" align="center" prop="eventTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="查看" placement="top">
            <el-button link type="primary" icon="View" @click="handleView(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="编辑" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
          </el-tooltip>
          <el-tooltip content="关闭事件" placement="top">
            <el-button link type="primary" icon="Close" @click="handleClose(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />

    <!-- 新增/修改弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="eventFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="事件标题" prop="eventTitle">
          <el-input v-model="form.eventTitle" placeholder="请输入事件标题" />
        </el-form-item>
        <el-form-item label="事件类型" prop="eventType">
          <el-select v-model="form.eventType" placeholder="请选择事件类型" clearable>
            <el-option v-for="item in data.eventTypeSelection" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="事件等级" prop="eventLevel">
          <el-select v-model="form.eventLevel" placeholder="请选择事件等级" clearable>
            <el-option v-for="item in data.eventLevelSelection" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="事件状态" prop="eventStatus">
          <el-select v-model="form.eventStatus" placeholder="请选择事件状态" clearable>
            <el-option v-for="item in data.eventStatusSelection" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="事件地点" prop="address">
          <el-button type="primary" @click="openMapDialog">地图定位</el-button>
          <el-input v-model="form.address" placeholder="请输入事件地点" readonly />
        </el-form-item>
        <el-form-item label="事发时间" prop="eventTime">
          <el-date-picker v-model="form.eventTime" type="datetime" placeholder="选择事发时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="上报时间" prop="reportTime">
          <el-date-picker v-model="form.reportTime" type="datetime" placeholder="选择上报时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="伤亡情况">
          <el-row :gutter="10">
            <el-col :span="6">
              <el-input v-model="form.deceased" placeholder="死亡">
                <template #suffix>人</template>
              </el-input>
            </el-col>
            <el-col :span="6">
              <el-input v-model="form.injured" placeholder="受伤">
                <template #suffix>人</template>
              </el-input>
            </el-col>
            <el-col :span="6">
              <el-input v-model="form.missing" placeholder="失踪">
                <template #suffix>人</template>
              </el-input>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="事件来源" prop="eventSource">
          <el-input v-model="form.eventSource" placeholder="请输入事件来源" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 地图弹窗 -->
    <el-dialog v-model="mapDialogVisible" title="地图定位" width="600px">
      <company-map v-model:visible="mapDialogVisible" :address="form.address" @change="handleMapChange"></company-map>
      <template #footer>
        <el-button @click="mapDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmMapLocation">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getDicts } from '@/api/system/dict/data';

const router = useRouter();
const eventList = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const selectedRow = ref(null);

const queryFormRef = ref();
const eventFormRef = ref();

const dialog = reactive({
  visible: false,
  title: ''
});

const initFormData = {
  eventId: '',
  eventTitle: '',
  eventType: '',
  eventLevel: '',
  eventStatus: '',
  address: '',
  eventTime: '',
  reportTime: '',
  deceased: '',
  injured: '',
  missing: '',
  eventSource: ''
};

const data = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    eventType: '',
    eventLevel: '',
    eventStatus: '',
    eventTime: '',
    regionCode: '',
    subject: ''
  },
  rules: {
    eventTitle: [{ required: true, message: '事件标题不能为空', trigger: 'blur' }],
    eventType: [{ required: true, message: '事件类型不能为空', trigger: 'blur' }],
    eventLevel: [{ required: true, message: '事件等级不能为空', trigger: 'blur' }],
    eventStatus: [{ required: true, message: '事件状态不能为空', trigger: 'blur' }],
    address: [{ required: true, message: '事件地点不能为空', trigger: 'blur' }],
    eventTime: [{ required: true, message: '事发时间不能为空', trigger: 'blur' }],
    reportTime: [{ required: true, message: '上报时间不能为空', trigger: 'blur' }],
    eventSource: [{ required: true, message: '事件来源不能为空', trigger: 'blur' }]
  },
  eventTypeSelection: [],
  eventLevelSelection: [],
  eventStatusSelection: [],
  regionSelection: []
});

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

const getList = async () => {
  loading.value = true;
  eventList.value = [
    {
      'eventId': 'YJSJ000000001',
      'eventTitle': 'XXX公交站西侧出现积水倒灌情况',
      'eventType': '0', //字典（事件类型：0自然灾害、1事故灾害、2公共卫生事件、3社会安全事件）
      'eventLevel': '0', //字典（事件等级：0其他，1一般，2较大，3重大，4特别重大）
      'eventStatus': '0', //字典（事件状态：0已登记，1指挥中，2指挥结束，3已关闭）
      'latitude': 123.123, //纬度
      'longitude': 345.456, //经度
      'address': 'XXX道路左侧路面',
      'eventTime': '2023-03-01 17:18'
    }
  ];
  total.value = 1;
  // try {
  //   const response = await fetchEvents(queryParams.value);
  //   const { data, total } = response;
  //   eventList.value = data;
  //   total.value = total;
  // } catch (error) {
  //   ElMessage.error('获取数据失败');
  // } finally {
    loading.value = false;
  // }
};

const fetchEvents = async (params) => {
  // 假设后端接口为 /api/events
  const response = await fetch('/api/events', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(params)
  });
  const result = await response.json();
  if (response.ok) {
    return result;
  } else {
    throw new Error(result.message || '获取事件列表失败');
  }
};

const cancel = () => {
  reset();
  dialog.visible = false;
};

const reset = () => {
  form.value = { ...initFormData };
  eventFormRef.value?.resetFields();
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryParams.value = { pageNum: 1, pageSize: 10, eventType: '', eventLevel: '', eventStatus: '', eventTime: '', regionCode: '', subject: '' };
  handleQuery();
};

const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.eventId);
  selectedRow.value = selection.length === 1 ? selection[0] : null;
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增事件';
};

// 修改事件
const handleUpdate = (row) => {
  if (row) {
    reset();
    Object.assign(form.value, row);
    dialog.visible = true;
    dialog.title = '修改事件';
  }
};

// 提交表单
const submitForm = () => {
  eventFormRef.value?.validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      setTimeout(() => {
        if (form.value.eventId) {
          // 更新逻辑
        } else {
          // 添加逻辑
        }
        buttonLoading.value = false;
        dialog.visible = false;
        getList();
      }, 500);
    }
  });
};

const handleDelete = (row) => {
  if (row) {
    // 删除逻辑
    setTimeout(() => {
      eventList.value = eventList.value.filter((item) => item.eventId !== row.eventId);
      getList();
    }, 500);
  }
};

// 关闭事件
const handleClose = (row) => {
  if (row) {
    // 关闭逻辑
    setTimeout(() => {
      row.eventStatus = '3'; // 已关闭
      getList();
    }, 500);
  }
};

// 查看事件详情
const handleView = (row) => {
  if (row) {
    // 查看事件详情逻辑
    console.log('查看事件详情', row);
    router.push({
      path: '/duty/eventing/eventDetails',
      query: { eventId: row.eventId }
    });
  }
};

// 地图定位
const mapDialogVisible = ref(false);

const openMapDialog = () => {
  mapDialogVisible.value = true;
};

const handleMapChange = (lnglat) => {
  form.value.address = `${lnglat[0]}, ${lnglat[1]}`;
};

const confirmMapLocation = () => {
  mapDialogVisible.value = false;
};

onMounted(() => {
  getList();
  Promise.all([getDicts('mm_event_type'), getDicts('mm_event_level'), getDicts('mm_event_state'), getDicts('region')]).then(
    ([eventTypeRes, eventLevelRes, eventStatusRes, regionRes]) => {
      data.eventTypeSelection = eventTypeRes.data;
      data.eventLevelSelection = eventLevelRes.data;
      data.eventStatusSelection = eventStatusRes.data;
      data.regionSelection = regionRes.data;
    }
  );
});
</script>
