<template>
  <div class="app-container">
    <transition name="fade">
      <div v-show="showSearch" class="mb-[10px]">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item style="width: 200px" 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-form-item label="发布日期" prop="publishDate">
              <el-date-picker
                v-model="queryParams.publishDate"
                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="queryParams.keyword" 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="reportNumber"/>
        <el-table-column label="报告名称" align="center" prop="reportName"/>
        <el-table-column label="主题词" align="center" prop="keyword"/>
        <el-table-column label="事件类型" align="center" prop="eventType"/>
        <el-table-column label="摘要" align="center" prop="summary"/>
        <el-table-column label="来源单位" align="center" prop="sourceUnit"/>
        <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="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="demoFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="报告编号" prop="reportNumber">
          <el-input v-model="form.reportNumber" placeholder="请输入报告编号"/>
        </el-form-item>
        <el-form-item label="报告名称" prop="reportName">
          <el-input v-model="form.reportName" placeholder="请输入报告名称"/>
        </el-form-item>
        <el-form-item label="主题词" prop="keyword">
          <el-input v-model="form.keyword" 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="summary">
          <el-input v-model="form.summary" placeholder="请输入摘要"/>
        </el-form-item>
        <el-form-item label="来源单位" prop="sourceUnit">
          <el-input v-model="form.sourceUnit" placeholder="请输入来源单位"/>
        </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-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, toRefs, onMounted} from 'vue';
import {getDicts} from "@/api/system/dict/data";
import {ElMessage} from 'element-plus';
import ChunkUpload from '@/components/ChunkUpload/index.vue';

const demoList = 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 demoFormRef = ref();

// const fileList = ref([]);

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

const initFormData = {
  reportNumber: '',
  reportName: '',
  keyword: '',
  eventType: '',
  summary: '',
  sourceUnit: '',
  publishDate: ''
};

const data = reactive({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    eventType: '',
    publishDate: ['', ''],
    keyword: ''
  },
  rules: {
    reportNumber: [{required: true, message: '报告编号不能为空', trigger: 'blur'}],
    reportName: [{required: true, message: '报告名称不能为空', trigger: 'blur'}],
    keyword: [{required: true, message: '主题词不能为空', trigger: 'blur'}],
    eventType: [{required: true, message: '事件类型不能为空', trigger: 'blur'}],
    summary: [{required: true, message: '摘要不能为空', trigger: 'blur'}],
    sourceUnit: [{required: true, message: '来源单位不能为空', trigger: 'blur'}],
    publishDate: [{required: true, message: '发布日期不能为空', trigger: 'blur'}]
  },
  eventTypeSelection: []
});

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

const getList = async () => {
  loading.value = true;
  try {
    const response = await fetchReports(queryParams.value);
    const {data, total} = response;
    demoList.value = data;
    total.value = total;
  } catch (error) {
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 获取报告列表
const fetchReports = async (params) => {
  // 假设后端接口为 /api/reports
  const response = await fetch('/api/reports', {
    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};
  demoFormRef.value?.resetFields();
};

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

const resetQuery = () => {
  queryParams.value = {pageNum: 1, pageSize: 10, eventType: '', publishDate: ['', ''], keyword: ''};
  handleQuery();
};

const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.reportNumber);
  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 handleView = (row) => {
  // 跳转到总结报告详情页
  window.location.href = `/report/details/${row.reportId}`;
};

// 修改报告
const handleUpdate = (row) => {
  if (row) {
    reset();
    Object.assign(form.value, row);
    dialog.visible = true;
    dialog.title = '修改报告';
  }
};
 // 提交表单
const submitForm = () => {
  demoFormRef.value?.validate((valid) => {
    if (valid) {
      buttonLoading.value = true;
      setTimeout(() => {
        if (form.value.reportNumber) {
          // 更新逻辑
        } else {
          // 添加逻辑
        }
        buttonLoading.value = false;
        dialog.visible = false;
        getList();
      }, 500);
    }
  });
};

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

const handleExport = () => {
  // 导出逻辑
  console.log('导出数据');
};

// 处理文件上传数量限制
onMounted(() => {
  getList();
  getDicts("mm_event_type").then(res => {
    data.eventTypeSelection = res.data;
  });
});
</script>
