<template>
  <div class="tables"
       ref="tables">
    <Row class="search-con search-con-top"
         v-if="searchable && searchPlace === 'top'"
         type="flex"
         :justify="justify">
      <i-col span="24">
        <div>
          <Select v-model="searchKey"
                  class="search-col">
            <Option v-for="item in columns"
                    v-show="item.key !== 'handle'"
                    :value="item.key"
                    :key="`search-col-${item.key}`">{{ item.title }}</Option>
          </Select>
          <Input @on-change="handleClear"
                 clearable
                 placeholder="输入关键字搜索"
                 class="search-col"
                 v-model="searchValue" />
          <div class="header-con-btn">
            <Button @click="handleSearch"
                    class="search-btn"
                    type="primary">搜索</Button>&nbsp;&nbsp;&nbsp;
            <Button class="resertBtn"
                    title="重置">重置</Button>
          </div>
        </div>
      </i-col>
    </Row>
    <div class="marginBot"
         v-if="searchable && searchPlace === 'top'"></div>
    <Row class="table-btn search-con-top"
         v-show="showAddBtn || showExportBtn">
      <i-col span="2">
        <Button type="primary"
                v-show="showExportBtn"
                @click="exportData">
          <Icon type="ios-download-outline"></Icon>导出为Csv文件
        </Button>
        <Button type="primary"
                v-show="showAddBtn"
                @click="addData"><span class="iconfont icon-chuangjian"></span>{{ btnTxt }}</Button>
      </i-col>
    </Row>
    <div class="setContentBox setTableBox">
      <Table ref="tablesMain"
             row-key="id"
             :data="insideTableData"
             :columns="insideColumns"
             :stripe="stripe"
             :border="border"
             :show-header="showHeader"
             :width="width"
             :height="height"
             :loading="loading"
             :disabled-hover="disabledHover"
             :highlight-row="highlightRow"
             :row-class-name="rowClassName"
             :size="size"
             :no-data-text="noDataText"
             :no-filtered-data-text="noFilteredDataText"
             @on-current-change="onCurrentChange"
             @on-select="onSelect"
             @on-select-cancel="onSelectCancel"
             @on-select-all="onSelectAll"
             @on-selection-change="onSelectionChange"
             @on-sort-change="onSortChange"
             @on-filter-change="onFilterChange"
             @on-row-click="onRowClick"
             @on-row-dblclick="onRowDblclick"
             @on-expand="onExpand">
        <slot name="header"
              slot="header"></slot>
        <slot name="footer"
              slot="footer"></slot>
        <slot name="loading"
              slot="loading"></slot>
      </Table>
    </div>
    <div v-if="searchable && searchPlace === 'bottom'"
         class="search-con search-con-top">
      <Select v-model="searchKey"
              class="search-col">
        <Option v-for="item in columns"
                v-show="item.key !== 'handle'"
                :value="item.key"
                :key="`search-col-${item.key}`">{{ item.title }}</Option>
      </Select>
      <Input placeholder="输入关键字搜索"
             class="search-input"
             v-model="searchValue" />
      <Button class="search-btn"
              type="primary">
        <Icon type="search" />&nbsp;&nbsp;搜索</Button>
    </div>
    <a id="hrefToExportTable"
       style="display: none;width: 0px;height: 0px;"></a>
    <table-drawer v-model="showDrawer"
                  :curColumn="currentColumn"
                  :title="title"
                  v-bind="$attrs"
                  v-on="$listeners"
                  :dragWidth="dragWidth"
                  :radioArr="radioArr"
                  :checkBoxArr="checkBoxArr"
                  :selectArr="selectArr"></table-drawer>
    <table-modal v-model="showModal"
                 :curColumn="currentColumn"
                 :title="title"
                 v-bind="$attrs"
                 v-on="$listeners"
                 :radioArr="radioArr"
                 :checkBoxArr="checkBoxArr"
                 :selectArr="selectArr"></table-modal>
  </div>
</template>

