<template>
  <div class="app-container" v-loading="loading">
    <SearchBar
      :config="searchConfig"
      @search="search"
      @reset="reset"
      class="search-bar"
    />
    <div class="tools">
      <div class="tools-item">
        <el-button
          size="mini"
          type="primary"
          @click.native="handleOperation({ type: 'downloadTemplate' })"
          icon="el-icon-download"
          :disabled="loading"
        >
          下载导入模板</el-button
        >

        <el-button
          size="mini"
          type="primary"
          @click.native="handleOperation({ type: 'viewImportRecord' })"
          icon="el-icon-document"
          plain
        >
          查看导入记录</el-button
        >
      </div>
      <div class="tools-item">
        <el-button
          size="mini"
          type="primary"
          @click.native="handleOperation({ type: 'add' })"
          icon="el-icon-plus"
        >
          添加</el-button
        >
        <el-button
          size="mini"
          type="success"
          @click.native="handleOperation({ type: 'multiAdd' })"
          icon="el-icon-upload"
        >
          批量导入</el-button
        >
      </div>
    </div>
    <div class="list">
      <el-tabs v-model="tabActive">
        <el-tab-pane label="待办" name="unPassed"></el-tab-pane>
        <el-tab-pane label="已审核通过" name="passed"></el-tab-pane>
      </el-tabs>
      <TablePage
        :data="getCurrentList().records"
        :tableTitle="passedTitle"
        :operates="operates"
      >
        <template v-slot:status="data">
          <el-popconfirm
            :title="getStatusTitle(data.scope.status)"
            @confirm="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="
              $getFullUrl(
                data.scope.faceImagePressUrl || data.scope.faceImageUrl
              )
            "
            alt="暂无图片"
            style="
              cursor: pointer;
              width: 80px;
              height: 80px;
              object-fit: contain;
            "
            @click="handelPreviewImages(data.scope.faceImageUrl)"
          />
        </template>
        <template v-slot:operates="scope">
          <TableOperation
            :operations="getOperations"
            :rawData="scope.scope.row"
            @handleOperation="handleOperation"
          ></TableOperation>
        </template>
      </TablePage>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="Number(getCurrentList().current)"
        :page-sizes="[10, 20, 40, 50]"
        :page-size="Number(getCurrentList().size)"
        layout="total, sizes, prev, pager, next, jumper"
        :total="Number(getCurrentList().total)"
        class="pagination"
      >
      </el-pagination>
    </div>

    <InfoEditDialog
      :visible="editVisible"
      :form="form"
      @handleClose="handleEditClose"
      @refresh="loadData"
    />
    <UploadDialog ref="UploadDialog" @update="loadData" />

    <ImportRecordDialog
      :visible="importRecordVisible"
      @reload="loadData"
      @handleClose="handleImportRecordClose"
    />

    <View3dDialog
      ref="View3dDialog"
      :visible="view3dDialogVisible"
      @handleClose="handleView3dDialogClose"
    />

    <el-image-viewer
      v-if="imgViewerVisible"
      :on-close="closeImgViewer"
      :url-list="imgList"
    />
  </div>
</template>

<script>
import {
  passedTitle,
  unPassedTitle,
  operates,
  operations,
  operationsTemp,
  searchConfig,
} from "./configs/list";
import {
  getCulturalRelicListPerTemp,
  getCulturalRelicListPer,
  getRCDetailByIdTemp,
  getRCDetailById,
  deleteCultralRelic,
  editCulturalRelic,
} from "@/api/culturalRelic";
import InfoEditDialog from "./components/InfoEditDialog";
import UploadDialog from "./components/UploadDialog";
import ImportRecordDialog from "./components/ImportRecordDialog";
import View3dDialog from "./components/View3dDialog";

