<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="地址" prop="params.key">
              <el-input v-model="queryParams.params.key" placeholder="请输入地址" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="事件等级" prop="level">
              <el-select v-model="queryParams.level" clearable placeholder="请选择">
                <el-option v-for="dict in event_level" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <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="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="eventList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="事件等级" prop="level" align="center">
          <template #default="{ row }">
            {{ event_level.filter((item) => item.value == row.level)[0]?.label }}
          </template>
        </el-table-column>
        <el-table-column label="事件类型" prop="ext2.lx" show-overflow-tooltip align="center" />
        <el-table-column label="地址" prop="addr" show-overflow-tooltip align="center" />
        <el-table-column label="发生时间" prop="createTimeFormat" align="center" />
        <el-table-column label="状态" prop="status" align="center">
          <template #default="{ row }">
            <span v-if="row.status == 3" style="color: #5f86fd">已上报</span>
            <span v-else-if="row.status == 1" style="color: #26c768">已解决</span>
            <span v-else-if="row.status == 2" style="color: #ff6124">未解决</span>
            <span v-else>{{ event_status.filter((item) => item.value == row.status)[0]?.label }}</span>
          </template>
        </el-table-column>
        <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="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改事件对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="eventFormRef" :model="form" label-position="top" label-width="90px" label-suffix=":">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="事件类型" prop="ext2.lx">
              <el-select v-model="form.ext2.lx" clearable filterable allow-create placeholder="请选择">
                <el-option v-for="dict in eventTypeOptions" :key="dict" :label="dict" :value="dict"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发生时间" prop="createTime">
              <el-date-picker style="width: 100%" value-format="YYYY-MM-DD HH:mm:ss" v-model="form.createTime" type="date" placeholder="请选择" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事件等级" prop="level">
              <el-select v-model="form.level" clearable placeholder="请选择">
                <el-option v-for="dict in event_level" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="桩号" prop="ext2.zh">
              <el-input v-model="form.ext2.zh" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" clearable placeholder="请选择">
                <el-option v-for="dict in event_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地点描述" prop="addr">
              <el-input v-model="form.addr" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="现场画面" prop="ext1">
              <uploadCom v-model="form.ext1" ref="fileUploadRef" :fileType="['png', 'jpg', 'jpeg', 'mp4']" />
            </el-form-item>
          </el-col>
        </el-row>
      </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>
  </div>
</template>

<script setup name="Event" lang="ts">
import { listEvent, getEvent, delEvent, addEvent, updateEvent, getEventTypes } from '@/api/system/event';
import { dateFormat } from '@/utils/index';
import uploadCom from './components/fileUpload.vue';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { event_level } = toRefs(proxy?.useDict('event_level'));
const { event_status } = toRefs(proxy?.useDict('event_status'));
const eventList = ref([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const eventFormRef = ref<ElFormInstance>();
const fileUploadRef = ref({} as any);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const initFormData = {
  id: undefined,
  addr: undefined,
  content: undefined,
  status: undefined,
  level: undefined,
  createTime: undefined,
  ext1: [],
  ext2: {
    lx: undefined,
    zh: undefined
  }
};
const data = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    level: undefined,
    ext1: undefined,
    ext2: undefined,
    params: {
      key: undefined
    }
  }
});
const { queryParams, form } = toRefs(data);
const eventTypeOptions = ref([]);
/** 查询事件列表 */
const getList = async () => {
  loading.value = true;
  const res = await listEvent(queryParams.value);
  eventList.value = res.rows.map((item) => ({
    ...item,
    status: item.status || '2',
    createTimeFormat: dateFormat(new Date(item.createTime), 'yyyy-MM-dd'),
    ext1: item.ext1 ? JSON.parse(item.ext1) : [],
    ext2: item.ext2 ? JSON.parse(item.ext2) : {}
  }));
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  eventFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加事件';
};

/** 修改按钮操作 */
const handleUpdate = async (row) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getEvent(_id);
  res.data.ext1 = JSON.parse(res.data.ext1) || [];
  res.data.ext2 = JSON.parse(res.data.ext2) || {
    lx: undefined,
    zh: undefined
  };
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改事件';
};

/** 提交按钮 */
const submitForm = () => {
  eventFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      const params = {
        ...form.value,
        ext1: JSON.stringify(form.value.ext1),
        ext2: JSON.stringify(form.value.ext2)
      };
      if (form.value.id) {
        await updateEvent(params).finally(() => (buttonLoading.value = false));
      } else {
        await addEvent(params).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
      getEventTypeOptions();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除？').finally(() => (loading.value = false));
  await delEvent(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/event/export',
    {
      ...queryParams.value
    },
    `event_${new Date().getTime()}.xlsx`
  );
};
const getEventTypeOptions = () => {
  getEventTypes().then(({ code, data }) => {
    if (code === 200) {
      eventTypeOptions.value = data;
    }
  });
};
onMounted(() => {
  getList();
  getEventTypeOptions();
});
</script>
