<template>
  <div>
    <el-input
      v-model="place"
      @focus="changeFoucs"
      @input="changeInput"
      :placeholder="placeholder"
    >
      <i slot="suffix" class="el-icon-search"></i>
    </el-input>

    <div>
      <template v-if="!dialogVisible">
        <el-tag
          v-for="tag in placeList"
          :key="tag.id"
          closable
          :disable-transitions="false"
          @close="handleTagClose(tag.id)"
        >
          {{ tag.name || tag.placeName }}
        </el-tag>
      </template>
    </div>

    <!-- 对话框 -->
    <el-dialog
      title="选择会议室"
      :visible.sync="dialogVisible"
      width="1200px"
      top="8vh"
      :before-close="handleClose"
      append-to-body
      v-if="dialogVisible"
    >
      <el-container class="fullheight" style="border: 1px solid #eee">
        <el-aside
          :width="isShowAside ? '200px' : '0px'"
          style="
            border-right: 1px solid #eee;
            transition: all 0.2s cubic-bezier(0, 0, 0.2, 1);
          "
        >
          <div class="tree-header flex">
            <el-input placeholder="请输入" v-model="filterText" clearable>
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
            <div
              :class="
                isIeExplorer
                  ? 'tree-button-group is-ie-explorer flex'
                  : 'tree-button-group flex'
              "
            >
              <i
                :class="{'icon-zhankai': !isExpand, 'icon-shouqi': isExpand}"
                :title="isExpand ? '收起' : '展开'"
                @click="handleExpandCollapse"
              />
              <i
                class="icon-sync"
                :class="{'icon-spin': loading}"
                title="刷新"
                @click="refresh"
              />
            </div>
          </div>
          <el-tree
            :data="treeData"
            :props="props"
            :load="loadNode"
            :filter-node-method="filterNode"
            :default-checked-keys="defaultCheckedKeys"
            :default-expanded-keys="defaultExpandedKeys"
            node-key="id"
            @node-click="handleNodeClick"
            accordion
            ref="tree"
            highlight-current
            style="background: #fafafa"
          >
            <span class="custom-tree-node" slot-scope="{node}">
              <span>
                <i class="el-icon-s-order icon" style="padding-right: 4px"></i>
                {{ node.label }}
              </span>
            </span>
          </el-tree>
        </el-aside>
        <el-container style="background-color: #fff; height: 600px">
          <div class="shrink" @click="handleHideMenu">
            <i
              :class="
                isShowAside ? 'el-icon-arrow-left' : 'el-icon-arrow-right'
              "
            ></i>
          </div>
          <at-table
            @load="loadData"
            :data="data"
            :page-result="pageResult"
            ref="AtTable"
            @select-all="handleSelect"
            @select="handleSelect"
            @row-click="handleRowClick"
          >
            <template v-slot:searchInput>
              <el-form
                ref="searchForm"
                :model="searchForm"
                label-width="80px"
                class="search-top"
                @submit.native.prevent
              >
                <el-input
                  v-model="searchForm.name"
                  placeholder="请输入会场名称"
                  clearable
                  @keyup.enter.native="handleSearch"
                  @input="handleSearch"
                ></el-input>
                <el-input
                  v-model="searchForm.uri"
                  placeholder="请输入会场标识"
                  clearable
                  @keyup.enter.native="handleSearch"
                  @input="handleSearch"
                ></el-input>
                <el-button
                  size="small"
                  @click="handleSearch"
                  type="primary"
                  class="el-icon-search search-btn"
                  >查询</el-button
                >
                <el-button
                  size="small"
                  @click="handleReset"
                  type="primary"
                  plain
                  class="el-icon-refresh"
                  >重置</el-button
                >
              </el-form>
            </template>

            <template>
              <el-table-column
                type="selection"
                width="55"
                align="center"
                v-if="!this.single"
              >
              </el-table-column>
              <el-table-column align="center" width="50" v-else>
                <template v-slot="{row}">
                  <el-radio
                    @change="changeRadio"
                    @click.native.stop
                    v-model="selectedId"
                    :label="row.id"
                  >
                    {{ '' }}
                  </el-radio>
                </template>
              </el-table-column>
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="60"
              >
              </el-table-column>
              <el-table-column
                prop="name"
                label="会场名称"
                align="center"
                :show-overflow-tooltip="true"
              >
              </el-table-column>
              <el-table-column
                prop="alias"
                label="会场别名"
                align="center"
                :show-overflow-tooltip="true"
              >
                <template v-slot="{row}">
                  {{ row.alias || '-' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="uri"
                label="会场标识"
                align="center"
                :show-overflow-tooltip="true"
              >
              </el-table-column>
              <el-table-column
                prop="type"
                label="会场类型"
                align="center"
                :show-overflow-tooltip="true"
              >
              </el-table-column>
              <el-table-column
                prop="ipAddress"
                label="会场IP地址"
                align="center"
                :show-overflow-tooltip="true"
              >
                <template v-slot="{row}">
                  {{ row.ipAddress || '-' }}
                </template>
              </el-table-column>
              <el-table-column
                prop="sequence"
                label="排序号"
                align="center"
                min-width="100"
                :show-overflow-tooltip="true"
              >
              </el-table-column>
            </template>
          </at-table>
        </el-container>
      </el-container>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleSure">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'EipPleceSelector',
  props: {
    value: {
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
    single: {
      type: Boolean,
      default: false,
    },
    placeList_: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      place: null,
      dialogVisible: false,
      filterText: '', //树型搜索内容
      isIeExplorer: false,
      isExpand: false,
      isShowAside: true, //左侧菜单默认显示
      loading: false,
      props: {
        label: 'name',
        code: 'code',
        id: 'id',
        children: 'children',
        pcode: 'pcode',
        isLeaf: 'leaf', // 指定节点是否为叶子节点，仅在指定了 lazy 属性的情况下生效
      },
      treeData: [{name: '分组管理', code: 'root', id: '1', children: []}],
      defaultCheckedKeys: [], //默认选中节点
      defaultExpandedKeys: ['1'], //默认展开节点
      node: '',
      resolve: '',
      searchForm: {
        name: '',
        uri: '',
      }, //顶部搜索参数
      data: [],
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      selectedId: '', // 单选时选中的id
      placeList: [], //会场列表
    }
  },
  // 超级牛
  model: {
    prop: 'value',
    event: 'change',
  },
  watch: {
    value: {
      immediate: true, // 立即执行 :当刷新页面时会立即执行一次handler函数
      handler(val) {
        this.place = val
      },
    },
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    single: {
      immediate: true,
      handler(val) {
        this.single = val
      },
    },
    placeList_: {
      immediate: true,
      handler(val) {
        this.placeList = val
      },
    },
  },
  mounted() {
    this.getTreeData()
  },
  methods: {
    unique(arr) {
      const res = new Map()
      return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1))
    },
    changeInput() {
      this.placeList = this.unique(this.placeList)
      this.$emit('change', this.place)
      this.$emit('showTag', this.placeList)
    },
    changeFoucs() {
      this.placeList = []
      this.selectedId = ''
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.AtTable.clearSelection()
      })
    },
    handleClose() {
      this.dialogVisible = false
    },
    handleSure() {
      this.dialogVisible = false
      this.changeInput()
    },
    //初始节点
    getTreeData() {
      let params = {
        pageBean: {
          pageSize: -1,
        },
      }
      this.$http
        .post('${xqhk}/bizMeetingPlaceName/v1/getJson', params)
        .then((res) => {
          let resp = res.data.value
          this.treeData[0].children = resp
        })
    },
    //点击节点
    handleNodeClick(data) {
      this.searchForm = {
        name: '',
        uri: '',
      }
      this.form = {}
      if (data.name != '分组管理') {
        this.searchForm.name = data.name
      }
      //根组件查询全部节点数据
      this.$refs.AtTable.load()
    },
    filterNode(value, data) {
      if (!value) return true
      return data[this.props.label].indexOf(value) !== -1
    },
    loadNode(node, resolve) {},
    // 树状菜单的全部展开和收起
    handleExpandCollapse() {
      let elTree = this.$refs.tree
      for (var i = 0; i < elTree.store._getAllNodes().length; i++) {
        elTree.store._getAllNodes()[i].expanded = this.isExpand
      }
      this.isExpand = !this.isExpand
    },
    //树状刷新
    refresh() {
      this.loading = true
      this.$emit('refresh', () => {
        this.loading = false
        this.filterText = ''
        this.getTreeData()
      })
      setTimeout(() => {
        this.loading = false
        this.filterText = ''
      }, 2000)
    },
    closeBefore() {
      setTimeout(() => {
        this.dialogVisible2 = false
        this.getTreeData()
      }, 500)
    },
    //隐藏目录
    handleHideMenu() {
      this.isShowAside = !this.isShowAside
    },
    loadData(param, cb) {
      let query = []
      let search = {
        alias: this.searchForm.alias,
        name: this.searchForm.name,
      }
      for (let i in search) {
        if (search[i]) {
          query.push({
            group: 'advance',
            operation: 'LIKE',
            property: i,
            relation: 'AND',
            value: search[i],
          })
        }
      }
      if (param.querys && param.querys.length) {
        param.querys.push(...query)
      } else {
        param.querys = query
      }

      this.$http
        .post('${xqhk}/bizSiteParamEx/v1/query', param)
        .then(
          (resp) => {
            let response = resp.data
            this.data = response.rows
            this.pageResult = {
              page: response.page,
              pageSize: response.pageSize,
              total: response.total,
            }
          },
          (error) => {
            reject(error)
          }
        )
        .finally(() => {
          if (cb) {
            cb()
          }
        })
    },
    handleSelect(selection) {
      this.placeList = [...selection, ...this.placeList]
      this.place = this.placeList.map((item) => item.name).join(',')
    },
    handleRowClick(data) {
      this.selectedId = data.id
      this.$refs.AtTable.toggleRowSelection(data)
      let rows = this.$refs.AtTable.getSelection()
      if (!this.single) {
        this.placeList = [...rows, ...this.placeList]
        this.place = this.placeList.map((item) => item.name).join(',')
      } else {
        this.placeList = [rows[rows.length-1]] || []
        this.place = this.placeList[0].name
      }
    },
    changeRadio(val) {
      this.selectedId = val
      let data = this.data.filter((item) => item.id == val)
      this.place = data[0].name
      this.placeList = data
    },
    handleTagClose(id) {
      this.placeList = this.placeList.filter((item) => item.id != id)
      this.place = this.placeList.map((item) => item.name).join(',')
      this.$emit('closeTag', this.placeList)
    },
    //查询
    handleSearch() {
      this.pageResult = {
        page: 1,
        pageSize: 20,
        total: 0,
      }
      this.$nextTick(() => {
        this.$refs.AtTable.load()
      })
    },
    handleReset() {
      this.searchForm = {
        name: '',
        uri: '',
      }
      this.$refs['searchForm'].resetFields()
      this.pageResult = {
        page: 1,
        pageSize: 20,
        total: 0,
      }
      this.$nextTick(() => {
        this.$refs.AtTable.load()
      })
    },
    // 防抖(在单位时间内时间再次触发则重新计时)
    debounce(func,wait) {
      let timer = null
      return function(...args) {
        if(timer) clearTimeout(timer)
        timer = setTimeout(() => {
            func.apply(this,args)
        }, wait)
      }
    },
    // 节流(单位时间内不管时间触发多少次，只有一次生效)
    throttle(func, wait){
      let last = 0
      return function(...args) {
        const now = new Date()
        if(now - last > wait) {
          func.apply(this,args)
          last = now
        }
      }
    }
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/common.scss';
.form-empty {
  position: absolute;
  text-align: center;
  width: 300px;
  font-size: 20px;
  top: 200px;
  left: 50%;
  margin-left: -150px;
  color: rgba(0, 0, 0, 0.5);
}
div.tree-header {
  min-height: 30px;
  /deep/ .el-input--small .el-input__inner {
    border: none;
  }
}
div.tree-header >>> .el-input__inner {
  border-width: 0;
  padding-right: 0;
}
div.tree-button-group i {
  cursor: pointer;
  display: inline;
  font-size: 18px;
  font-weight: bold;
  margin-right: 10px;
}
div.tree-button-group i:hover {
  color: lightcoral;
}
.tree-button-group {
  margin-left: 10px;
}
.is-ie-explorer {
  margin-right: 25px;
}
.flex {
  display: flex;
}
>>> .el-dropdown {
  display: none;
}
>>> .el-header {
  border-bottom: 1px solid #ccc;
  button {
    float: right;
    margin-left: 5px;
  }
}

