<template>
  <div class="app-container">
    <div class="top-bar">
      <SearchBar :config="searchConfig" @search="search" @reset="reset" />
    </div>
    <div class="tools">
      <div class="tools-item">
        <el-button
          type="primary"
          @click.native="handleOperation({ type: 'add' })"
          icon="el-icon-plus"
        >
          添加</el-button
        >
        <el-upload
          class="upload-button"
          :action="importZipUrl"
          :headers="headers"
          accept=".zip"
          :show-file-list="false"
          :on-exceed="handleExceed"
          :before-upload="handleUpload"
          :on-success="handleSuccess"
          multiple
        >
          <el-button
            type="success"
            @click.native="handleOperation({ type: 'multiAdd' })"
            icon="el-icon-upload"
          >
            批量导入</el-button
          >
        </el-upload>
      </div>
      <div class="tools-item">
        <el-button
          type="primary"
          @click.native="handleOperation({ type: 'downloadTemplate' })"
          icon="el-icon-download"
        >
          下载导入模板</el-button
        >

        <el-button
          type="primary"
          @click.native="handleOperation({ type: 'viewImportRecord' })"
          icon="el-icon-document"
        >
          查看导入记录</el-button
        >
      </div>
    </div>
    <TablePage
      :data="list.records"
      :tableTitle="tableTitle"
      :operates="tableOperates"
      :height="tableHeight"
    >
      <template v-slot:status="data">
        <el-popconfirm
          :title="getStatusTitle(data.scope.status)"
          @onConfirm="handleChangeStatus(data.scope)"
        >
          <el-switch
            slot="reference"
            :value="Boolean(Number(data.scope.status))"
          ></el-switch>
        </el-popconfirm>
      </template>
      <template v-slot:faceImageUrl="data">
        <img
          :src="data.scope.faceImagePressUrl || data.scope.faceImageUrl"
          alt="查看大图"
          v-if="data.scope.faceImagePressUrl || data.scope.faceImageUrl"
          style="cursor: pointer"
          width="100px"
          @click="handelPreviewImages(data.scope.faceImageUrl)"
        />
      </template>
      <template v-slot:years="data">
        {{ dicts.cultural_relic_years[data.scope.years] }}
      </template>
      <template v-slot:level="data">
        {{ dicts.cultural_relic_level[data.scope.level] }}
      </template>
      <template v-slot:textureType="data">
        {{ dicts.cultural_relic_texture[data.scope.textureType] }}
      </template>
      <template v-slot:type="data">
        {{ dicts.cultural_relic_type[data.scope.type] }}
      </template>
      <template v-slot:operates="scope">
        <TableOperation
          :operations="tableOperations"
          :rawData="scope.scope.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="editVisible"
      :form="form"
      @handleClose="handleEditClose"
      @refresh="loadData"
    />
    <UploadListDialog
      :visible="multiUploadVisible"
      :filesList="filesList"
      @handleClose="handleMultiUploadClose"
      @handleCancel="handleMultiUploadCancel"
    />

    <ImportRecordDialog
      :visible="importRecordVisible"
      @handleClose="handleImportRecordClose"
    />
  </div>
</template>

<script>
import TablePage from "@/components/Table/TablePage.vue";
import TableOperation from "@/components/Table/TableOperation.vue";
import SearchBar from "@/components/SearchBar";
import { title, operates, operations } from "./config";
import {
  getCulturalRelicList,
  getRCDetailById,
  deleteCultralRelic,
  editCulturalRelic,
} from "@/api/culturalRelic";
import InfoEditDialog from "./components/InfoEditDialog";
import UploadListDialog from "./components/UploadListDialog";
import ImportRecordDialog from "./components/ImportRecordDialog";

