<template>
  <div class="app-container">
    <div class="top-bar">
      <SearchBar :config="searchConfig" @search="search" @reset="reset" />
      <PermissionButton
        button
        perms="sysLiterature:add"
        size="mini"
        type="primary"
        @click.native="handleOperation({ type: 'add' })"
        icon="el-icon-plus"
      >
        添加</PermissionButton
      >
    </div>
    <TablePage
      :data="list.records"
      :tableTitle="tableTitle"
      :operates="tableOperates"
      v-loading="loading"
    >
      <template v-slot:status="{ scope }">
        <el-popconfirm
          :title="getStatusTitle(scope.status)"
          @confirm="handleChangeStatus(scope)"
        >
          <el-switch
            slot="reference"
            :value="Boolean(Number(scope.status))"
          ></el-switch>
        </el-popconfirm>
      </template>

      <template v-slot:operates="{ scope }">
        <TableOperation
          :operations="tableOperations"
          :rawData="row"
          @handleOperation="handleOperation"
        >
        </TableOperation>
      </template>
    </TablePage>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="Number(list.current)"
      :page-sizes="[10, 20, 40, 50]"
      :page-size="Number(list.size)"
      layout="total, sizes, prev, pager, next, jumper"
      :total="Number(list.total)"
      class="pagination"
    >
    </el-pagination>
    <InfoEditDialog
      :visible="drawerVisible"
      :form="form"
      @handleClose="handleClose"
      @reloadParent="loadData"
    />
  </div>
</template>

<script>
import { title, operates, operations } from "./config";
import { editLiterature, deleteLt } from "@/api/literature";
import InfoEditDialog from "./components/InfoEditDialog";
import { downloadFile, previewFile, downloadBlob } from "@/utils/file";
import { mapActions } from "vuex";
export default {
  components: {
    InfoEditDialog,
  },
  data() {
    return {
      list: {
        records: [],
        size: 10,
        current: 1,
        total: 0,
      },
      searchForm: {
        name: "",
        status: "",
      },
      searchConfig: [
        {
          prop: "name",
          type: "input",
          label: "文献名称",
        },
        {
          prop: "authors",
          type: "input",
          label: "作者",
        },
        {
          prop: "status",
          type: "select",
          label: "状态",
          selectOptions: [
            {
              label: "已上架",
              value: "1",
            },
            {
              label: "已下架",
              value: "0",
            },
          ],
        },
      ],
      drawerVisible: false,
      form: {
        name: "", //名称
        authors: "", //作者
        date: "", //日期（出版年份、发布日期）
        source: "", //文献来源
        status: 1, //上下架状态
        remark: "", //备注
      },
      loading: false,
      searchParams: {},
    };
  },

  computed: {
    tableTitle() {
      return title;
    },
    tableOperates() {
      return operates;
    },
    tableOperations() {
      return operations;
    },
    getStatusTitle(status) {
      return (status) => {
        if (Number(status)) {
          return "是否确定要下架？";
        } else {
          return "是否确定要上架？";
        }
      };
    },
  },
  mounted() {
    this.loadData();
  },
  methods: {
    ...mapActions("dict", ["getLtList"]),
    // 搜索
    async search(form) {
      // 记录搜索的参数
      this.searchParams = form;
      // 重置分页到第一页
      this.resetPage();
      this.loadData(form);
    },
    // 清除分页到初始状态
    resetPage() {
      this.list.current = 1;
    },
    // 重置
    reset() {
      this.searchParams = {};
      this.loadData();
    },
    // 加载表格数据
    async loadData(form) {
      this.loading = true;
      var params = {
        page: this.list.current,
        limit: this.list.size,
      };
      const queryParams = form || this.searchParams;
      if (Object.keys(queryParams)) {
        params = { ...params, ...queryParams };
      }
      const res = await this.getLtList(params);
      if (res.code == 0) {
        this.list = res.data;
      }
      this.loading = false;
    },
    handleOperation(value, row) {
      switch (value.type) {
        case "add":
          this.drawerVisible = true;
          break;
        case "view":
          this.view(row);
          break;
        case "download":
          this.download(row);
          break;
        case "edit":
          this.form = row;
          this.drawerVisible = true;
          break;
        case "delete":
          this.handleDelete();
          break;
      }
    },
    // 预览
    view(row) {
      const { files } = row;
      const hasFileUrl = files.length > 0 && files[0].url;
      if (!hasFileUrl) {
        this.$message.info("暂无文献附件！");
        return;
      } else {
        previewFile(row.files[0].url, row.name);
      }
    },
    // 下载
    download(row) {
      const { files } = row;
      const hasFileUrl = files.length > 0 && files[0].url;
      if (!hasFileUrl) {
        this.$message.error("暂无文献！");
        return;
      } else {
        let msg = this.$message.info("正在准备下载...");
        let url = "/files" + files[0].url.split("files")[1];
        const { name } = row;
        const method = "get";
        const fileName = name;
        const suffix = "pdf";
        const options = {
          url,
          method,
          fileName,
          suffix,
        };
        downloadBlob(options)
          .then((res) => {
            msg.close();
            this.$message.success("下载成功！");
          })
          .catch((err) => {
            msg.close();
            this.$message.error("下载失败：" + err);
          });
      }
    },
    // 删除
    async handleDelete(row) {
      let deleteRes = await deleteLt([row.literatureId]);
      if (deleteRes.code == 0) {
        this.$message.success("删除成功！");
        this.loadData();
      }
    },
    async handleChangeStatus(row) {
      const callback = this.loadData;
      this.$bizCommon.changeStatus(row, editLiterature, callback);
    },

    // 改变页容量
    handleSizeChange(value) {
      this.list.size = value;
      this.loadData();
    },

    // 改变当前显示页
    handleCurrentChange(value) {
      this.list.current = value;
      this.loadData();
    },

    // 关闭Dialog
    handleClose() {
      this.drawerVisible = false;
      this.form = {
        status: 1,
      };
    },
  },
};
</script>

<style lang="scss" scoped>
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin: 16px;
}

// .el-button {
//   margin-bottom: 22px;
// }

::v-deep .el-card__header {
  padding: 10px 20px;
  font-weight: bold;
}
</style>
