<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryRef"
      :inline="true"
      :model="queryParams"
      @submit.prevent
    >
      <el-form-item
        :label="t('admin.form.name', { type: t('admin.common.achievement') })"
        prop="title"
      >
        <el-input
          v-model="queryParams.title"
          clearable
          :placeholder="
            t('admin.form.placeholder', {
              type: t('admin.form.name', {
                type: t('admin.common.achievement'),
              }),
            })
          "
          size="small"
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          icon="Search"
          size="small"
          type="primary"
          @click="handleQuery"
          >{{ t("common.search") }}
        </el-button>
        <el-button icon="Refresh" size="small" @click="resetQuery"
          >{{ t("admin.common.reset") }}
        </el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col
        v-if="route.name === 'LabAchievement' && locale === 'zh'"
        :span="1.5"
      >
        <el-button
          icon="UploadFilled"
          size="small"
          type="primary"
          @click="handleImport"
          >{{ t("admin.form.importAchievement") }}
        </el-button>
      </el-col>
      <!--      <el-col v-if="route.name === 'LabAchievement'" :span="1.5">
              <el-button icon="plus" size="small" type="primary" @click="handleAdd"
                >{{
                  t("admin.form.add", {
                    type: t("admin.common.achievement"),
                  })
                }}
              </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="t('admin.common.dataNumber')" prop="id" />
      <el-table-column
        :show-overflow-tooltip="true"
        :label="t('admin.form.name', { type: t('admin.common.achievement') })"
        prop="title"
      />
      <el-table-column
        :show-overflow-tooltip="true"
        :label="t('admin.table.achievementIndustry')"
        prop="industryStr"
      />
      <el-table-column
        v-if="route.name === 'ExpertAchievement'"
        :label="t('admin.form.belongExpert')"
        prop="expertName"
      />
      <!--      <el-table-column label="浏览量" prop="visitCount"/>-->
      <el-table-column
        align="center"
        :label="t('admin.table.publishTime')"
        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="t('admin.common.operation')"
      >
        <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)"
            ><!--删除-->
            {{ t("admin.common.delete") }}
          </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="t('admin.form.importAchievement')"
      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">{{ t("tips.uploadFile") }}</div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>{{ t("tips.onlyAllowImportXlsXlsx") }}</span>
            <el-link
              :underline="false"
              style="font-size: 12px; vertical-align: baseline"
              type="primary"
              @click="downloadImportTemplate"
              >{{ t("tips.downloadTemplate") }}
            </el-link>
            <br />
            <span>{{ t('tips.importTip') }}</span>
            <ol style="text-align: left">
              <li>{{ t("tips.keywordsImportTip") }}</li>
              <li>
                {{ t("tips.industryImportTip") }}
                <br />
                {{ t("tips.industryImportExample") }}
              </li>
            </ol>
          </div>
          <!--          <div class="el-upload__tip text-center">-->
          <!--            <span style="color: red">{{ t("tips.importInstructions") }}</span>-->
          <!--            <el-link-->
          <!--              :underline="false"-->
          <!--              style="font-size: 12px; vertical-align: baseline"-->
          <!--              type="primary"-->
          <!--              @click="saveAs(importTip, `${t('tips.importInstructions')}.txt`)"-->
          <!--              >&lt;!&ndash;下载&ndash;&gt;{{ t("common.download") }}-->
          <!--            </el-link>-->
          <!--          </div>-->
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm"
            >{{ t("common.confirm") }}
          </el-button>
          <el-button @click="upload.dialogVisible = false"
            >{{ t("common.cancel") }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import { getCurrentInstance, reactive, ref, toRefs } from "vue";
import {
  achievementList,
  deleteAchievements,
  labAchievementTemplate,
  laboratoryAchievementList,
} from "@/api/admin/laboratory/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";
import { useI18n } from "vue-i18n";
import dayjs from "dayjs";
import modal from "@/plugins/modal";

const { t, locale } = useI18n();
const router = useRouter();
const route = useRoute();

const { proxy } = getCurrentInstance();
console.log(route.name);
const dataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const title = ref("");
const fetchMethods = {
  LabAchievement: laboratoryAchievementList,
  ExpertAchievement: achievementList,
};
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    inventor: undefined,
  },
});

const { queryParams } = toRefs(data);

const queryRef = ref();

/** 查询数据列表 */
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) {
  modal
    .confirm(
      t("admin.common.confirmAction", {
        action: t("admin.common.delete"),
        type: t("admin.common.achievement"),
        number: id,
      })
    )
    .then(function () {
      return deleteAchievements(id);
    })
    .then(() => {
      getList();
      ElMessage.success(t("admin.common.deleteSuccess"));
    })
    .catch((err) => {
      console.log(err);
    });
}

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/laboratory/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>",
    t("tips.importResult"),
    { dangerouslyUseHTMLString: true }
  );
  getList();
};

/** 下载模板操作 */
const importTemplate = () => {
  saveAs(xlsl, `${t("admin.common.achievementImportTemplate")}.xlsx`);
};

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

const handleAdd = () => {
  router.push({
    path: "./release",
    // query: {
    //   id: "",
    // },
  });
};

const downloadImportTemplate = async () => {
  const blob = await labAchievementTemplate();
  saveAs(blob, `${t("admin.common.achievementImportTemplate")}.xlsx`);
};

getList();
</script>