<template>
  <div class="app-container">
    <transition name="fade">
      <div v-show="showSearch" class="mb-[10px]">
        <el-form ref="queryFormRef" :model="planForm" :inline="true">
          <el-form-item style="width: 200px" label="预案类型" prop="planType">
            <el-select v-model="planForm.planType" placeholder="全部" clearable>
              <el-option label="总体应急预案" value="1" />
              <el-option label="专项应急预案" value="2" />
              <el-option label="部门应急预案" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item label="发布日期" prop="publish_date">
            <el-date-picker
              v-model="planForm.publish_date"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-input v-model="planForm.planName" placeholder="请输入预案名称/编制单位" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          </el-form-item>
          <el-form-item>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </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="success" plain icon="Edit" :disabled="single" @click="handleUpdate(selectedRow)">修改</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-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
    </el-row>

    <!-- 表格组件 -->
    <el-table v-loading="loading" :data="demoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="预案编号" align="center" prop="planId" />
      <el-table-column label="预案名称" align="center" prop="planName" />
      <el-table-column label="预案类型" align="center" prop="planType" />
      <el-table-column label="发文字号" align="center" prop="document" />
      <el-table-column label="编制单位" align="center" prop="organUnit" />
      <el-table-column label="发布日期" align="center" prop="publishDate" />
      <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="Delete" @click="handleDelete(scope.row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 新增/修改弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="demoFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="预案名称" prop="planName">
          <el-input v-model="form.planName" placeholder="请输入预案名称" />
        </el-form-item>
        <el-form-item label="预案类型" prop="planType">
          <el-select v-model="form.planType" placeholder="请选择预案类型" clearable>
            <el-option label="总体应急预案" value="1" />
            <el-option label="专项应急预案" value="2" />
            <el-option label="部门应急预案" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布日期" prop="publishDate">
          <el-date-picker v-model="form.publishDate" type="date" placeholder="选择发布日期" value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item label="发文字号" prop="document">
          <el-input v-model="form.document" placeholder="请输入发文字号" />
        </el-form-item>
        <el-form-item label="编制单位" prop="organizingUnit">
          <el-input v-model="form.organizingUnit" placeholder="请输入编制单位" />
        </el-form-item>
        <el-col :span="1.5">
          <!-- 使用分片上传组件,每个分片 -->
          <chunk-upload :max-file-size="50 * 1024 * 1024" :max-files="5" />
        </el-col>
      </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 lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { fetchReports, addReport, updateReport, deleteReport } from '@/api/system/user/planList.ts';
import { PlanForm, PlanVO } from '@/api/system/user/types';
import ChunkUpload from '@/components/ChunkUpload/index.vue';
import { getDicts } from '@/api/system/dict/data';

import { useRouter } from 'vue-router';
import { getPlanDetail, getTrainingList } from "@/api/riskPrevention/planManage";

const router = useRouter();
const demoFormRef = ref(null);
const demoList = ref<PlanVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<string[]>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const selectedRow = ref<PlanVO | null>(null);
let proxy = getCurrentInstance()?.proxy;
const { mm_event_type } = toRefs<any>(proxy?.useDict('mm_event_type'));

const planForm = reactive<PlanForm>({
  pageNum: 1,
  pageSize: 10,
  planType: '',
  publish_date: ['', ''],
  planName: ''
});

const form = reactive({
  planId: '',
  planName: '',
  planType: '',
  document: '',
  organizingUnit: '',
  publishDate: ''
});

const rules = reactive({
  planName: [{ required: true, message: '预案名称不能为空', trigger: 'blur' }],
  planType: [{ required: true, message: '预案类型不能为空', trigger: 'blur' }],
  document: [{ required: true, message: '发文字号不能为空', trigger: 'blur' }],
  organizingUnit: [{ required: true, message: '编制单位不能为空', trigger: 'blur' }],
  publishDate: [{ required: true, message: '发布日期不能为空', trigger: 'blur' }]
});

const planTypeSelection = ref([]);

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

// const getList = async () => {
//   loading.value = true;
//   try {
//     const response = await fetchReports(planForm);
//     demoList.value = response.data;
//     total.value = response.total;
//   } catch (error) {
//     console.error('获取数据时出错:', error);
//   } finally {
//     loading.value = false;
//   }
// };
const getList = async () => {
  loading.value = true;
  const res = await getPlanDetail(planForm);
  loading.value = false;
  demoList.value = res.data;
  total.value = res.total;
};
const handleQuery = () => {
  planForm.pageNum = 1;
  getList();
};

const resetQuery = () => {
  planForm.pageNum = 1;
  planForm.pageSize = 10;
  queryParams.planType = '';
  queryParams.publish_date = ['', ''];
  queryParams.planName = '';
  getList();
};

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

const handleAdd = () => {
  resetForm();
  dialog.visible = true;
  dialog.title = '添加预案';
};

const handleUpdate = (row: PlanVO) => {
  if (row) {
    resetForm();
    Object.assign(form, row);
    dialog.visible = true;
    dialog.title = '修改预案';
  }
};

const handleDelete = async (row: PlanVO) => {
  try {
    await deleteReport(row.planId);
    ElMessage.success('删除成功');
    getList();
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

const handleView = (row: PlanVO) => {
  router.push({
    path: '/riskPrevention/planManage/planList',
    query: { planId: row.planId }
  });
};

const submitForm = () => {
  demoFormRef.value?.validate(async (valid) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        if (form.planId) {
          await updateReport(form);
          ElMessage.success('更新成功');
        } else {
          await addReport(form);
          ElMessage.success('添加成功');
        }
        dialog.visible = false;
        getList();
      } catch (error) {
        ElMessage.error('操作失败');
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

const resetForm = () => {
  Object.assign(form, {
    planId: '',
    planName: '',
    planType: '',
    document: '',
    organizingUnit: '',
    publishDate: ''
  });
  demoFormRef.value?.resetFields();
};

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

const handleExport = () => {
  ElMessage.success('导出成功');
};

onMounted(() => {
  getList();
  getDicts('mm_event_type').then((res) => {
    planTypeSelection.value = res.data;
  });
});
</script>
