<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryRef"
      :inline="true"
      :model="queryParams"
      @submit.prevent
    >
      <el-form-item label="成果名称" prop="title">
        <el-input
          v-model="queryParams.title"
          clearable
          placeholder="请输入成果名称"
          size="small"
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          icon="Search"
          size="small"
          type="primary"
          @click="handleQuery"
          >搜索
        </el-button>
        <el-button icon="Refresh" size="small" @click="resetQuery"
          >重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-if="route.name === 'ResearchAchievement'"
          icon="UploadFilled"
          size="small"
          type="primary"
          @click="handleImport"
          >导入成果
        </el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="dataList">
      <el-table-column label="数据编号" prop="id" />
      <el-table-column
        :show-overflow-tooltip="true"
        label="成果名称"
        prop="title"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        label="成果领域"
        prop="industryStr"
      />
      <el-table-column
        v-if="route.name === 'ExpertAchievement'"
        label="所属专家"
        prop="expertName"
      />
      <!--      <el-table-column label="浏览量" prop="visitCount"/>-->
      <el-table-column align="center" label="发布时间" prop="createTime">
        <template #default="{ row }">
          <span>{{ dayjs(row.createTime).format("YYYY-MM-DD") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        label="操作"
      >
        <template #default="{ row }">
          <!--          <el-button-->
          <!--              icon="download"-->
          <!--              size="small"-->
          <!--              type="text"-->
          <!--              @click="handleDelete(row.id)"-->
          <!--          >下架-->
          <!--          </el-button-->
          <!--          >-->
          <el-button
            icon="delete"
            size="small"
            type="text"
            @click="handleDelete(row.id)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 用户导入对话框 -->
    <el-dialog
      v-model="upload.dialogVisible"
      append-to-body
      title="导入成果"
      width="400px"
    >
      <el-upload
        ref="uploadRef"
        :action="upload.url"
        :auto-upload="false"
        :disabled="upload.isUploading"
        :headers="upload.headers"
        :limit="1"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        accept=".xlsx, .xls"
        drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              type="primary"
              @click="saveAs(xlsl, '成果导入模板.xlsx')"
              >下载模板
            </el-link>
          </div>
          <div class="el-upload__tip text-center">
            <span style="color: red">成果导入说明(必读)。</span>
            <el-link
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              type="primary"
              @click="saveAs(importTip, '成果导入说明(必读).txt')"
              >下载
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.dialogVisible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import dayjs from "dayjs";
import { useRoute, useRouter } from "vue-router";
import { reactive, ref, toRefs } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  achievementList,
  deleteAchievements,
  researchAchievementList,
} from "@/api/admin/research/achievement";
import { getToken } from "@/utils/auth";
import xlsl from "@/assets/achievement_import_template.xlsx?url";
import importTip from "@/assets/achievement_import_description.txt?url";
import { saveAs } from "file-saver";

const router = useRouter();

const dataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const route = useRoute();
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: undefined,
  },
});

const { queryParams } = toRefs(data);

const queryRef = ref();
const fetchMethods = {
  ResearchAchievement: researchAchievementList,
  ExpertAchievement: achievementList,
};
/** 查询数据列表 */
const getList = async () => {
  loading.value = true;
  fetchMethods[route.name](queryParams.value)
    .then((resp) => {
      dataList.value = resp.rows;
      total.value = resp.total;
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};

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

/** 重置按钮操作 */
function resetQuery() {
  queryRef.value.resetFields();
  handleQuery();
}

/**
 * 删除按钮操作
 * @param id
 */
function handleDelete(id) {
  ElMessageBox.confirm(`是否确认删除数据编号为"${id}"的成果项?'`)
    .then(function () {
      return deleteAchievements(id);
    })
    .then(() => {
      getList();
      ElMessage.success("删除成功");
    });
}

const uploadRef = ref(null);
const upload = reactive({
  dialogVisible: false,
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { "client-token": "Bearer " + getToken() },
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/app/research/importData",
});

/**
 * 导入成果
 */
const handleImport = () => {
  upload.dialogVisible = true;
};

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};
/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.dialogVisible = false;
  upload.isUploading = false;
  uploadRef.value.handleRemove(file);
  proxy.$alert(
    "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
      response.msg +
      "</div>",
    "导入结果",
    { dangerouslyUseHTMLString: true }
  );
  getList();
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value.submit();
}

getList();
</script>
