<template>
  <div>
    <div class="app-container">
      <div v-show="!dialog.visible && !knowledgeDetailState.show">
        <transition name="fade">
          <div v-show="showSearch">
            <el-form ref="queryFormRef" :model="queryParams">
              <el-row :gutter="20">
                <!-- 第一行 -->
                <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 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="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-col>
                <el-col :span="6">
                  <el-form-item>
                    <el-input v-model="queryParams.query" placeholder="请输入报告的名称" clearable @keyup.enter="handleQuery" />
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item>
                    <el-button type="primary" @click="handleQuery">搜索</el-button>
                    <el-button @click="resetQuery">重置</el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </transition>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" 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-text class="common-btn-text-primary" @click="handleView(scope.row)">查看</el-text>
              <el-text class="common-btn-text-primary" @click="handleUpdate(scope.row)">修改</el-text>
              <el-text class="common-btn-text-danger" @click="handleDelete(scope.row)">删除</el-text>
            </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" />
      </div>
      <!-- 新增/修改弹窗 -->
      <div v-show="dialog.visible" class="common-dialog">
        <div class="common-dialog-content">
          <div class="common-dialog-title-box">
            <i class="common-dialog-title-icon" />
            <div>{{ dialog.title }}</div>
          </div>
          <div class="common-dialog-box">
            <el-form ref="demoFormRef" :model="form" :rules="rules" label-width="80px">
              <el-form-item label="报告名称：" prop="reportName">
                <el-input v-model="form.reportName" placeholder="请输入报告名称" style="width: 468px !important" />
              </el-form-item>
              <el-form-item label="主题词：" prop="subject">
                <el-input v-model="form.subject" placeholder="请输入主题词" style="width: 468px !important" />
              </el-form-item>
              <el-form-item label="事件类型：" prop="eventType">
                <el-select v-model="form.eventType" placeholder="请选择事件类型" clearable style="width: 468px !important">
                  <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="请输入摘要" style="width: 468px !important" />
              </el-form-item>
              <el-form-item label="来源单位：" prop="publishingUnit">
                <el-input v-model="form.publishingUnit" placeholder="请输入来源单位" style="width: 468px !important" />
              </el-form-item>
              <el-form-item label="发布日期：" prop="publishDate">
                <el-date-picker v-model="form.publishDate" type="datetime" placeholder="选择发布日期" style="width: 468px !important"></el-date-picker>
              </el-form-item>
              <el-col :span="1.5">
                <!-- 使用分片上传组件,每个分片 -->
                <!--          <chunk-upload ref="chunkUploadRef" :max-file-size="50 * 1024 * 1024" :max-files="5" />-->
                <FileUpload v-model="form.fileNames" />
              </el-col>
            </el-form>
          </div>
          <div class="common-dialog-footer" style="display: flex; justify-content: center">
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">确定</el-button>
            <el-button @click="cancel">取消</el-button>
          </div>
        </div>
      </div>
    </div>
    <KnowledgeDetail v-if="knowledgeDetailState.show" :reportId="knowledgeDetailState.reportId" @close="handleKnowledgeDetailClose"></KnowledgeDetail>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { fetchReports, addReport, updateReport, deleteReport } from '@/api/knowledge';
import { AddReportParams, QueryParams, ReportItem } from '@/api/knowledge/types';
// import ChunkUpload from '@/components/ChunkUpload/index.vue';
import { getDicts } from '@/api/system/dict/data';
import router from '@/router';
import axios, { AxiosError, isAxiosError } from 'axios';
import KnowledgeDetail from './detail.vue';

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>({
  query: '',
  pageNum: 1,
  pageSize: 10,
  eventType: '',
  publishDate: ['', ''],
  subject: '',
  sortBy: 'publishDate',
  sortOrder: 'desc',
  publishDateRange: ''
});
// 表单数据
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: ''
});

let knowledgeDetailState = reactive({
  show: false,
  reportId: ''
});

// getLists是获取列表数据的方法
const getList = async () => {
  // 开始加载数据
  loading.value = true;
  try {
    // 这里格式化日期范围参数
    // 将-分割转换为/分割
    const [startDate, endDate] = queryParams.publishDate;
    const formattedStartDate = startDate ? startDate.replace(/-/g, '/') : '';
    const formattedEndDate = endDate ? endDate.replace(/-/g, '/') : '';
    const publishDateRange = formattedStartDate && formattedEndDate ? `${formattedStartDate}-${formattedEndDate}` : '';

    // 构建新的请求参数对象
    const requestParams = {
      ...queryParams,
      publishDateRange, // 添加新的日期范围参数
      publishDate: undefined // 移除原来的 publishDate 参数
    };

    // 发送请求
    const response = await fetchReports(requestParams);

    if (response && response.code === 200) {
      // demoLIst是ref对象，需要通过.value赋值
      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'; // 重置排序方式
  queryParams.query = '';
  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) {
    selectedRow.value = row;
    resetForm();
    Object.assign(form, row);
    dialog.visible = true;
    dialog.title = '修改报告';
  }
};

// 删除报告
const handleDelete = async (row: ReportItem) => {
  ElMessageBox.confirm('此操作将永久删除该报告, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteReport(row.reportId);
      ElMessage({
        type: 'success',
        message: '报告已删除'
      });
      getList();
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除'
      });
    });
  /*
  try {
    await deleteReport(row.reportId);
    ElMessage.success('删除成功');
    getList();
  } catch (error) {
    ElMessage.error('删除失败');
  }
  */
};

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

const handleKnowledgeDetailClose = () => {
  knowledgeDetailState.show = false;
}

// 格式化日期
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 {
        // 格式化日期为后端所需的格式
        form.publishDate = formatDate(new Date(form.publishDate));

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

        if (dialog.title === '修改报告' && selectedRow.value) {
          const updateData = {
            ...form,
            reportId: selectedRow.value.reportId
          };
          console.log('modify:', updateData)
          await updateReport(updateData);
          ElMessage.success('更新成功');
        } else {
          await addReport(form);
          ElMessage.success('添加成功');
        }
        dialog.visible = false;
        getList(); // 刷新列表
      } catch (error) {
        if (isAxiosError(error)) {
          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>
