<template>
  <div>
    <el-table
      ref="elTable"
      :data="data"
      v-bind="table"
      style="width:100%;"
      v-on="$listeners"
      @selection-change="tableSelection = $event"
    >
      <template v-for="(column, index) in columns">
        <el-table-column
          v-if="!column._hidden_ && column.type && !column._slot_"
          :key="index"
          v-bind="column"
        />
        <el-table-column
          v-else-if="!column._hidden_"
          :key="index"
          v-bind="column"
        >
          <template slot="header" slot-scope="scope">
            <span>{{ column.label }}</span>
            <span
              v-if="column._screen_"
              @click.stop="addConditionItemByCol(column, scope)"
            >
              <i
                v-if="column._screen_tip_ === false"
                :style="isHasScreenColumn(column) ? 'color:#3888e5;' : ''"
                class="el-icon-connection"
              />
              <el-tooltip
                v-else
                 
                :effect="column._screen_tip_effect_ || 'dark'"
                :content="column._screen_tip_ || '筛选'"
                :placement="column._screen_tip_placement_ || 'top'"
              >
                <i
                  :style="isHasScreenColumn(column) ? 'color:#3888e5;' : ''"
                  class="el-icon-connection"
                />
              </el-tooltip>
            </span>
          </template>
          <slot
            v-if="column._slot_"
            slot-scope="scope"
            :name="column._slot_"
            :scope="scope"
          />
          <template v-else-if="column._render_" slot-scope="scope">
            <ex-slot
              :column="column"
              :render="column._render_"
              :scope="scope"
            />
          </template>
          <template v-else slot-scope="scope">
            <span
              v-html="
                column._format_
                  ? column._format_(scope.row)
                  : getObjPrototype(scope.row, column.prop)
              "
            />
          </template>
        </el-table-column>
      </template>
    </el-table>
    <el-pagination
      v-if="page !== false && data && data.length > 0"
      :current-page="page.curr"
      :page-sizes="[10, 20, 50, 100]"
      :total="page.total"
      layout="total, sizes, prev, pager, next, jumper"
      style="text-align:right"
      class="fu-page"
      @current-change="$emit('page-curr-change', $event)"
      @size-change="$emit('page-size-change', $event)"
    />
    <!-- 筛选框 begin -->
    <div v-show="isScreenDialog" class="dialog-screen">
      <div v-drap.parent.limit class="header">
        <span>设置筛选</span>
        <i
          class="el-icon-close"
          :style="'line-height:inherit;cursor:pointer;'"
          @click="screenReset"
        />
      </div>
      <div class="body">
        <div class="condition">
          <div class="condition-left">且</div>
          <div class="condition-right">
            <div
              v-for="(conditionItem, conditionIndex) in conditions"
              :id="'conditionItem' + conditionIndex"
              :key="'conditionItem' + conditionIndex"
              class="condition-item"
            >
              <hr>
              <el-select
                v-model="conditionItem.prop"
                :class="{
                  'el-error': !conditionItem.prop || conditionItem.prop == ''
                }"
                :clearable="true"
                placeholder="请选择"
                @change="
                  screenPropsChange($event, conditionIndex, conditionItem)
                "
              >
                <el-option
                  v-for="screenColumnItem in screenColumns"
                  :key="
                    'conditionItem_screenCol' +
                      conditionIndex +
                      screenColumnItem.prop
                  "
                  :label="screenColumnItem.label"
                  :value="screenColumnItem.prop"
                />
              </el-select>
              <el-select
                v-model="conditionItem.keyId"
                :class="{
                  'el-error': !conditionItem.keyId || conditionItem.keyId == ''
                }"
                :clearable="true"
                placeholder="请选择"
                @change="
                  screenKeysChange($event, conditionIndex, conditionItem)
                "
              >
                <el-option
                  v-for="screenKeyItem in conditionItem._screenKeys_"
                  :key="
                    'conditionItem_screenKey' +
                      conditionIndex +
                      screenKeyItem.id
                  "
                  :label="screenKeyItem.label"
                  :value="screenKeyItem.id"
                />
              </el-select>
              <template v-for="(typeItem, typeIndex) in conditionItem.type">
                <hr
                  v-if="typeIndex > 0"
                  :key="
                    'conditionItem_hr' + conditionIndex + typeItem + typeIndex
                  "
                  :class="'divider-hr'"
                >
                <el-input
                  v-if="typeIndex == 0 && typeItem === 'text'"
                  :key="
                    'conditionItem_val' + conditionIndex + typeItem + typeIndex
                  "
                  v-model="conditionItem.value"
                  :class="{
                    'el-error':
                      conditionItem.value === undefined ||
                      conditionItem.value === ''
                  }"
                  placeholder="请输入内容"
                  maxlength="50"
                  @input="$forceUpdate()"
                />
                <el-input
                  v-else-if="typeIndex > 0 && typeItem === 'text'"
                  :key="
                    'conditionItem_val_end' +
                      conditionIndex +
                      typeItem +
                      typeIndex
                  "
                  v-model="conditionItem.value_end"
                  :class="{
                    'el-error':
                      conditionItem.value_end === undefined ||
                      conditionItem.value_end === ''
                  }"
                  placeholder="请输入内容"
                  maxlength="50"
                  @input="$forceUpdate()"
                />
                <el-input-number
                  v-else-if="typeIndex == 0 && typeItem === 'number'"
                  :key="
                    'conditionItem_val' + conditionIndex + typeItem + typeIndex
                  "
                  v-model="conditionItem.value"
                  :class="{
                    'el-error':
                      conditionItem.value === undefined ||
                      conditionItem.value === ''
                  }"
                  :min="0"
                  :max="999"
                  @change="$forceUpdate()"
                />
                <el-input-number
                  v-else-if="typeIndex > 0 && typeItem === 'number'"
                  :key="
                    'conditionItem_val_end' +
                      conditionIndex +
                      typeItem +
                      typeIndex
                  "
                  v-model="conditionItem.value_end"
                  :class="{
                    'el-error':
                      conditionItem.value_end === undefined ||
                      conditionItem.value_end === ''
                  }"
                  :min="0"
                  :max="999"
                  @change="$forceUpdate()"
                />
                <el-date-picker
                  v-else-if="
                    typeIndex == 0 &&
                      (typeItem === 'date' || typeItem === 'datetime')
                  "
                  :key="
                    'conditionItem_val' + conditionIndex + typeItem + typeIndex
                  "
                  v-model="conditionItem.value"
                  :class="{
                    'el-error':
                      conditionItem.value === undefined ||
                      conditionItem.value === ''
                  }"
                  :type="typeItem"
                  :value-format="'timestamp'"
                  placeholder="选择日期"
                  @blur="$forceUpdate()"
                  @input="$forceUpdate()"
                />
                <el-date-picker
                  v-else-if="
                    typeIndex > 0 &&
                      (typeItem === 'date' || typeItem === 'datetime')
                  "
                  :key="
                    'conditionItem_val_end' +
                      conditionIndex +
                      typeItem +
                      typeIndex
                  "
                  v-model="conditionItem.value_end"
                  :class="{
                    'el-error':
                      conditionItem.value_end === undefined ||
                      conditionItem.value_end === ''
                  }"
                  :type="typeItem"
                  :value-format="'timestamp'"
                  placeholder="选择日期"
                  @blur="$forceUpdate()"
                  @input="$forceUpdate()"
                />
                <el-select
                  v-else-if="typeIndex == 0 && typeItem === 'select'"
                  :key="
                    'conditionItem_val' + conditionIndex + typeItem + typeIndex
                  "
                  v-model="conditionItem.value"
                  :class="{
                    'el-select-val': true,
                    'el-error':
                      conditionItem.value === undefined ||
                      conditionItem.value === ''
                  }"
                  :clearable="true"
                  placeholder="请选择"
                  @change="$forceUpdate()"
                >
                  <el-option
                    v-for="(optionItem,
                            optionIndex) in conditionItem._select_options_"
                    :key="
                      'conditionItem_val_option' +
                        conditionIndex +
                        typeItem +
                        typeIndex +
                        optionIndex
                    "
                    :label="optionItem.label"
                    :value="optionItem.id"
                  />
                </el-select>
                <el-select
                  v-else-if="typeIndex > 0 && typeItem === 'select'"
                  :key="
                    'conditionItem_val_end' +
                      conditionIndex +
                      typeItem +
                      typeIndex
                  "
                  v-model="conditionItem.value_end"
                  :class="{
                    'el-select-val': true,
                    'el-error':
                      conditionItem.value_end === undefined ||
                      conditionItem.value_end === ''
                  }"
                  :clearable="true"
                  placeholder="请选择"
                  @change="$forceUpdate()"
                >
                  <el-option
                    v-for="(optionItem,
                            optionIndex) in conditionItem._select_options_end_"
                    :key="
                      'conditionItem_val_option_end' +
                        conditionIndex +
                        typeItem +
                        typeIndex +
                        optionIndex
                    "
                    :label="optionItem.label"
                    :value="optionItem.id"
                  />
                </el-select>
              </template>
              <el-button
                :style="'padding:10px;flex-shrink:0;'"
                size="mini"
                icon="el-icon-delete"
                @click="delConditionItemByIndex(conditionIndex, conditionItem)"
              />
            </div>
            <div class="condition-item">
              <hr>
              <el-button
                type="primary"
                icon="el-icon-circle-plus-outline"
                circle
                @click="addConditionItemByCol()"
              />
            </div>
          </div>
        </div>
      </div>
      <el-row :class="'footer'">
        <el-button @click.stop="screenReset">重置</el-button>
        <el-button type="primary" @click.stop="screenSubmit">筛选</el-button>
      </el-row>
    </div>
    <!-- 筛选框 end -->
  </div>
