<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 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.subject" 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="reportId"/>
      <el-table-column label="报告名称" align="center" prop="reportName"/>
      <el-table-column label="主题词" align="center" prop="subject"/>
      <el-table-column label="事件类型" align="center" prop="eventType">
        <template #default="scope">
          <dict-tag :options="mm_event_type" :value="scope.row.eventType" />
        </template>
      </el-table-column>
      <el-table-column label="摘要" align="center" prop="summary"/>
      <el-table-column label="来源单位" align="center" prop="publishingUnit"/>
      <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="reportName">
          <el-input v-model="form.reportName" placeholder="请输入报告名称"/>
        </el-form-item>
        <el-form-item label="主题词" prop="subject">
          <el-input v-model="form.subject" placeholder="请输入主题词"/>
        </el-form-item>
        <el-form-item label="事件类型" prop="eventType">
          <el-select v-model="form.eventType" placeholder="请选择事件类型" clearable>
            <el-option
              v-for="item in 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="publishingUnit">
          <el-input v-model="form.publishingUnit" placeholder="请输入来源单位"/>
        </el-form-item>
        <el-form-item label="发布日期" prop="publishDate">
          <el-date-picker
            v-model="form.publishDate"
            type="datetime"
            placeholder="选择发布日期"
          ></el-date-picker>
        </el-form-item>
        <el-col :span="1.5">
          <!-- 使用分片上传组件,每个分片 -->
          <chunk-upload ref="chunkUploadRef" :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/kenowledge';
import {AddReportParams, QueryParams, ReportItem} from '@/api/kenowledge/types';
import ChunkUpload from '@/components/ChunkUpload/index.vue';
import {getDicts} from "@/api/system/dict/data";
import router from "@/router";

const demoFormRef = ref(null);
const demoList = ref<ReportItem[]>([]);
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<ReportItem | null>(null);
let proxy = getCurrentInstance()?.proxy;
const { mm_event_type } = toRefs<any>(proxy?.useDict('mm_event_type'));
const chunkUploadRef = ref(null);

const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  eventType: '',
  publishDate: ['', ''],
  subject: '',
  sortBy: 'publishDate',
  sortOrder: 'desc',
});
 // 表单数据
const form = reactive<AddReportParams>({
  reportName: '',
  subject: '',
  eventType: '',
  summary: '',
  publishingUnit: '',
  publishDate: '',
  fileNames: [],
});

const rules = reactive({
  reportName: [{ required: true, message: '报告名称不能为空', trigger: 'blur' }],
  subject: [{ required: true, message: '主题词不能为空', trigger: 'blur' }],
  eventType: [{ required: true, message: '事件类型不能为空', trigger: 'blur' }],
  summary: [{ required: true, message: '摘要不能为空', trigger: 'blur' }],
  publishingUnit: [{ required: true, message: '来源单位不能为空', trigger: 'blur' }],
  publishDate: [{ required: true, message: '发布日期不能为空', trigger: 'blur' }]
});

const eventTypeSelection = ref([]);

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


// 更新 getList 函数
const getList = async () => {
  loading.value = true;
  try {
    const response = await fetchReports(queryParams);
    if (response && response.code === 200) {
      // 去掉日期字符串中的 'T'
      demoList.value = response.data.map((item: ReportItem) => {
        return {
          ...item,
          publishDate: item.publishDate.replace('T', ' ')
        };
      });
      total.value = response.total;
      queryParams.pageNum = response.currentPage; // 确保currentPage赋值
      queryParams.pageSize = response.pageSize; // 确保pageSize赋值
    } else {
      console.error('数据格式不匹配:', response);
      throw new Error(response.msg || '响应数据格式不正确');
    }
  } catch (error) {
    console.error('获取数据时出错:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};


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

// 重置查询条件
const resetQuery = () => {
  queryParams.pageNum = 1;
  queryParams.pageSize = 10;
  queryParams.eventType = '';
  queryParams.publishDate = ['', ''];
  queryParams.subject = '';
  queryParams.sortBy = 'publishDate'; // 重置排序字段
  queryParams.sortOrder = 'desc'; // 重置排序方式
  getList();
};

// 多选框选中数据
const handleSelectionChange = (selection: ReportItem[]) => {
  ids.value = selection.map((item) => item.reportId);
  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: ReportItem) => {
  if (row) {
    resetForm();
    Object.assign(form, row);
    dialog.visible = true;
    dialog.title = '修改报告';
  }
};

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

// 详情页
const handleView = (row: ReportItem) => {
  router.push({
    path: `/knowledge/detail`,
    query: { reportID: row.reportId }
  });
};


// 格式化日期
const formatDate = (date: Date): string => {
  const yyyy = date.getFullYear();
  const mm = String(date.getMonth() + 1).padStart(2, '0'); // 月份以0为基数
  const dd = String(date.getDate()).padStart(2, '0');
  const hh = String(date.getHours()).padStart(2, '0');
  const min = String(date.getMinutes()).padStart(2, '0');
  const ss = String(date.getSeconds()).padStart(2, '0');
  return `${yyyy}-${mm}-${dd} ${hh}:${min}:${ss}`;
};

// 提交表单
const submitForm = () => {
  demoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 使用新定义的 getUploadedFileNames 方法
        form.fileNames = chunkUploadRef.value?.getUploadedFileNames() || [];

        // 格式化日期为后端所需的格式
        form.publishDate = formatDate(new Date(form.publishDate));

        // 打印发送的数据，检查格式是否正确
        console.log('提交给后端的 JSON 数据:', JSON.stringify(form, null, 2));

        if (dialog.title === '修改报告' && selectedRow.value) {
          const updateData = {
            ...form,
            reportId: selectedRow.value.reportId,
          };
          await updateReport(updateData);
          ElMessage.success('更新成功');
        } else {
          await addReport(form);
          ElMessage.success('添加成功');
        }
        dialog.visible = false;
        getList(); // 刷新列表
      } catch (error) {
        if (error.response) {
          console.error('后端响应错误:', error.response.data);
          ElMessage.error(`操作失败: ${error.response.data.message || '未知错误'}`);
        } else {
          console.error('提交失败:', error);
          ElMessage.error('操作失败，无法连接到服务器');
        }
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};
// 重置表单
const resetForm = () => {
  Object.assign(form, {
    reportName: '',
    subject: '',
    eventType: '',
    summary: '',
    publishingUnit: '',
    publishDate: '',
    fileNames: [] // 也可以清空上传的文件名列表
  });
  demoFormRef.value?.resetFields();
};

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

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

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