<template>
  <!-- <div class="container">
    
  </div> -->
  <el-container>
    <el-header height="60px" class="content-header">
      <MyHeader
        :title="'统一接入标准'"
        :formData="headerFormData"
        @submit="handleHeaderFormSubmit"
      ></MyHeader>
    </el-header>
    <el-container>
      <el-main>
        <MyTableHeader
          :title="tableHeaderTitle"
          :buttons="buttons"
          @tabClick="handleTabClick"
          @buttonClick="handleButtonClick"
        ></MyTableHeader>

        <MyTable
          :tableData="tableData"
          :formData="formData"
          :minWidth="80"
          :rowKey="'fileId'"
        >
          <!-- 自定义操作按钮，传递 row 和 index -->
          <template #operation="{ row, index }">
            <el-button
              size="mini"
              @click="handleView(row, 'view')"
              type="primary"
              >预览</el-button
            >

            <el-button
              size="mini"
              @click="handleDownload(row, index)"
              type="primary"
              >下载</el-button
            >

            <el-button size="mini" @click="handleDelete(row)" type="primary"
              >删除</el-button
            >
          </template>
        </MyTable>
        <MyPagination
          :total="tableTotal"
          :page-size="pageSize"
          :current-page="currentPage"
          @pageChange="pagi_changePage"
          @sizeChange="pagi_changeSize"
        ></MyPagination>
      </el-main>
    </el-container>
    <!-- 文件上传 -->
    <el-dialog
      :visible.sync="visible"
      title="文件上传"
      width="50%"
      @close="handleClose"
    >
      <el-upload
        class="upload-container"
        ref="upload"
        :action="uploadUrl"
        :headers="headers"
        :before-upload="beforeUpload"
        :on-success="handleSuccess"
        :on-error="handleError"
        :auto-upload="false"
        :file-list="fileList"
        :drag="true"
        :show-file-list="true"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          <!-- 只能上传Excel文件（.xls, .xlsx），且不超过2MB -->
        </div>
      </el-upload>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 预览 -->

    <div v-if="showDialog">
      <PreviewDialog
        :rowObj="rowObj"
        :fileType="fileType"
        @cancel="getList"
        v-model="showDialog"
      ></PreviewDialog>
    </div>
  </el-container>
