<template>
  <div class="app-container consult-list">
    <h3>
      数据集
      <el-tooltip
        content="数据集是存放服务的数据文件,支持JSON、EXCEL格式文件。用户可下载文件获取数据。"
        placement="top-start"
        effect="light"
      >
        <i class="el-icon-question"></i>
      </el-tooltip>
    </h3>
    <el-divider></el-divider>
    <el-row type="flex" justify="space-between">
      <el-col :span="18">
        <el-form :inline="true" :model="table.query.data">
          <el-form-item>
            <el-input
              placeholder="数据集名称"
              v-model="table.query.data.title"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="getOpenDataList"
              icon="Search"
              size="small"
            >
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="2" style="text-align: right">
        <el-upload
          ref="upload"
          name="file"
          :action="uploadUrl"
          :headers="headers"
          :before-upload="handleBeforeUpload"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :data="uploadData"
          :show-file-list="false"
        >
          <el-button size="small" type="primary">添加数据集</el-button>
        </el-upload>
      </el-col>
    </el-row>
    <el-row class="table_box">
      <el-table
        stripe
        :data="table.list"
        :height="table.height"
        style="width: 100%"
        size="small"
        :header-cell-style="{
          background: '#ebf3fb',
          color: '#333',
          padding: '4px 0',
          'border-right': '1px solid #fff',
        }"
      >
        <el-table-column type="index" align="center" label="序号" :index="1"/>
        <el-table-column
          show-overflow-tooltip
          v-for="(param, index) in table.params"
          :key="index"
          header-align="center"
          :align="param.align ? param.align : 'center'"
          :width="param.width ? param.width : 'auto'"
          :prop="param.paramCode"
          :label="param.paramName"
        >
          <template #default="scope">
            <span v-if="param.paramCode != 'viewNum'">
              {{ scope.row[param.paramCode] }}
            </span>
            <span v-if="param.paramCode == 'viewNum'">
              <el-tag disable-transitions>
                {{
                  scope.row[param.paramCode] == null
                    ? "0"
                    : scope.row[param.paramCode]
                }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="auto">
          <template #default="scope">
            <!-- <el-button @click="handlerDoc('view', scope.row)">
              预览
            </el-button> -->
            <el-button type="primary" @click="downloadFile(scope.row)">
              下载
            </el-button>
            <el-button
              type="danger"
              @click="deleteServiceFile(scope.row.fileId)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="table.total > 0"
        :total="table.total"
        :page.sync="table.query.pageNum"
        :limit.sync="table.query.pageSize"
        @pagination="getOpenDataList"
      />
    </el-row>
    <el-row type="flex" justify="center">
      <!-- <el-button
        icon="ArrowLeft"
        @click="forwardStep"
        circle
      ></el-button> -->
      <el-button @click="exit">退出</el-button>
      <!-- <el-button
        icon="ArrowRight"
        @click="nextStep"
        disabled
        circle
      ></el-button> -->
    </el-row>
    <a ref="downloadTools" style="display: none" href="" download=""></a>
  </div>
</template>

<script>
import {
  getServiceFile,
  updateServiceFile,
  deleteServiceFile,
} from "@/api/service/serviceFile.js";
import {getToken} from "@/utils/auth";

export default {
  name: "serviceFile",
  props: ["srvId"],
  data() {
    return {
      uploadUrl: "/pt/service/file/add",
      headers: {Authorization: "Bearer " + getToken()},
      fileSize: "100",
      uploadData: {},
      fileTypes: [
        "application/vnd.ms-excel",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel",
        "application/pdf",
        "text/xml, application/xml",
        "application/xml",
        "text/xml",
        "application/json",
        "text/csv",
      ],
      table: {
        height: window.innerHeight - 430,
        list: [],
        params: [
          {
            paramCode: "fileViewname",
            paramName: "数据集名称",
            align: "left",
            width: "200",
          },
          {
            paramCode: "fileType",
            paramName: "数据集类型",
            width: "100",
          },
          {
            paramCode: "fileSize",
            paramName: "数据集大小",
            width: "100",
          },
          {paramCode: "viewNum", paramName: "访问数量/次", width: "90"},
          {paramCode: "fileTime", paramName: "提交时间", width: "120"},
        ],
        total: 0,
        query: {
          pageNum: 1,
          pageSize: 20,
          orderBy: "",
          data: {
            name: "",
          },
        },
      },
    };
  },
  mounted() {
    this.getOpenDataList();
  },
  methods: {
    // 前进一步
    forwardStep() {
      this.$emit("forwardStep");
    },
    // 后退一步
    nextStep() {
      this.$emit("nextStep");
    },
    // 查询帮助数据集表
    async getOpenDataList() {
      if (!this.srvId) {
        return;
      }
      await getServiceFile(this.table.query, this.srvId).then((r) => {
        this.table.list = r.rows;
        this.table.total = r.total;
      });
    },
    // 下载文件
    downloadFile(file) {
      if (file) {
        this.$refs.downloadTools.href = "/doc/files" + file.path;
        this.$refs.downloadTools.download = file.name;
        this.$refs.downloadTools.click();
      }
    },
    // 删除文件
    deleteServiceFile(id) {
      deleteServiceFile(id)
        .then(() => {
          this.$message.success("文件删除成功");
          this.getOpenDataList();
        })
        .catch(() => {
          this.$message.error("文件删除失败");
        });
    },
    // 上传前校检格式和大小
    handleBeforeUpload(file) {
      if (!this.srvId) {
        return;
      }
      this.headers.srvId = this.srvId;
      this.uploadData = {srvId: this.srvId};
      const pattern = /\.{1}[A-Za-z]{1,}$/;
      let fileExt = pattern.exec(file.name);
      const checkType = this.fileTypes.includes(file.type);
      debugger;
      if (!checkType) {
        this.$message.warning(
          "只能上传 .xls、.xlsx、.json、.xml、.csv 格式的文件!"
        );
        return false;
      }
      if (![".xls", ".xlsx"].includes(fileExt[0].toLowerCase())) {
        this.$message.warning(
          "只能上传 .xls、.xlsx、.json、.xml、.csv 格式的文件!"
        );
        return false;
      }
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      return true;
    },
    // 上传成功后
    handleUploadSuccess(res, file) {
      this.getOpenDataList();

      // // 获取富文本组件实例
      // let quill = this.Quill;
      // // 如果上传成功
      // if (res.code == 200) {
      //   // 获取光标所在位置
      //   let length = quill.getSelection().index;
      //   // 插入图片  res.url为服务器返回的图片地址
      //   quill.insertEmbed(
      //     length,
      //     "image",
      //     process.env.VUE_APP_BASE_API + res.fileName
      //   );
      //   // 调整光标到最后
      //   quill.setSelection(length + 1);
      // } else {
      //   this.$message.error("文件上传成功");
      // }
    },
    // 文件上传失败
    handleUploadError() {
      this.$message.error("文件上传失败");
    },
    // 退出
    exit() {
      this.$nextTick(() => {
        this.$router.replace({
          query: {isClose: "true"},
        });
      });
    },
  },
  watch: {
    // 监听 srvId
    srvId: {
      handler(val) {
        if (val) {
          this.getOpenDataList();
        }
      },
      immediate: true,
      // deep: true,
    },
  },
};
</script>
<style scoped>
.active {
  background: #3785ea;
  color: #fff;
  border-radius: 2px;
}
</style>