import { importZip } from "@/utils/file";
import { getToken } from "@/utils/auth";
export default {
  components: {
    TablePage,
    TableOperation,
    InfoEditDialog,
    SearchBar,
    ImportRecordDialog,
    UploadListDialog,
  },
  data() {
    return {
      tableHeight: 400,
      list: {
        records: [],
        size: 10,
        current: 1,
        total: 0,
      },
      searchForm: {
        name: "",
        status: "",
      },
      searchConfig: [
        {
          prop: "name",
          type: "input",
          label: "文物名称",
        },
        {
          prop: "status",
          type: "select",
          label: "状态",
          selectOptions: [
            {
              label: "已上架",
              value: "1",
            },
            {
              label: "已下架",
              value: "0",
            },
          ],
        },
      ],
      editVisible: false, //编辑

      isAdd: true,
      form: {
        name: "", //名称
        type: "", //类别（字典值）
        level: "", //文物级别（字典值）
        textureType: "", //质地（字典值）
        detailSize: "", //	具体尺寸
        years: "", //年代
        num: "", //数量
        deptId: "", //收藏馆id——新增传当前用户的deptId
        intro: "", //馆藏介绍
        literature: "", //关联文献。id1,id2,id3
        // directory:'',//	文件夹（字母或者数字命名）
        // regionCode:'',//所属地（分号分隔的编号）——传当前用户的regionCode
        sourceWay: "", //来源方式
        sayExplain: "", //讲解词文件。文件id
        status: 1, //上下架状态(0-下架，1-上架）
        // flag3d:'',//是否有3D图片（字典值：1-有；0-无）
        themeWord: "", //主题词
        url3d: "", //3durl链接
        remark: "", //备注
        audios: "", //音频文件（文件id）
        images: "", //图片文件（文件id，多个以逗号隔开）
        videos: "", //视频文件（文件id）
      },
      loading: false,
      imgViewerVisible: false,
      imgList: [],
      importZipUrl: process.env.VUE_APP_BASE_API + "/bizImport/importZip",
      headers: {
        authorization: getToken(),
      },
      multiUploadVisible: false, //控制批量上传弹窗显示
      importRecordVisible: false, //上传记录
      filesList: [], //上传当中的文件队列
      uploadCount: 0, //处于上传中的文件数量，当等于fileList的时候就关闭弹窗，请求完毕一个就++
      cancelUploadArr: [], //保存每个文件上传接口对应的取消请求的函数[fn,fn,fn...]，点叉叉关闭弹窗就遍历这个全部执行一遍就取消了所以请求，（有那么点点发布订阅的思想，关闭弹窗，通知取消请求，我这里是全部取消，也可以根据需要，取消某一个请求，思想都一样的）
    };
  },

  //watch部分
  watch: {
    //监听弹窗变化
    multiUploadVisible(val) {
      //弹窗关闭记得清空，开启执行批量上传
      if (val) {
        for (let i = 0; i < this.filesList.length; i++) {
          this.uploadSelf(this.filesList[i].file, i); //弹窗显示的时候，就根据文件队列的数量调用上传接口
        }
      } else {
        //弹窗关闭，还原数据到初始位置
        this.filesList = [];
        this.uploadCount = 0;
        this.cancelUploadArr = [];
      }
    },
  },
  computed: {
    tableTitle() {
      return title;
    },
    tableOperates() {
      return operates;
    },
    tableOperations() {
      return operations;
    },
    getStatusTitle(status) {
      return (status) => {
        if (Number(status)) {
          return "是否确定要下架？";
        } else {
          return "是否确定要上架？";
        }
      };
    },
  },
  async created() {
    this.loadData();
  },
  mounted() {
    // this.tableHeight = 500
  },
  methods: {
    async search(form) {
      var params = {
        page: this.list.current,
        limit: this.list.size,
        ...form,
      };
      if (!params.level) {
        delete params.level;
      }
      if (params.status == "") {
        delete params.status;
      }
      let res = await getCulturalRelicList(params);
      if (res.code == 0) {
        this.list = res.data;
      }
    },

    reset() {
      this.loadData();
    },

    //   加载表格数据
    async loadData() {
      var params = {
        page: this.list.current,
        limit: this.list.size,
      };
      let res = await getCulturalRelicList(params);
      if (res.code == 0) {
        // debugger
        this.list = res.data;
      }
    },
    async handleOperation(value, row) {
      switch (value.type) {
        case "add":
          this.editVisible = true;
          break;
        case "view":
          break;
        case "edit":
          let detailRes = await getRCDetailById({ crId: row.crId });
          if (detailRes.code == 0) {
            this.form = detailRes.data;
            this.editVisible = true;
          }
          break;
        case "delete":
          let deleteRes = await deleteCultralRelic([row.crId]);
          if (deleteRes.code == 0) {
            this.$message.success("删除成功！");
            this.loadData();
          }
          break;
        case "multiAdd":
          // debugger
          // this.multiUploadVisible = true;
          // console.log("this.multiUploadVisible", this.multiUploadVisible);

          break;

        case "downloadTemplate":
          this.handleDownloadTemplate();
          break;
        case "viewImportRecord":
          this.importRecordVisible = true;
          break;
      }
    },

    //下载批量导入模板
    handleDownloadTemplate() {
      let a = document.createElement("a");
      a.href = "./static/文物导入模板及操作说明.zip";
      a.download = "文物导入模板及操作说明.zip";
      a.style.display = "none";
      document.body.appendChild(a);
      a.click();
      a.remove();
    },

    // 文件个数超出
    handleExceed() {
      this.$message.error(`超出上传文件个数,请删除以后再上传！`);
    },
    handleUpload(file) {
      this.multiUploadVisible = true; //显示弹窗
      this.filesList.push({
        file,
        name: file.name,
        size: file.size,
        status: null,
        desc: null,
      });
      return false; //阻止自动上传
    },
    uploadSelf(file, index) {
      let formData = new FormData();
      formData.append("type", "biz_cultural_relic");
      formData.append("zipFile", file);
      importZip(
        formData,
        (progressEvent) => this.uploadUnderWayCallback(progressEvent, index),
        (c) => this.cancelCallBack(c, index)
      ).then((res) => {
        if (res.data.code == 0) {
          this.$set(this.filesList[index], "status", "success");
          this.$set(this.filesList[index], "desc", "上传成功");
          this.$message.success("文件" + file.name + "上传成功！");
        } else {
          this.$set(this.filesList[index], "status", "warning");
          this.$set(this.filesList[index], "desc", "上传失败" + res.data.msg);
          this.$message.error("上传失败:" + res.data.msg);
        }
      });
    },

    // 文件上传进度回调
    uploadUnderWayCallback(progressEvent, index) {
      let completeVal =
        (progressEvent.loaded / progressEvent.total) * 100 - 1 || 0; //处理成组件库进度组件需要的格式
      this.$set(this.filesList[index], "percent", Math.floor(completeVal)); //直接改变数组某一项不是响应式的，因此我们需要用到这个api，将其响应式化，添加到数组中
    },

    // 文件取消回调
    cancelCallBack(c, index) {
      this.$set(this.cancelUploadArr, index, c); //添加取消队列中，关闭弹窗批量取消
      this.uploadCount = 0;
    },

    handleMultiUploadClose() {
      // 文件列表中如果Status为null，则代表有仍在上传中
      let isUpLoading = false;
      this.filesList.map((item) => {
        if (item.status == null) {
          isUpLoading = true;
          return;
        }
      });
      let title = isUpLoading ? "当前有上传任务，是否取消上传" : "确认关闭？";
      let confirmButtonText = isUpLoading ? "关闭并取消上传" : "确定";
      let cancelButtonText = isUpLoading ? "否" : "取消";
      let that = this;
      this.$confirm(title, "提示", {
        confirmButtonText,
        cancelButtonText,
        type: "warning",
      })
        .then(() => {
          // 点击取消上传
          if (that.isUpLoading) {
            this.handleCancelAllUpLoad();
            this.$message.warning("已取消上传！");
          }
          this.multiUploadVisible = false; //最后关闭
          this.multiUploadVisible = false;
        })
        .catch(() => {
          console.log("用户取消操作");
        });
    },

    handleMultiUploadCancel(index) {
      if (this.cancelUploadArr[index]) {
        this.cancelUploadArr[index](); //取消上传
        this.cancelUploadArr.splice(index, 1); //从取消队列中删除
      }
      if (this.filesList[index]) {
        this.filesList.splice(index, 1);
      }
      this.$message.info("已取消上传！");
    },

    handleCancelAllUpLoad() {
      this.cancelUploadArr.forEach((cancelCallBack) => cancelCallBack()); //批量取消上传
    },

    handleSuccess(res) {
      res.Success && this.$Message.success("上传成功"); //提示
      this.processModal = false; //成功后关闭弹窗
      this.filesList = [];
    },

    // 关闭预览图片
    closeImgViewer() {
      this.imgViewerVisible = false;
    },
    // 预览图片
    handelPreviewImages(images) {
      this.imgViewerVisible = true;
      this.imgList = [images];
    },
    async handleChangeStatus(row) {
      const { status } = row;
      let newStatus = status === "0" ? "1" : "0";
      const params = {
        ...row,
        status: newStatus,
      };
      let res = await editCulturalRelic(params);
      if (res.code == 0) {
        this.loadData();
        this.$message.success("修改成功！");
      }
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

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

    // 改变当前显示页
    handleCurrentChange(value) {
      this.list.current = value;
      this.loadData();
    },
    // 关闭Dialog
    handleEditClose() {
      this.editVisible = false;
      this.form = {
        status: 0,
      };
    },

    handleImportRecordClose() {
      this.importRecordVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
}
.top-bar {
  // display: flex;
  // justify-content: space-between;
  // align-items: center;
  margin-bottom: 10px;
  height: 68px;
}

// .scoll-area{
//   height: calc(100vh - 170px);
//   overflow: auto;
// }
.tools {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 14px;
  .tools-item {
    display: flex;
    &:last-child {
      justify-content: flex-end;
    }
  }
  .upload-button {
    margin: 0 10px;
  }
}
.pagination {
  margin: 16px;
}
</style>