<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="getTitle"
        :operates="operates"
      >
        <template v-slot:sourceWay="{ scope }">
          <DictText
            name="culturalRelicSourceWay"
            :dictValue="scope.sourceWay"
          />
        </template>
        <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:checkStatus="{ scope }">
          <el-tag
            :type="
              $constantsTool.getTagTypeByValue('checkStatus', scope.checkStatus)
            "
            >{{
              $constantsTool.getLabelByValue("checkStatus", scope.checkStatus)
            }}</el-tag
          >
        </template>
        <template v-slot:faceImageUrl="{ scope }">
          <img
            :src="$getFullUrl(scope.faceImagePressUrl || scope.faceImageUrl)"
            alt="暂无图片"
            style="
              cursor: pointer;
              width: 80px;
              height: 80px;
              object-fit: contain;
            "
            @click="handelPreviewImages(scope.faceImageUrl)"
          />
        </template>
        <template v-slot:operates="{ scope }">
          <TableOperation
            :operations="getOperations(scope)"
            :rawData="scope"
            @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 ref="InfoEditDialog" :form="form" @refresh="loadData" />
    <UploadDialog ref="UploadDialog" @update="loadData" />

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

    <View3dDialog ref="View3dDialog" />

    <PreviewDialog ref="PreviewDialog" :info="previewInfo" />

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

<script>
import {
  passedTitle,
  unPassedTitle,
  operates,
  previewButton,
  editButton,
  deleteButton,
  editDisabledButton,
  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 PreviewDialog from "./components/PreviewDialog";
import View3dDialog from "./components/View3dDialog";
import { rules } from "./configs/validateRules";
import boutiqueTool from "@/utils/boutique";
export default {
  components: {
    InfoEditDialog,
    ImportRecordDialog,
    UploadDialog,
    View3dDialog,
    PreviewDialog,
  },
  data() {
    return {
      // （存放两份数据的目的是为了防止切换的时候分页被重置）
      //最终表
      list: {
        records: [],
        size: 10,
        current: 1,
        total: 0,
      },
      // 临时表
      listTemp: {
        records: [],
        size: 10,
        current: 1,
        total: 0,
      },
      searchConfig,
      editVisible: false, //编辑
      form: {},
      loading: false,
      imgViewerVisible: false,
      importRecordVisible: false, //上传记录
      imgList: [],
      passedTitle,
      unPassedTitle,
      operates,
      tabActive: "unPassed",
      previewInfo: {},
    };
  },
  watch: {
    // 监听Tab值不同调取不同的接口
    tabActive(value) {
      this.resetPage();
      this.loadData();
    },
  },
  computed: {
    getTitle() {
      return this.tabActive == "passed" ? this.passedTitle : this.unPassedTitle;
    },
    getStatusTitle(status) {
      return (status) => {
        if (Number(status)) {
          return "是否确定要下架？";
        } else {
          return "是否确定要上架？";
        }
      };
    },
    getOperations(row) {
      return (row) => {
        if (this.tabActive == "passed") {
          return [previewButton, deleteButton];
        } else if (row.checkStatus == 0) {
          // 审核中的禁用编辑
          return [previewButton, editDisabledButton, deleteButton];
        } else {
          return [previewButton, editButton, deleteButton];
        }
      };
    },
  },
  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.form = {
            name: "", //名称
            type: "", //类别（字典值）
            level: "", //文物级别（字典值）
            textureType: "", //质地（字典值）
            detailSize: "", //	具体尺寸
            years: "", //年代
            num: 1, //数量
            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）
          };
          this.$refs.InfoEditDialog.visible = true;
          break;

        case "view":
          this.view(row);
          break;
        case "view3D":
          this.view3d(row);
          break;
        case "edit":
          this.edit(row);
          break;
        case "delete":
          this.deleteRow(row);
          break;
        case "multiAdd":
          this.multiAdd();
          break;

        case "downloadTemplate":
          this.handleDownloadTemplate();
          break;
        case "viewImportRecord":
          this.viewImport();
          break;
      }
    },
    async view(row) {
      if (!row) {
        return;
      }
      if (boutiqueTool.isBoutique(row.title)) {
        this.$message.info("精品展暂不支持预览！");
        return;
      }
      const request = this.getCurrentPreviewRequest();
      const { crId } = row;
      let res = await request({
        crId,
      });
      if (res.data) {
        this.previewInfo = res.data;
        this.$refs.PreviewDialog.visible = true;
      } else {
        this.$message.error("暂无数据！");
      }
    },
    view3d(row) {
      this.$refs.View3dDialog.visible = true;
    },

    getCurrentPreviewRequest() {
      const currentRequest =
        this.tabActive == "passed" ? getRCDetailById : getRCDetailByIdTemp;
      return currentRequest;
    },

    async edit(row) {
      const { crId } = row;
      let detailRes = await getRCDetailByIdTemp({ crId });
      if (detailRes.code == 0) {
        this.form = detailRes.data;
        this.$refs.InfoEditDialog.visible = true;
      }
    },
    async deleteRow(row) {
      let deleteRes = await deleteCultralRelic([row.crId]);
      if (deleteRes.code == 0) {
        this.$message.success("删除成功！");
        this.loadData();
      }
    },
    multiAdd() {
      this.$refs.UploadDialog.visible = true;
    },
    viewImport() {
      this.importRecordVisible = true;
    },
    //下载批量导入模板
    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 callback = this.loadData;
      this.$bizCommon.changeStatus(row, editCulturalRelic, callback);
    },
    // 多选
    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;
    },
  },
};
</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>
