<template>
  <div
    class="app-container"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.3)"
  >
    <div class="top-bar">
      <SearchBar :config="searchConfig" @search="search" @reset="reset" />
      <div class="tools">
        <el-button
          type="primary"
          @click.native="handleOperation({ type: 'multiAdd' })"
          icon="el-icon-upload"
        >
          批量导入</el-button
        >
        <el-button
          type="primary"
          @click.native="handleOperation({ type: 'add' })"
          icon="el-icon-plus"
        >
          添加</el-button
        >
      </div>
    </div>
    <TablePage
      :data="list.records"
      :tableTitle="tableTitle"
      :operates="tableOperates"
    >
      <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.faceImageUrl"
          alt="查看大图"
          v-if="data.scope.faceImageUrl"
          style="cursor: pointer"
          width="100px"
          @click="handelPreviewImages(data.scope.faceImageUrl)"
        />
      </template>
      <template v-slot:years="data">
        {{ dict.cultural_relic_years[data.scope.years] }}
      </template>
      <template v-slot:level="data">
        {{ dict.cultural_relic_level[data.scope.level] }}
      </template>
      <template v-slot:textureType="data">
        {{ dict.cultural_relic_texture[data.scope.textureType] }}
      </template>
      <template v-slot:type="data">
        {{ dict.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"
    />
    <MultiUploadDialog
      :visible="multiUploadVisible"
      @handleClose="handleMultiUploadClose"
    />
  </div>
</template>

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

import SearchBar from "@/components/SearchBar";

export default {
  components: {
    TablePage,
    TableOperation,
    InfoEditDialog,
    SearchBar,
    MultiUploadDialog
  },
  dicts: [
    // "cultural_relic_years",
    "culturalRelicLevel",
    // "cultural_relic_texture",
    "culturalRelicType",
  ],
  data() {
    return {
      list: {
        records: [],
        size: 10,
        current: 1,
        total: 0,
      },
      searchForm: {
        name: "",
        status: "",
      },
      searchConfig: [
        {
          prop: "name",
          type: "input",
          label: "文物名称",
        },
        // {
        //   prop: "level",
        //   type: "select",
        //   label: "文物级别",
        //   selectOptions: [],
        // },
        {
          prop: "status",
          type: "select",
          label: "状态",
          selectOptions: [
            {
              label: "已上架",
              value: "1",
            },
            {
              label: "已下架",
              value: "0",
            },
          ],
        },
      ],
      editVisible: false, //编辑
      multiUploadVisible: 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: 0, //上下架状态(0-下架，1-上架）
        // flag3d:'',//是否有3D图片（字典值：1-有；0-无）
        themeWord: "", //主题词
        url3d: "", //3durl链接
        remark: "", //备注
        audios: "", //音频文件（文件id）
        images: "", //图片文件（文件id，多个以逗号隔开）
        videos: "", //视频文件（文件id）
      },
      loading: false,
      imgViewerVisible: false,
      imgList: [],
    };
  },
  watch: {
    dict(value) {
      if (value) {
        this.dict = value;
      }
    },
  },
  computed: {
    tableTitle() {
      return title;
    },
    tableOperates() {
      return operates;
    },
    tableOperations() {
      return operations;
    },
    getStatusTitle(status) {
      return (status) => {
        if (Number(status)) {
          return "是否确定要下架？";
        } else {
          return "是否确定要上架？";
        }
      };
    },
  },
  mounted() {
    this.loadData();
  },
  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;
      }
      console.log("params", params);
      let res = await getCulturalRelicList(params);
      if (res.code == 0) {
        this.list = res.data;
      }
    },

    reset() {
      console.log("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) {
      console.log("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":
          this.multiUploadVisible = true
          break;
      }
    },
    // 关闭预览图片
    closeImgViewer() {
      this.imgViewerVisible = false;
    },
    // 预览图片
    handelPreviewImages(images) {
      this.imgViewerVisible = true;
      if (images.length > 1) {
        this.imgList = images.split(",");
      } else {
        this.imgList = [images];
      }
    },
    async handleChangeStatus(row) {
      console.log("status", 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();
    },

    // 搜索
    onSubmitSearch() {
      console.log("submit!");
    },

    // 打开drawer
    handleOpenDialog(type, value) {
      this.editVisible = true;
      switch (type) {
        case "add":
          console.log("新增");
          break;
        case "edit":
          console.log("编辑", value);
          break;
      }
    },
    // 关闭Dialog
    handleEditClose() {
      this.editVisible = false;
      this.form = {
        status: 0,
      };
    },
    handleMultiUploadClose() {
      this.multiUploadVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.top-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}
.pagination {
  margin: 16px;
}
</style>