>>> .el-tree-node__content:hover .el-dropdown {
  display: inline-block;
}

>>> .navbar-collapse {
  position: relative;
  top: -60%;
  cursor: pointer;
  width: 20px;
}

>>> .navbar-collapse.navbar-collapse-right {
  top: 40%;
}

>>> .navbar-collapse:hover {
  transform: scale(1) translateY(2px);
}

>>> .navbar-collapse:hover .navbar-collapse-arrow {
  color: #333333;
}

>>> .navbar-collapse-arrow {
  position: relative;
  top: 38%;
  right: 15px;
  font-size: 18px;
  color: #a8a8a8;
}

>>> .navbar-collapse-bg {
  transition: all 0.12s ease;
  height: 50px;
  border-bottom: 8px solid transparent;
  border-right: none;
  border-left: 12px solid #ebebeb;
  border-top: 8px solid transparent;
  opacity: 0.9;
}
.el-aside-footer {
  position: absolute;
  bottom: 18px;
}

.custom-tree-node {
  width: calc(100% - 40px);
  // flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.icon-more {
  font-size: 12px;
  color: #909399;
}
.custom-tree-node .icon-more {
  visibility: hidden;
  font-weight: bold;
}

.custom-tree-node:hover .icon-more {
  visibility: visible;
}
.addDialog /deep/ .el-dialog__body {
  padding-left: 80px;
  padding-right: 80px;
}
.shrink {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  height: 50px;
  border-bottom: 8px solid transparent;
  border-right: none;
  border-left: 12px solid #ebebeb;
  border-top: 8px solid transparent;
  opacity: 0.9;
  cursor: pointer;
  i {
    position: absolute;
    top: 50%;
    left: -14px;
    transform: translateY(-50%);
  }
  &:hover {
    color: #21aeff;
  }
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