<script>
import TablesEdit from './edit.vue'
// eslint-disable-next-line no-unused-vars
import TablesAdd from './add.vue'
import handleBtns from './handle-btns'
import TableDrawer from './tableDrawer.vue'
import TableModal from './tableModal.vue'
import './index.less'
// eslint-disable-next-line no-unused-vars
import { debuglog } from 'util'
export default {
  name: 'hTable',
  components: {
    TableDrawer,
    TableModal
  },
  props: {
    value: {
      type: Array,
      default () {
        return []
      }
    },
    columns: {
      type: Array,
      default () {
        return []
      }
    },
    size: String,
    width: {
      type: [Number, String]
    },
    height: {
      type: [Number, String],
      default: 520
    },
    stripe: {
      type: Boolean,
      default: false
    },
    border: {
      type: Boolean,
      default: false
    },
    showHeader: {
      type: Boolean,
      default: true
    },
    highlightRow: {
      type: Boolean,
      default: false
    },
    rowClassName: {
      type: Function,
      default () {
        return ''
      }
    },
    context: {
      type: Object
    },
    noDataText: {
      type: String
    },
    noFilteredDataText: {
      type: String
    },
    disabledHover: {
      type: Boolean
    },
    loading: {
      type: Boolean,
      default: false
    },
    /**
     * @description 全局设置是否可编辑
     */
    editable: {
      type: Boolean,
      default: false
    },
    /**
     * @description 是否可搜索
     */
    searchable: {
      type: Boolean,
      default: false
    },
    /**
     * @description 搜索控件所在位置，'top' / 'bottom'
     */
    searchPlace: {
      type: String,
      default: 'top'
    },
    showExportBtn: {
      type: Boolean,
      default: false
    },
    showAddBtn: {
      type: Boolean,
      default: false
    },
    radioArr: {
      type: Array,
      // eslint-disable-next-line vue/require-valid-default-prop
      default: () => []
    },
    checkBoxArr: {
      type: Array,
      // eslint-disable-next-line vue/require-valid-default-prop
      default: () => []
    },
    selectArr: {
      type: Array,
      // eslint-disable-next-line vue/require-valid-default-prop
      default: () => []
    },
    currentColumn: {
      type: Object,
      // eslint-disable-next-line vue/require-valid-default-prop
      default: () => {}
    },
    dragDrawerWidth: {
      type: String,
      default: '30'
    },
    btnTxt: {
      type: String,
      default: '新建'
    },
    justify: {
      type: String,
      default: 'start'
    }
  },
  /**
   * Events
   * @on-start-edit 返回值 {Object} ：同iview中render函数中的params对象 { row, index, column }
   * @on-cancel-edit 返回值 {Object} 同上
   * @on-save-edit 返回值 {Object} ：除上面三个参数外，还有一个value: 修改后的数据
   */
  data () {
    return {
      insideColumns: [],
      insideTableData: [],
      edittingCellId: '',
      edittingText: '',
      searchValue: '',
      searchKey: '',
      modal: false,
      checkboxGroup: [],
      showDrawer: false,
      showModal: false,
      dragWidth: '',
      title: ''
    }
  },
  methods: {
    suportEdit (item, index) {
      item.render = (h, params) => {
        return h(TablesEdit, {
          props: {
            params: params,
            value: this.insideTableData[params.index][params.column.key],
            edittingCellId: this.edittingCellId,
            editable: this.editable
          },
          on: {
            input: val => {
              this.edittingText = val
            },
            'on-start-edit': params => {
              this.edittingCellId = `editting-${params.index}-${params.column.key}`
              this.$emit('on-start-edit', params)
            },
            'on-cancel-edit': params => {
              this.edittingCellId = ''
              this.$emit('on-cancel-edit', params)
            },
            'on-save-edit': params => {
              // eslint-disable-next-line standard/computed-property-even-spacing
              this.value[params.row.initRowIndex][
                params.column.key
              ] = this.edittingText
              this.$emit('input', this.value)
              this.$emit(
                'on-save-edit',
                Object.assign(params, { value: this.edittingText })
              )
              this.edittingCellId = ''
            }
          }
        })
      }

      return item
    },
    surportHandle (item) {
      // debugger
      const options = item.options || []
      // eslint-disable-next-line prefer-const
      let insideBtns = []
      options.forEach(item => {
        if (handleBtns[item]) insideBtns.push(handleBtns[item])
      })
      // eslint-disable-next-line prefer-const
      let btns = item.button ? [].concat(insideBtns, item.button) : insideBtns
      item.render = (h, params) => {
        params.tableData = this.value
        return h(
          'div',
          btns.map(item => item(h, params, this))
        )
      }
      return item
    },
    handleColumns (columns) {
      this.insideColumns = columns.map((item, index) => {
        let res = item
        if (res.editable) res = this.suportEdit(res, index)
        if (res.key === 'handle') res = this.surportHandle(res)
        return res
      })
    },
    setDefaultSearchKey () {
      this.searchKey =
        this.columns[0].key !== 'handle'
          ? this.columns[0].key
          : this.columns.length > 1
            ? this.columns[1].key
            : ''
    },
    handleClear (e) {
      if (e.target.value === '') this.insideTableData = this.value
    },
    handleSearch () {
      this.insideTableData = this.value.filter(item => {
        if (typeof item[this.searchKey] === 'number') {
          item[this.searchKey] = item[this.searchKey].toString()
        }
        return item[this.searchKey].indexOf(this.searchValue) > -1
      })
      //   this.insideTableData = this.value.filter(
      //     item => item[this.searchKey].indexOf(this.searchValue) > -1
      //   );
    },
    handleTableData () {
      this.insideTableData = this.value.map((item, index) => {
        const res = item
        res.initRowIndex = index
        for (var tag in res) {
          // eslint-disable-next-line eqeqeq
          if (tag == 'gatherTime') {
            res[tag] = this.$moment(res[tag]).format('YYYY-MM-DD')
          }
          // eslint-disable-next-line eqeqeq
          if (tag == 'gatherRangeTime') {
            const startTime = this.$moment(res[tag].split(',')[0]).format(
              'YYYY-MM-DD'
            )
            // eslint-disable-next-line prefer-const
            let endTime = this.$moment(res[tag].split(',')[1]).format(
              'YYYY-MM-DD'
            )
            res[tag] = startTime + ',' + endTime
          }
        }
        return res
      })
    },
    exportCsv (params) {
      this.$refs.tablesMain.exportCsv(params)
    },
    clearCurrentRow () {
      this.$refs.talbesMain.clearCurrentRow()
    },
    onCurrentChange (currentRow, oldCurrentRow) {
      this.$emit('on-current-change', currentRow, oldCurrentRow)
    },
    onSelect (selection, row) {
      this.$emit('on-select', selection, row)
    },
    onSelectCancel (selection, row) {
      this.$emit('on-select-cancel', selection, row)
    },
    onSelectAll (selection) {
      this.$emit('on-select-all', selection)
    },
    onSelectionChange (selection) {
      this.$emit('on-selection-change', selection)
    },
    onSortChange (column, key, order) {
      this.$emit('on-sort-change', column, key, order)
    },
    onFilterChange (row) {
      this.$emit('on-filter-change', row)
    },
    onRowClick (row, index) {
      this.$emit('on-row-click', row, index)
    },
    onRowDblclick (row, index) {
      this.$emit('on-row-dblclick', row, index)
    },
    onExpand (row, status) {
      this.$emit('on-expand', row, status)
    },
    exportData () {
      this.$refs.tables.exportCsv({
        filename: `table-${new Date().valueOf()}.csv`
      })
    },
    addData () {
      this.action = 'add'
      this.modal = true
      // eslint-disable-next-line prefer-const
      // eslint-disable-next-line no-unused-vars
      // let addRow = {} // 保存新建row数据
      // eslint-disable-next-line prefer-const
      let newColomusArr = this.columns.filter(
        // eslint-disable-next-line eqeqeq
        item => item.key && item.key != 'handle' && item.isShow != false
      )
      this.title = '新增列表'
      if (newColomusArr.length <= 5) {
        this.showModal = true
        // this.modalForm(addRow,newColomusArr)
      } else if (newColomusArr.length > 5) {
        this.dragWidth = this.dragDrawerWidth
        this.showDrawer = true
      }
    },
    editCurCol () {
      const newColomusArr = this.columns.filter(
        // eslint-disable-next-line eqeqeq
        item => item.key && item.key != 'handle' && item.isShow != false
      )
      this.title = '编辑列表'
      if (newColomusArr.length <= 5) {
        this.showModal = true
        // this.editModalForm(newColomusArr,this.currentColumn)
      } else if (newColomusArr.length > 5) {
        this.dragWidth = this.dragDrawerWidth
        this.showDrawer = true
      } else if (newColomusArr.length > 12) {
        this.dragWidth = this.dragDrawerWidth
        this.showDrawer = true
      }
    }
  },
  watch: {
    columns (columns) {
      this.handleColumns(columns)
      this.setDefaultSearchKey()
    },
    value (val) {
      this.handleTableData()
      if (this.searchable) this.handleSearch()
    },
    currentColumn (newCurCol) {
      if (newCurCol) {
        this.editCurCol()
      }
    }
  },
  mounted () {
    this.handleColumns(this.columns)
    this.setDefaultSearchKey()
    this.handleTableData()
  },
  beforeCreate () {
    // this.ruleProp={
    //     age: [
    //             { required:true, message: '输入不能为空', trigger: 'blur' }
    //         ]
    //   }
  }
}
</script>
<style lang="less">
.tablesForm {
  .ivu-form-item-content {
    display: inline-block;
    // width: 260px;
  }
}
</style>
