<template>
  <div class="table-main">
    <div v-if="controllable" class="table-tools">
      <div class=" clearfix">
        <div class="tools-left fl">
          <div class="tools-search-item" v-for="(tools, index) in tools" :key="index">
            <label>{{ tools.label }}</label>
            <Select clearable  v-model="pageParam[`tools_${index}`]" style="width:240px" size="large" :placeholder="tools.placeholder" filterable @on-change="handleTableData">
              <Option v-for="item in tools.options" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </div>
          <div class="tools-search-item">
            <Input :placeholder="placeholder" v-model="pageParam.searchKey" style="width: 240px" size="large" @on-enter="handleTableData" @on-click="handleTableData">
                <Icon type="ios-search" slot="suffix" />
            </Input>
          </div>
        </div>
        <!-- 顶部按钮组，由父组件:buttonList 传递 -->
      <div v-if="buttonList.length > 0" class="button-group fr">
        <Button
          v-for="(btn, index) in buttonList"
          :key="index"
          size="large"
          :type="btn.type ? btn.type : 'primary'"
          @click="btnHandle(btn.handle, btn.param)"
        >{{ btn.text }}</Button>
      </div>
      </div>
      
    </div>
    <Table :data="tableData" :columns="tableColumns" @on-selection-change="handleSelect">
      <template slot="action" slot-scope="{ row, index }">
        <handleBtns
          :tools-btn-group="toolsBtnGroup"
          :row="row"
          @handleClickBtn="handleRowBtn"
        />
      </template>
    </Table>
    <div style="margin-top: 20px; overflow: hidden;">
      <div style="float: right;">
        <Page
          v-if="pageParam.total > 0"
          :current.sync="pageParam.current"
          :total="pageParam.total"
          :page-size="pageParam.pageSize"
          class-name="tatle-page"
          size="small"
          show-total
          show-elevator
          @on-change="changePage"
        />
      </div>
    </div>
  </div>
</template>

<script>
import handleBtns from './handle-btns.vue'

export default {
  name: 'Tables',
  components: {
    handleBtns
  },
  props: {
    // 从父组件得到的数据接口
    dataApi: Function,
    deleteApi: Function,
    deleteIdKey: String,
    // 从父组件得到的表格列数据
    columns: {
      type: Array,
      default() {
        return []
      }
    },
    tools: {
      type: Array,
      default () {
        return []
      }
    },
    // 是否显示工具控件
    controllable: {
      type: Boolean,
      default: true
    },
    // 是否显示按钮组
    buttonList: {
      type: Array,
      default() {
        return []
      }
    },
    long: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: '房源ID/名称/经纪人'
    }
  },
  data() {
    return {
      // 通过dataApi获取，处理后的单元格数据
      tableData: [],
      // 通过props获取后，处理后的表格列数据
      tableColumns: [],
      // 工具按钮组
      toolsBtnGroup: [],
      time: null,
      pageParam: { pageNum: 1, pageSize: 10, searchKey: '', total: 0, current: 1, tools_0: '', tools_1: '' }
    }
  },
  computed: {
    access() {
      return this.$store.state.user.access
    }
  },
  watch: {
    // 监听搜索框，并在用户在时间间隔内只发送一次请求
    'pageParam.searchKey'() {
      this.$bebounce(this.handleTableData, { pageNum: 1, current: 1 })
    },
    columns() {
      this.handleTableData()
    }
  },
  created() {
  },
  mounted() {
    this.handleColumns(this.columns)
    if (this.long) {
      this.time = window.setInterval(() => {
        setTimeout(this.handleTableData, 0)
      }, 3000)
    }
    this.handleTableData()
  },
  beforeDestroy() {
    clearInterval(this.time)
  },
  methods: {
    // 处理表格列数据
    handleColumns(columns) {
      this.tableColumns = columns.map(item => {
        const res = item
        // 当表格列数据存在 slot 时，特殊处理
        if (item.slot === 'action') this.slotAction(res)
        return res
      })
    },
    // 处理表格列中 含有 slot 的项
    slotAction(item) {
      const arr = ['admin', 'edit']
      const access = this.access.some(i => arr.includes(i))
      const { tools = [] } = item
      // this.toolsBtnGroup = access ? tools : tools.filter(item => item == 'view' || item == 'del')
      this.toolsBtnGroup = tools
    },
    // 处理单元格数据
    handleTableData(param) {
      const fetchParam = Object.assign(this.pageParam, param)
      this.dataApi(fetchParam).then(
        res => {
          const { data } = res
          const list = data.list || data
          // list.forEach(item => {
          //   if (item.roleKey === 'admin') item._disabled = true
          //   item.orientation = this.oriAction(item.orientation)
          // })
          this.tableData = list
          this.pageParam.total = data.totalNum || data.total
        }
      )
    },
    // 处理表格列中 朝向 的项
    oriAction(ori) {
      const aspectList = [
        {
          value: 'E',
          label: '东'
        },
        {
          value: 'W',
          label: '西'
        },
        {
          value: 'S',
          label: '南'
        },
        {
          value: 'N',
          label: '北'
        },
        {
          value: 'ES',
          label: '东南'
        },
        {
          value: 'EN',
          label: '东北'
        },
        {
          value: 'WS',
          label: '西南'
        },
        {
          value: 'WN',
          label: '西北'
        }
      ]
      for (let i = 0; i < aspectList.length; i++) {
        if (aspectList[i].value === ori) {
          return aspectList[i].label
        }
      }
    },
    // 选中某列 返回选中的数据
    handleSelect(selection) {
      this.$emit('chooseSelection', selection)
    },
    // 按钮事件
    btnHandle(handleName, param) {
      
      this.$emit(handleName, param)
    },
    async handleRowBtn(param) {
      if (param.action === 'toDel') {
        // 获取对应的id字段得值
        await this.deleteApi([param.row[this.deleteIdKey] || param.row[Object.keys(param.row).find(item => item.indexOf('_id') > -1)]])
        this.handleTableData()
        return
      }
      this.$emit(param.action, param.row)
    },
    // 分页
    changePage(page) {
      this.handleTableData({ pageNum: page })
    }
  }
}
</script>

<style scoped lang="less">
.search-box {
  display: inline-block;
}
.button-group {
  float: right;
}
.table-tools {
  margin-bottom: 20px;
}
.tools-search-item {
  margin-right: 20px;
  display: inline-block;
  label {
    margin-right: 10px;
  }
}
</style>
