<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">
        <PermissionButton
          button
          size="mini"
          type="primary"
          @click.native="handleOperation({ type: 'downloadTemplate' })"
          icon="el-icon-download"
          :disabled="loading"
          :perms="perms.add"
          style="margin-right: 16px"
        >
          下载导入模板</PermissionButton
        >

        <PermissionButton
          button
          size="mini"
          type="primary"
          @click.native="handleOperation({ type: 'viewImportRecord' })"
          icon="el-icon-document"
          plain
          :perms="perms.add"
          style="margin-right: 16px"
        >
          查看导入记录</PermissionButton
        >

        <PermissionButton
          button
          size="mini"
          type="danger"
          @click.native="handleOperation({ type: 'multiDelete' })"
          icon="el-icon-delete"
          plain
          :perms="perms.delete"
          :disabled="isMultiDisabled"
        >
          批量删除</PermissionButton
        >
      </div>
      <div class="tools-item">
        <PermissionButton
          button
          size="mini"
          type="primary"
          @click.native="handleOperation({ type: 'add' })"
          icon="el-icon-plus"
          :perms="perms.add"
          style="margin-right: 16px"
        >
          添加</PermissionButton
        >
        <PermissionButton
          button
          :perms="perms.add"
          size="mini"
          type="success"
          @click.native="handleOperation({ type: 'multiAdd' })"
          icon="el-icon-upload"
        >
          批量导入</PermissionButton
        >
      </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"
        :selectableFuction="selectableFuction"
        hasMultiSelection
        @handleSelectionChange="handleSelectionChange"
      >
        <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; height: 50px; 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"
      :options="multiUploadOptions"
    />

    <ImportRecordDialog ref="ImportRecordDialog" bizType="biz_cultural_relic" />

    <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,
  deleteDisabledButton,
  searchConfig,
} from "./configs/list";
import perms from "./configs/perms";
import {
  getCulturalRelicListPerTemp,
  getCulturalRelicListPer,
  getRCDetailByIdTemp,
  getRCDetailById,
  deleteCultralRelic,
  deleteCultralRelicTemp,
  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";
import { downloadFile } from "@/utils/file";
export default {
  components: {
    InfoEditDialog,
    ImportRecordDialog,
    UploadDialog,
    View3dDialog,
    PreviewDialog,
  },
  data() {
    return {
      perms, //权限code,很重要
      // （存放两份数据的目的是为了防止切换的时候分页被重置）
      //最终表
      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: {},
      searchParams: {}, //记录SearchForm中的搜索条件
      //批量上传的参数
      multiUploadOptions: {
        bizType: "biz_cultural_relic", //业务类型，文物、展览等biz_cultural_relic——文物，biz_exhibition——展览，如果是文物和展览批量上传必填，抠图不用填
        uploadUrl: process.env.VUE_APP_BASE_API + "/bizImport/importZip", //上传的地址，必填
      },
      multipleSelection: [], //批量选择的数组
    };
  },
  watch: {
    // 监听Tab值不同调取不同的接口
    tabActive(value) {
      this.resetPage();
      this.loadData();
      this.multipleSelection = [];
    },
  },
  computed: {
    getTitle() {
      return this.tabActive == "passed" ? this.passedTitle : this.unPassedTitle;
    },
    getStatusTitle(status) {
      return (status) => {
        if (Number(status)) {
          return "是否确定要下架？";
        } else {
          return "是否确定要上架？";
        }
      };
    },
    getOperations(row) {
      return (row) => {
        const { checkStatus, batchNum } = row;
        const isApprovaling = checkStatus == 0;
        const isMultiAdd = batchNum && batchNum > 0;
        if (this.tabActive == "passed") {
          return [previewButton, deleteButton];
        } else if (isApprovaling) {
          // 审核中的禁用编辑和删除
          return [previewButton, editDisabledButton, deleteDisabledButton];
        } else if (isMultiAdd) {
          return [previewButton, editDisabledButton, deleteButton];
        } else {
          return [previewButton, editButton, deleteButton];
        }
      };
    },
    isMultiDisabled() {
      return this.multipleSelection.length === 0;
    },
  },
  async created() {
    this.loadData();
  },
  methods: {
    async search(form) {
      // 记录搜索的参数
      this.searchParams = form;
      this.resetPage();
      this.loadData(form);
    },
    // 清除分页到初始状态
    resetPage() {
      this.getCurrentList().current = 1;
    },
    // 重置
    reset() {
      this.searchParams = {};
      this.loadData();
    },
    // 加载表格数据
    async loadData(form) {
      const { current, size } = this.getCurrentList();
      var params = {
        page: current,
        limit: size,
      };
      if (!params.level) {
        delete params.level;
      }
      if (params.status == "") {
        delete params.status;
      }
      const queryParams = form || this.searchParams;
      if (Object.keys(queryParams)) {
        params = { ...params, ...queryParams };
      }
      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.add(row);
          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;
        case "multiDelete":
          this.multiDelete();
          break;
      }
    },
    add(row) {
      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;
    },
    // 获取多选中的可被选择项目，true则可被选择
    selectableFuction(row, rowIndex) {
      // 除了审核中的，其他状态都可以删除
      const isApproval = 0;
      if (row.checkStatus !== isApproval) {
        return true;
      }
    },
    // 批量删除
    multiDelete() {
      const ids = this.multipleSelection.map((item) => {
        return item.crId;
      });
      const request = this.getCurrentDeleteRequest();
      const callback = this.loadData;
      this.$bizCommon.multiDelete(request, ids, callback);
    },
    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.$appCommon.openDialog(this, "View3dDialog");
    },

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

    getCurrentDeleteRequest() {
      const currentRequest =
        this.tabActive == "passed"
          ? deleteCultralRelic
          : deleteCultralRelicTemp;
      return currentRequest;
    },

    async edit(row) {
      const { crId } = row;
      let detailRes = await getRCDetailByIdTemp({ crId });
      if (detailRes.code == 0) {
        this.form = detailRes.data;
        this.$appCommon.openDialog(this, "InfoEditDialog");
      }
    },
    async deleteRow(row) {
      const request = this.getCurrentDeleteRequest();
      let deleteRes = await request([row.crId]);
      if (deleteRes.code == 0) {
        this.$message.success("删除成功！");
        this.loadData();
      }
    },
    multiAdd() {
      this.$appCommon.openDialog(this, "UploadDialog");
    },
    viewImport() {
      this.$appCommon.openDialog(this, "ImportRecordDialog");
    },
    //下载批量导入模板
    handleDownloadTemplate() {
      this.loading = true;
      const href = "/files/zip/crImportTemplate.zip";
      const dowmloadName = "文物导入模板及操作说明.zip";
      downloadFile(href, dowmloadName);
      this.loading = false;
    },

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