export default {
  components: {
    InfoEditDialog,
    ImportRecordDialog,
    UploadDialog,
    View3dDialog,
  },
  data() {
    return {
      // （存放两份数据的目的是为了防止切换的时候分页被重置）
      //最终表
      list: {
        records: [],
        size: 10,
        current: 1,
        total: 0,
      },
      // 临时表
      listTemp: {
        records: [],
        size: 10,
        current: 1,
        total: 0,
      },
      searchConfig,
      editVisible: false, //编辑
      form: {
        name: "", //名称
        type: "", //类别（字典值）
        level: "", //文物级别（字典值）
        textureType: "", //质地（字典值）
        detailSize: "", //	具体尺寸
        years: "", //年代
        num: 1, //数量
        deptId: "", //收藏馆id——新增传当前用户的deptId
        intro: "", //馆藏介绍
        literature: "", //关联文献。id1,id2,id3
        // directory:'',//	文件夹（字母或者数字命名）
        // regionCode:'',//所属地（分号分隔的编号）——传当前用户的regionCode
        sourceWay: "", //来源方式
        sayExplain: "", //讲解词文件。文件id
        status: true, //上下架状态(0-下架，1-上架）
        // flag3d:'',//是否有3D图片（字典值：1-有；0-无）
        themeWord: "", //主题词
        url3d: "", //3durl链接
        remark: "", //备注
        audios: "", //音频文件（文件id）
        images: "", //图片文件（文件id，多个以逗号隔开）
        videos: "", //视频文件（文件id）
      },
      loading: false,
      imgViewerVisible: false,
      importRecordVisible: false, //上传记录
      imgList: [],
      view3dDialogVisible: false, //3D文件在线浏览弹窗可见性
      passedTitle,
      unPassedTitle,
      operates,
      operations,
      operationsTemp,
      tabActive: "unPassed",
    };
  },
  watch: {
    // 监听Tab值不同调取不同的接口
    tabActive(value) {
      this.resetPage();
      this.loadData();
    },
  },
  computed: {
    getStatusTitle(status) {
      return (status) => {
        if (Number(status)) {
          return "是否确定要下架？";
        } else {
          return "是否确定要上架？";
        }
      };
    },
    getOperations() {
      return this.tabActive == "passed" ? this.operations : this.operationsTemp;
    },
  },
  async created() {
    this.loadData();
  },
  methods: {
    async search(form) {
      this.resetPage();
      this.loadData(form);
    },
    // 清除分页到初始状态
    resetPage() {
      this.getCurrentList().current = 1;
    },
    reset() {
      this.loadData();
    },
    // 加载表格数据
    async loadData(form) {
      const { current, size } = this.getCurrentList();
      var params = {
        page: current,
        limit: size,
        ...form,
      };
      if (!params.level) {
        delete params.level;
      }
      if (params.status == "") {
        delete params.status;
      }
      const currentRequest = this.getCurrentRequest();
      const res = await currentRequest(params);
      if (res.code == 0) {
        this.setList(res.data);
      }
    },
    // 获取当前请求方法
    getCurrentRequest() {
      const currentRequest =
        this.tabActive == "passed"
          ? getCulturalRelicListPer
          : getCulturalRelicListPerTemp;
      return currentRequest;
    },

    // 设置两张表的数据
    setList(data) {
      if (this.tabActive === "passed") {
        this.list = data;
      } else {
        this.listTemp = data;
      }
    },
    // 获取当前加载的list
    getCurrentList() {
      const currentList =
        this.tabActive == "passed" ? this.list : this.listTemp;
      return currentList;
    },

    async handleOperation(value, row) {
      switch (value.type) {
        case "add":
          this.editVisible = true;
          break;
        case "view3D":
          console.log(value, row);
          this.$refs.View3dDialog.visible = true;
          break;
        case "edit":
          let detailRes = await getRCDetailByIdTemp({ 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":
          this.$refs.UploadDialog.visible = true;
          break;

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

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

    // 关闭预览图片
    closeImgViewer() {
      this.imgViewerVisible = false;
    },
    // 预览图片
    handelPreviewImages(images) {
      // debugger
      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.getCurrentList().size = value;
      this.loadData();
    },

    // 改变当前显示页
    handleCurrentChange(value) {
      this.getCurrentList().current = value;
      this.loadData();
    },
    // 关闭Dialog
    handleEditClose() {
      this.editVisible = false;
      this.form = {
        status: 1,
        num: 1,
      };
    },
    // 关闭导入记录弹窗
    handleImportRecordClose() {
      this.importRecordVisible = false;
    },
    // 关闭预览3D弹窗
    handleView3dDialogClose() {
      this.view3dDialogVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;
}
.search-bar {
  margin-bottom: 16px;
}

.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;
  display: flex;
  justify-content: right;
}
</style>
