<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="list.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="operations"
            :rawData="scope.scope.row"
            @handleOperation="handleOperation"
          ></TableOperation>
        </template>
      </TablePage>
      <el-pagination
        background
        @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>
    </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 TablePage from "@/components/Table/TablePage.vue";
import TableOperation from "@/components/Table/TableOperation.vue";
import SearchBar from "@/components/SearchBar";
import { passedTitle, unPassedTitle, operates, operations } from "./config";
import {
  getCulturalRelicListPer,
  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: {
    TablePage,
    TableOperation,
    InfoEditDialog,
    SearchBar,
    ImportRecordDialog,
    UploadDialog,
    View3dDialog,
    "el-image-viewer": () =>
      import("element-ui/packages/image/src/image-viewer"),
  },
  data() {
    return {
      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",
            },
          ],
        },
        // 是否只看3D
        {
          prop: "onlyShow3d",
          type: "checkbox",
          label: "只看3D",
        },
      ],
      editVisible: false, //编辑
      isAdd: true,
      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: [],
      isUpLoading: false,
      view3dDialogVisible: false, //3D文件在线浏览弹窗可见性
      passedTitle,
      unPassedTitle,
      operates,
      operations,
      tabActive: "unPassed",
    };
  },

  //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 = [];
    //   }
    // },
    // 监听Tab值不同调取不同的接口
    tabActive(value) {
      if (value == "passed") {
        console.log("passed to do");
      } else {
        console.log("unPassed to do");
      }
    },
  },
  computed: {
    getStatusTitle(status) {
      return (status) => {
        if (Number(status)) {
          return "是否确定要下架？";
        } else {
          return "是否确定要上架？";
        }
      };
    },
  },
  async created() {
    this.loadData();
  },
  methods: {
    async search(form) {
      var params = {
        page: 1,
        limit: this.list.size,
        ...form,
      };
      if (!params.level) {
        delete params.level;
      }
      if (params.status == "") {
        delete params.status;
      }
      let res = await getCulturalRelicListPer(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 getCulturalRelicListPer(params);
      if (res.code == 0) {
        // debugger
        this.list = res.data;
      }
    },
    async handleOperation(value, row) {
      console.log(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 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.$refs.UploadDialog.visible = true;
          // console.log("this.multiUploadVisible", this.multiUploadVisible);
          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.list.size = value;
      this.loadData();
    },

    // 改变当前显示页
    handleCurrentChange(value) {
      this.list.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>
