<template>
  <div class="app-container">
    <div class="top-bar">
      <SearchBar :config="searchConfig" @search="search" @reset="reset" />
      <PermissionButton
        perms="sys:dept:add"
        size="mini"
        type="primary"
        @click.native="handleOperation('add')"
        button
      >
        <i class="el-icon-plus"></i>
        添加</PermissionButton
      >
    </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">
          <PermissionButton
            :perms="'sys:dept:update'"
            type="primary"
            size="mini"
            icon="el-icon-edit"
            @click.native="handleOperation('edit', scope.row)"
            style="margin-right: 16px"
            >编辑</PermissionButton
          >
          <el-popconfirm
            title="确定删除吗？"
            @confirm="handleOperation('delete', scope.row)"
          >
            <PermissionButton
              :perms="'sys:dept:deleted'"
              size="mini"
              type="danger"
              icon="el-icon-delete"
              slot="reference"
              >删除</PermissionButton
            >
          </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 InfoEditDialog from "./components/InfoEditDialog";
import { deleteMuseum, editMuseum } from "@/api/org";
export default {
  components: {
    InfoEditDialog,
  },
  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: {
    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) => {
          if (res[0].pid == "0") {
            this.orgTreeData = res[0].children;
            this.tableData = res[0].children;
          } else {
            this.orgTreeData = res;
            this.tableData = res;
          }

          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) {
      const callback = this.loadData;
      this.$bizCommon.changeStatus(row, editMuseum, callback);
    },
    // 多选
    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>