</template>

<script>
import Sortable from 'sortablejs'

export default {
  name: 'ExTable',
  components: {
    'ex-slot': {
      functional: true,
      props: {
        render: Function,
        scope: {
          type: Object,
          default: null
        },
        column: {
          type: Object,
          default: null
        }
      },
      render: (h, data) => {
        if (data.props.column) data.props.scope.column = data.props.column
        return data.props.render(h, data.props.scope)
      }
    }
  },
  directives: {
    // v-drap  可拖拽指令
    drap: {
      inserted: function(element, binding) {
        element.onmousedown = function(e) {
          const el = binding.modifiers.parent ? element.parentNode : element
          const bodyWidth = document.body.offsetWidth
          const bodyHeight = document.body.offsetHeight
          const elWidth = el.offsetWidth
          const elHeight = el.offsetHeight
          // 开始拖动，记录左上角坐标点
          const disX = e.clientX - el.offsetLeft
          const disY = e.clientY - el.offsetTop
          document.onmousemove = function(e) {
            // 拖动中，修改dom的左上角坐标点
            let l = e.clientX - disX
            let t = e.clientY - disY
            if (binding.modifiers.limit) {
              l = l < 0 ? 0 : l
              t = t < 0 ? 0 : t
              l = l > bodyWidth - elWidth ? bodyWidth - elWidth : l
              t = t > bodyHeight - elHeight ? bodyHeight - elHeight : t
            }
            el.style.left = l + 'px'
            el.style.top = t + 'px'
          }
          document.onmouseup = function() {
            // 结束拖动
            document.onmousemove = null
          }
        }
      }
    }
  },
  props: {
   
    // el-table 表格数据 对应data字段
    data: {
      type: Array,
      default: () => []
    },
    /**
     * el-table-column 表格列属性集合
     * 自定义属性：
     * @param {Boolean}       _noset_        : 是否不允许设置列
     * @param {Boolean}        _screen_      : 是否允许筛选
     * @param {Boolean}        _hidden_      : 是否隐藏列
     * @param {String/Boolean} _screen_tip_  : 筛选按钮提示信息，为false不提示
     * @param {String} _screen_tip_effect_   : 筛选按钮提示信息主题，dark/light
     * @param {String} _screen_tip_placement_: 筛选按钮提示信息位置，top/top-start/top-end/bottom/bottom-start/bottom-end/left/left-start/left-end/right/right-start/right-end
     * @param {Array}          _keys_        : 支持的筛选key
     * @param {Array}      _select_options_  : 若需支持包含select的key，value的备选数据，示例：{_select_options_: [{id:'', label:''},...]}
     * @param {Array}  _select_options_end_  : 若需支持包含select的key，value_end的备选数据，默认使用_select_options_，示例：{_select_options_: [{id:'', label:''},...]}
     * @param {Array}          _keys_        : 支持的筛选key
     * @param {String}         _slot_        : 使用具名插槽时的名称
     * @param {Function}       _format_      : 数据格式化函数，支持返回html
     * @param {Function}       _render_      : 自定义列，采用vue中的render函数，示例: { _render_:(h, scope) => { return h(...) } }
     */
    columns: {
      type: Array,
      default: () => []
    },
    /**
     * el-pagination
     * @param {Boolean} page 是否开启表格分页，若不传或传false则不开启
     * @param {Object} page {
     *   size: '10'
     *   total: '100'
     *   curr: '1'
     * }
     * Event:
     * page-curr-change  分页当前页改变
     * page-size-change  分页大小改变
     */
    page: {
      type: [Boolean, Object],
      default: false
    },
    /**
     * 筛选条件集合
     */
    conditions: {
      type: Array,
      default: () => []
    },
    /**
     * 是否允许拖拽行
     */
    isRowDrop: {
      type: Boolean,
      default: false
    },
    /**
     * 是否允许拖拽列
     */
    isColDrop: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 表格选中项
      tableSelection: [],
      // 是否显示筛选框
      isScreenDialog: false,
      // 筛选的key集合
      screenKeys: [
        { id: '1', key: '1', type: 'text', label: '包含' },
        { id: '2', key: '2', type: 'text', label: '不包含' },
        { id: '3', key: '3', type: 'text', label: '等于' },
        { id: '4', key: '4', type: 'text', label: '不等于' },
        { id: '5', key: '5', type: '', label: '为空' },
        { id: '6', key: '6', type: '', label: '不为空' },
        { id: '7', key: '7', type: 'date', label: '开始于' },
        { id: '8', key: '8', type: 'date', label: '结束于' },
        { id: '9', key: '9', type: 'date', label: '早于' },
        { id: '10', key: '10', type: 'date', label: '晚于' },
        { id: '11', key: '11', type: 'date', label: '不早于' },
        { id: '12', key: '12', type: 'date', label: '不晚于' },
        { id: '13', key: '13', type: 'datetime_datetime', label: '时间段' },
        { id: '14', key: '14', type: 'number', label: '前N天' },
        { id: '15', key: '15', type: 'number', label: '后N天' },
        { id: '16', key: '16', type: 'number', label: '前N月' },
        { id: '17', key: '17', type: 'number', label: '后N月' },
        { id: '18', key: '18', type: 'number', label: '大于' },
        { id: '19', key: '19', type: 'number', label: '大于等于' },
        { id: '20', key: '20', type: 'number', label: '小于' },
        { id: '21', key: '21', type: 'number', label: '小于等于' },
        { id: '22', key: '22', type: 'number_number', label: '介于' },
        { id: '23', key: '3', type: 'select', label: '单项选择' },
        { id: '24', key: '22', type: 'select_select', label: '区间选择' }
      ]
    }
  },
  computed: {
    // 允许筛选的列
    screenColumns() {
      return this.columns.filter(item => item._screen_ === true)
    },
    // 允许设置的列
    setColumns() {
      return this.columns.filter(item => !item._noset_)
    },
    // 筛选条件是否包含当前列
    isHasScreenColumn() {
      return function(col) {
        return this.conditions.some(item => item.prop === col.prop)
      }
    }
  },
  watch: {},
  mounted() {
    // 拖拽绑定
    this.rowDrop()
    this.columnDrop()
  },
  methods: {
    // 添加一行条件
    addConditionItemByCol(col, scope) {
      this.isScreenDialog = true
      // 当前项
      const index = col
        ? this.conditions.findIndex(item => item.prop === col.prop)
        : undefined
      if (col && index !== undefined && index > -1) {
        const dom = document.querySelector(
          `.dialog-screen .body #conditionItem${index}`
        )
        this.$nextTick(() => {
          this.screenBodyScrollTop(dom.offsetTop - dom.scrollHeight)
        })
      } else {
        this.conditions.push(
          Object.assign(
            {},
            col || {},
            col
              ? {
                _select_options_end_:
                    col._select_options_ && !col._select_options_end_
                      ? col._select_options_
                      : col._select_options_end_,
                _screenKeys_: col._keys_
                  ? col._keys_.map(item =>
                    this.screenKeys.find(fitem => item == fitem.id)
                  )
                  : [].concat(this.screenKeys)
              }
              : {}
          )
        )
        this.$nextTick(() => {
          this.screenBodyScrollTop(
            document.querySelector('.dialog-screen .body').scrollHeight
          )
        })
      }
    },
    // 删除一行条件
    delConditionItemByIndex(index, item) {
      this.conditions.splice(index, 1)
    },
    // 筛选重置
    screenReset() {
      this.conditions.splice(0)
      this.$emit('screen-reset', this.conditions)
      this.isScreenDialog = false
    },
    // 筛选提交
    screenSubmit() {
      if (this.validotarScreen()) {
        this.$emit('screen-submit', this.conditions)
        this.isScreenDialog = false
      } else {
        this.$message.error('筛选项及筛选值不可为空')
      }
    },
    // 滚动筛选框body
    screenBodyScrollTop(t) {
      document.querySelector('.dialog-screen .body').scrollTop = t
    },
    // 校验筛选框筛选条件
    validotarScreen() {
      return this.conditions.every(
        item =>
          item.prop &&
          item.prop != '' &&
          item.keyId &&
          item.keyId != '' &&
          item.key &&
          item.key != '' &&
          (item.type.length === 0 ||
            (item.type.length === 1 &&
              item.value !== undefined &&
              item.value !== '') ||
            (item.type.length > 1 &&
              item.value !== undefined &&
              item.value !== '' &&
              item.value_end !== undefined &&
              item.value_end !== ''))
      )
    },
    // 筛选条件prop改变
    screenPropsChange(val, scindex, scitem) {
      if (val === undefined || val === '') throw new Error('数据异常')
      // 选中列的原始数据
      const columnsItem = this.columns.find(item => item.prop === val)
      // 重置当前筛选条件数据
      this.$set(
        this.conditions,
        scindex,
        Object.assign(
          {
            keyId: '',
            key: '',
            value: '',
            value_end: ''
          },
          columnsItem,
          {
            _select_options_end_:
              columnsItem._select_options_ && !columnsItem._select_options_end_
                ? columnsItem._select_options_
                : columnsItem._select_options_end_,
            _screenKeys_: columnsItem._keys_
              ? columnsItem._keys_.map(item =>
                this.screenKeys.find(fitem => item == fitem.id)
              )
              : [].concat(this.screenKeys)
          }
        )
      )
    },
    // 筛选条件key改变
    screenKeysChange(val, scindex, scitem) {
      if (val === undefined || val === '') throw new Error('数据异常')
      // 选中key支持的类型
      const typeText = this.screenKeys.find(item => item.id === val).type || ''
      const key = this.screenKeys.find(item => item.id === val).key || ''
      // 重置当前筛选条件数据
      this.$set(
        this.conditions,
        scindex,
        Object.assign({}, scitem, {
          key: key,
          value: '',
          value_end: '',
          typeText: typeText,
          type: typeText
            .split('_')
            .filter(item => item !== undefined && item !== '')
        })
      )
    },
    // 行拖拽
    rowDrop() {
      const tbody = document.querySelector(
        '.el-table__body-wrapper > table > tbody'
      )
      Sortable.create(tbody, {
        disabled: !this.isRowDrop,
        ghostClass: 'sortable-ghost',
        animation: 180,
        delay: 0,
        onEndevt: evt => {
          const currItem = this.data.splice(evt.oldIndex, 1)[0]
          this.data.splice(evt.newIndex, 0, currItem)
        }
      })
    },
    // 列拖拽
    columnDrop() {
      const wrapperTr = document.querySelector('.el-table__header-wrapper tr')
      Sortable.create(wrapperTr, {
        disabled: !this.isColDrop,
        ghostClass: 'sortable-ghost',
        animation: 180,
        delay: 0,
        onEnd: evt => {
          const currItem = this.columns.splice(evt.oldIndex, 1)[0]
          this.columns.splice(evt.newIndex, 0, currItem)
        }
      })
    },
    // 获取对象的属性
    getObjPrototype(o, a) {
      const fn = Function
      return new fn('obj', `return obj.${a}`)(o)
    },
    /** 表格方法 传递给el-table，后续有需要可继续增加 **/
    // 对 Table 进行重新布局。当 Table 或其祖先元素由隐藏切换为显示时，可能需要调用此方法
    doLayout(...arg) {
      this.$refs.elTable.doLayout(...arg)
    },
    // 用于多选表格，清空用户的选择
    clearSelection(...arg) {
      this.$refs.elTable.clearSelection(...arg)
    },
    // 用于多选表格，切换某一行的选中状态
    toggleRowSelection(...arg) {
      this.$refs.elTable.toggleRowSelection(...arg)
    },
    // 用于多选表格，切换所有行的选中状态
    toggleAllSelection(...arg) {
      this.$refs.elTable.toggleAllSelection(...arg)
    },
    // 用于单选表格，设定某一行为选中行
    setCurrentRow(...arg) {
      this.$refs.elTable.setCurrentRow(...arg)
    },
    // 用于可展开表格与树形表格，切换某一行的展开状态，如果使用了第二个参数，则是设置这一行展开与否（expanded 为 true 则展开）
    toggleRowExpansion(...arg) {
      this.$refs.elTable.toggleRowExpansion(...arg)
    }
  }
}
</script>