</template>
<script>
import { getToken } from "@/utils/auth";
import {
  getTabFileInfoList,
  updateTabFileInfoById,
  uploadTabFileInfoById,
  downloadTabFileInfoById,
  delTabFileInfoById,
  previewFileTabFileInfoById,
} from "@/api/unified-access/access-standard";
import FileUploadDialog from "./dialog/FileUploadDialog.vue";
import MyHeader from "@/components/MyHeader";
import MyTable from "@/components/MyTable";
import MyPagination from "@/components/MyPagination";
import MyTableHeader from "@/components/MyTableHeader";
import StandardDialog from "./dialog/StandardDialog.vue";
import PreviewDialog from "./dialog/PreviewDialog";
export default {
  name: "access-standard",
  components: {
    MyHeader,
    MyTableHeader,
    MyTable,
    MyPagination,
    StandardDialog,
    FileUploadDialog,
    PreviewDialog,
  },
  data() {
    return {
      rowObj: {},
      fileType: "",
      fileUrl: "",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      file: null,
      visible: false,
      uploadDialogVisible: false,
      // 文件上传接口的 URL

      uploadUrl: process.env.VUE_APP_BASE_API + "/web/tab-file-info/upload", // 替换为实际的上传接口
      fileList: [], // 文件列表
      showDialog: false,
      title: "新增",
      tableData: [],
      formData: [
        {
          label: "标准名称",
          fieldName: "fileName",
          type: "input",
          align: "",
          showInTable: true,
          value: "",
          width: "",
        },

        {
          label: "状态",
          fieldName: "status",
          type: "input",
          align: "center",
          showInTable: true,
          value: "",
          width: "",
        },
      ],
      tableTotal: 0,
      pageSize: 10,
      currentPage: 1,
      searchForm: {},
      treeSearchVal: "",
      tableHeaderTitle: "项目列表",
      tabs: [
        { label: "全部", name: "全部", active: true },
        {
          label: "数据源(数据提供方)",
          name: "数据源(数据提供方)",
          active: false,
        },
        { label: "数据接收方", name: "数据接收方", active: false },
      ],
      buttons: [
        {
          label: "上传",
          type: "primary",
          methodName: "action1",
          icon: "el-icon-circle-plus",
        },
      ],

      headerFormData: [
        {
          label: "标准名称",
          fieldName: "fileName",
          type: "input",
          value: "",
          placeholder: "请输入用标准名称",
          // isRequired: true,
        },
        {
          fieldName: "status",
          label: "状态",
          type: "select",
          trigger: "change",
          value: "",
          isRequired: false,
          options: [
            { value: 1, label: "启用" },
            { value: 0, label: "停用" },
          ],
        },
        // {
        //   label: "用户状态",
        //   fieldName: "gender",
        //   type: "select",
        //   value: "",
        //   placeholder: "请选择用户状态",
        //   isRequired: true,
        //   options: [
        //     { label: "男", value: "male" },
        //     { label: "女", value: "female" },
        //   ],
        // },
        // {
        //   label: "生日",
        //   fieldName: "birthdate",
        //   type: "date",
        //   value: "",
        //   placeholder: "请选择生日",
        //   isRequired: false,
        // },
      ],
      previewUrl: "", // 文件的预览 URL
      isImage: false, // 是否是图片
      isText: false, // 是否是文本文件
      isExcel: false, // 是否是 Excel 文件
      isPdf: false, // 是否是 PDF 文件
    };
  },
  methods: {
    // 头部搜索框
    handleHeaderFormSubmit(form) {
      this.searchForm = form;
      this.getList();
    },
    // 树结构点击
    handleNodeClick() {},
    // 列表头部
    handleTabClick(tab) {
      this.tabs.forEach((item) => {
        if (item.label === tab.label) {
          item.active = true;
        } else {
          item.active = false;
        }
      });
    },

    getList() {
      getTabFileInfoList({
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        ...this.searchForm,
      }).then((res) => {
        if (+res.code === 200) {
          this.tableData = res.rows;
          this.tableTotal = +res.total;
        }
      });
    },
    // 列表分页
    pagi_changePage(page) {
      this.currentPage = page;
      this.getList();
    },
    pagi_changeSize(size) {
      this.pageSize = size;
      this.getList();
    },

    // 列表头部功能按钮
    handleButtonClick(methodName) {
      console.log(methodName, "methodName");

      switch (methodName) {
        case "action1":
          // 上传
          // this.openDialog();
          this.visible = true;
          break;

        default:
          break;
      }
    },
    handleDownload(row) {
      const filePath = row.filePath;
      // 获取文件扩展名
      const ext = filePath.split(".").pop().toLowerCase();
      this.download(
        `/web/tab-file-info/download/${row.fileId}`,
        {},
        `接入标准_${new Date().getTime()}.${ext}`
      );
    },
    handleDelete(row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        center: true,
        type: "warning",
      })
        .then(() => {
          delTabFileInfoById(row.fileId).then((res) => {
            if (+res.code === 200) {
              this.$message({
                message: res.msg,
                type: "success",
              });
              this.getList();
            } else {
              this.$message.error(res.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      console.log(row, "row");
    },
    // 打开上传弹窗
    openDialog() {
      this.uploadDialogVisible = true;
    },
    // 文件上传成功后的处理
    handleFileSuccess(response, file, fileList) {
      // 处理上传成功的逻辑
      this.$message.success("文件上传成功！");
      console.log("上传成功:", response, file, fileList);
      // 例如保存文件的 URL
      const fileUrl = response.url;
      this.saveFileUrl(fileUrl);
      // 关闭弹窗
      this.uploadDialogVisible = false;
    },
    // 文件上传失败后的处理
    handleFileError(error, file, fileList) {
      // 处理上传失败的逻辑
      this.$message.error("文件上传失败");
      console.log("上传失败:", error, file, fileList);
    },
    // 保存上传后的文件 URL 或其他处理
    saveFileUrl(url) {
      // 保存文件 URL 或其他逻辑
      console.log("保存文件 URL:", url);
    },

    handleFileConfirm(val) {},

    // 预览
    handleView(row) {
      this.rowObj = row;
      // previewFileTabFileInfoById(row.fileId).then(res => {
      //   if (+res.code===200) {

      //   }
      // })

      const filePath = row.filePath;
      this.previewUrl = filePath;
      const ext = filePath.split(".").pop().toLowerCase();
      this.fileType = ext;
      // this.fileUrl = process.env.VUE_APP_BASE_API + filePath;

      // 重置所有预览类型
      // this.isImage = false;
      // this.isText = false;
      // this.isExcel = false;
      // this.isPdf = false;
      // 获取文件扩展名

      // 根据扩展名判断文件类型
      // if (["png", "jpg", "jpeg", "gif"].includes(ext)) {
      //   this.isImage = true; // 图片文件
      // } else if (["txt"].includes(ext)) {
      //   this.isText = true; // 文本文件
      // } else if (["xlsx", "xls"].includes(ext)) {
      //   this.isExcel = true; // Excel 文件
      // } else if (["pdf"].includes(ext)) {
      //   this.isPdf = true; // PDF 文件
      // } else {
      //   this.previewUrl = ""; // 不支持预览的类型
      // }
      // this.title = "预览";
      this.showDialog = true;
    },
    handleEdit(row) {
      this.title = "编辑";
      this.showDialog = true;
    },

    // 上传前处理
    beforeUpload(file) {
      console.log("上传前处理");

      console.log(file, "file");
      this.file = file;
      // 可以在这里做一些文件格式、大小的校验
      const isPdf = file.type !== "json";
      if (!isPdf) {
        this.$message.error("不能能上传json文件");
      }
      return isPdf; // 如果返回 false，文件将不会被上传
    },
    handleFileUploadProgress() {
      this.upload.isUploading = true;
    },
    // 上传成功处理
    handleSuccess(response, file, fileList) {
      console.log("上传成功处理");
      console.log(file, "file");
      this.file = file;
      // this.upload.isUploading = false;
      // this.form.filePath = response.url;
      this.$modal.msgSuccess(response.msg);
    },
    beforeAvatarUpload(file) {
      console.log(file, "file==beforeAvatarUpload");
      this.file = file;
    },
    // 上传失败处理
    handleError(error, file, fileList) {
      console.log("上传失败处理");
      // 调用父组件传递的 onError 方法
      this.onError(error, file, fileList);
    },
    // 提交上传
    submitUpload() {
      this.loading = true;
      // uploadTabFileInfoById({ ...this.file }).then((res) => {});
      this.$refs.upload.submit(); // 提交上传
    },
    // 关闭弹窗时清空文件列表
    handleClose() {
      this.visible = false;
    },

    // 取消按钮处理方法
    handleCancel() {
      this.visible = false;
      this.getList();
    },

    // 确定按钮处理方法
    handleConfirm(response) {
      this.$refs.upload.submit();
      // this.$modal.msgSuccess(response.msg);
      this.handleClose();
    },
  },
  created() {},
  mounted() {
    this.getList();
  },
};
</script>
<style lang="scss" scoped>
.el-main {
  padding: 0 20px;
}

.el-icon-search {
  font-size: 16px;
  font-weight: 700;
  color: #1e80e0;
}
</style>
