<template>
  <div class="app-container">
    <div class="top-bar">
      <SearchBar :config="searchConfig" @search="search" @reset="reset" />
      <el-button type="primary" @click.native="handleOperation('add')">
        <i class="el-icon-plus"></i>
        添加</el-button>
    </div>

    <el-table :tree-props="{ children: 'children' }" fit row-key="id" :data="orgTreeData" border stripe
      default-expand-all v-loading="loading">
      <el-table-column type="index" width="50" label="序号" align="center"> </el-table-column>
      <el-table-column align="center" prop="name" label="名称"></el-table-column>
      <el-table-column align="center" prop="regionName" label="归属地"></el-table-column>
      <el-table-column align="center" prop="status" label="状态">
        <template slot-scope="scope">
          <el-popconfirm :title="getStatusTitle(scope.row.status)" @confirm="handleChangeStatus(scope.row)">
            <el-switch slot="reference" :value="Boolean(Number(scope.row.status))"></el-switch>
          </el-popconfirm>
        </template>
      </el-table-column>
      <el-table-column align="center" label="封面">
        <template slot-scope="scope">
          <img :src="scope.row.faceImageUrl" style="cursor: pointer" width="100px"
            @click="handelPreviewImages(scope.row.faceImageUrl)" />
        </template>
      </el-table-column>
      <el-table-column align="center" prop="longitude" label="经度">
      </el-table-column>
      <el-table-column align="center" prop="latitude" label="纬度">
      </el-table-column>
      <!-- <el-table-column
        align="center"
        prop="intro"
        label="简介"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <span v-html="scope.row.intro"></span>
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" @click.native="handleOperation('edit', scope.row)"
            style="margin-right: 4px">编辑</el-button>
          <el-popconfirm title="确定删除吗？" @confirm="handleOperation('delete', scope.row)">
            <el-button type="danger" size="mini" icon="el-icon-delete" slot="reference">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <InfoEditDialog :visible="drawerVisible" :form="form" :orgTreeData="orgTreeData" @handleClose="handleClose"
      @refresh="loadData" />
    <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 { title, operates, operations } from "./config";
import InfoEditDialog from "./components/InfoEditDialog";
import SearchBar from "@/components/SearchBar";
import { deleteMuseum, editMuseum } from "@/api/org";
export default {
  components: {
    TablePage,
    TableOperation,
    InfoEditDialog,
    SearchBar,
    "el-image-viewer": () =>
      import("element-ui/packages/image/src/image-viewer"),
  },
  data() {
    return {
      list: [],
      searchForm: {
        name: "",
        status: "",
      },
      searchConfig: [
        {
          prop: "name",
          type: "input",
          label: "博物馆名称",
        },
        // {
        //   prop: "regionCode",
        //   type: "select",
        //   label: "地区",
        //   selectOptions: [

        //   ],
        // },
      ],
      drawerVisible: false,
      isAdd: true,
      form: {
        name: "", //名称
        intro: "",
        latitude: "", //纬度
        longitude: "", //经度
        faceImage: "",
        pid: "", //所属部门id
        regionCode: "", //所属地code
      },
      loading: false,
      orgTreeData: [],
      expandRow: [],
      tableData: [],
      imgList: [],
      imgViewerVisible: false,
    };
  },
  computed: {
    tableTitle() {
      return title;
    },
    tableOperates() {
      return operates;
    },
    tableOperations() {
      return operations;
    },
    getStatusTitle(status) {
      return (status) => {
        if (Number(status)) {
          return "是否确定要下架？";
        } else {
          return "是否确定要上架？";
        }
      };
    },
  },
  created() {
    this.loadData(true);
  },
  watch: {
    'searchForm.name': function (value) {
      console.log(value);
    }
  },
  methods: {
    async search(form) {
      let searchValue = form.name;
      let treeData = this.orgTreeData;
      let handleTreeData = this.handleTreeData(treeData, searchValue);
      // debugger;
      this.setExpandRow(handleTreeData);
      this.expandRow = this.expandRow.join(",").split(",");
      this.orgTreeData = handleTreeData;
    },

    //  树形表格过滤
    handleTreeData(treeData, searchValue) {
      // debugger
      if (!treeData || treeData.length === 0) {
        return [];
      }
      const array = [];
      for (let i = 0; i < treeData.length; i += 1) {
        let match = false;
        for (let pro in treeData[i]) {
          if (typeof treeData[i][pro] == "string") {
            match |= treeData[i][pro].includes(searchValue);
            if (match) break;
          }
        }
        if (
          this.handleTreeData(treeData[i].children, searchValue).length > 0 ||
          match
        ) {
          array.push({
            ...treeData[i],
            children: this.handleTreeData(treeData[i].children, searchValue),
          });
        }
      }
      return array;
    },

    setExpandRow(handleTreeData) {
      if (handleTreeData.length) {
        for (let i of handleTreeData) {
          // debugger
          this.expandRow.push(i.id);
          if (i.children.length) {
            this.setExpandRow(i.children);
          }
        }
      }
    },

    reset() {
      this.loadData();
    },

    /**
     * 加载表格数据
     * @param  isReload {Boolean} 是否需要重新调用接口加载，默认不传则从vuex中获取
     */
    loadData(isReload) {
      this.loading = true
      this.$store.dispatch("org/getMuseumTreeData", isReload).then((res) => {
        this.orgTreeData = res[0].children
        this.tableData = res[0].children
        this.loading = false
      }).catch(err => {
        this.loading = false
      });
    },

    async handleOperation(type, row) {
      console.log("handleOperation", type, row);
      switch (type) {
        case "add":
          this.drawerVisible = true;
          break;
        case "edit":
          this.form = row;
          this.drawerVisible = true;
          break;
        case "delete":
          const { id } = row;
          let res = await deleteMuseum(id);
          if (res.code == 0) {
            this.$message.success("删除成功！");
            this.loadData(true);
          }
          break;
      }
    },
    async handleChangeStatus(row) {
      // debugger

      const { status } = row;
      let newStatus = status ? "0" : "1";
      const params = {
        ...row,
        status: newStatus,
      };
      // console.log(params);
      //  return
      let res = await editMuseum(params);
      if (res.code == 0) {
        this.loadData(true);
        this.$message.success("修改成功！");
      }
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 改变页容量
    handleSizeChange(value) {
      this.list.size = value;
      this.loadData(true);
    },

    // 改变当前显示页
    handleCurrentChange(value) {
      this.list.current = value;
      this.loadData(true);
    },

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

    // 打开drawer
    handleOpenDialog(type, value) {
      this.drawerVisible = true;
      switch (type) {
        case "add":
          console.log("新增");
          break;
        case "edit":
          console.log("编辑", value);
          break;
      }
    },
    // 关闭Dialog
    handleClose() {
      this.drawerVisible = false;
      this.form = {};
    },

    // 预览图片
    handelPreviewImages(images) {
      this.imgViewerVisible = true;
      if (images.length > 1) {
        this.imgList = images.split(",");
      } else {
        this.imgList = [images];
      }
    },

    // 关闭预览图片
    closeImgViewer() {
      this.imgViewerVisible = false;
    },
  },
};
</script>

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

.pagination {
  margin: 16px;
}
</style>