<style lang="css">
.el-switch__core {
  flex-shrink: 0;
}
.el-switch,
.el-switch__label {
  height: auto;
}
.dialog-screen .el-error input {
  border-color: red;
}
.dialog-screen .el-input-number,
.dialog-screen .el-input,
.dialog-screen .el-date-editor,
.dialog-screen .el-select-val {
  width: 100%;
}
.dialog-screen .el-input-number__decrease,
.dialog-screen .el-input-number__increase {
  top: 2px;
  bottom: 2px;
}
.ex-table-setcol-dropdown {
  max-width: 180px;
  max-height: 280px;
  overflow-y: auto;
}
</style>

<style lang="scss" scoped>
.table-header {
  display: flex;
  display: -webkit-flex;
  background-color: #f5f5f5;
  padding: 0 10px;
}
.table-header > * {
  margin-top: 10px;
  margin-bottom: 10px;
}
.table-header :nth-child(n + 2) {
  margin-left: 10px;
}
.dialog-screen {
  position: fixed;
  z-index: 2000;
  top: 200px;
  left: 20%;
  width: 60%;
  min-width: 600px;
  max-height: 80vh;
  background-color: #fff;
  box-shadow: 1px 1px 50px rgba(0, 0, 0, 0.3);
  .header {
    cursor: move;
    padding: 0 10px;
    height: 44px;
    line-height: 44px;
    display: flex;
    display: -webkit-flex;
    justify-content: space-between;
    border-bottom: 1px solid #eee;
    font-size: 14px;
    color: #333;
    overflow: hidden;
    background-color: #f8f8f8;
    border-radius: 2px 2px 0 0;
  }
  .footer {
    height: 64px;
    line-height: 64px;
    float: right;
    padding: 0 10px;
  }
  .body {
    max-height: calc(80vh - 45px - 64px);
    overflow: auto;
    background-color: #fff;
    .condition {
      display: flex;
      display: -webkit-flex;
      margin: 10px 20px 10px 10px;
      .condition-left {
        margin: 25px 0;
        width: 30px;
        border-right: 1px #303133 solid;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .condition-right {
        width: calc(100% - 30px);
      }
      .condition-item {
        padding: 5px 0 5px 20px;
        margin: 5px 0;
        height: 38px;
        background-color: #eff4fd;
        position: relative;
        display: flex;
        display: -webkit-flex;
        align-items: center;
        hr {
          position: absolute;
          left: 0;
          top: 23px;
          width: 20px;
          margin: 0;
        }
        hr ~ * {
          margin: 0 5px;
        }
        :nth-child(2).el-select {
          flex-shrink: 0;
          width: 20%;
        }
        :nth-child(3).el-select {
          flex-shrink: 0;
          width: 20%;
        }
        .divider-hr {
          position: relative !important;
          flex-shrink: 0 !important;
          top: 0 !important;
          margin: 0 !important;
          width: 10px !important;
          color: rgb(51, 51, 51) !important;
        }
      }
      :last-child.condition-item hr {
        top: 27px;
      }
      :first-child.condition-item hr {
        top: 20px;
      }
    }
  }
}
</style>
