<template>
  <div>
    <!-- 通过v-bind="$attrs" v-on="$listeners"，把父组件传的属性全部绑定到子组件上，保证了api和el-table一致 -->
    <el-table
      ref="table"
      style="width: 100%"
      v-bind="$attrs"
      :max-height="tableHight"
      :height="tableHight"
      :header-cell-style="headerStyle"
      :cell-style="cellStyle"
      :data="elTableData"
      size="small"
      row-key="id"
      highlight-current-row
      v-on="$listeners"
      @header-dragend="headerDragend"
    >
      <el-table-column v-if="selectionTF" type="selection" width="55" />
      <el-table-column v-if="indexTF" type="index" width="55" />
      <el-table-column
        v-for="(item,index) in columns"
        :key="index+''+item.remarks+item.id"
        :show-overflow-tooltip="item.tfShowOverflowTooltip"
        :prop="item.propName"
        :label="item.labelName"
        :sortable="item.tfSortable"
        :width="item.width"
        align="center"
      >
        <template slot-scope="scope">
          <!--   文本内容     -->
          <span v-if="!item.tfElTag">
            <i v-if="item.tfIcon" :class="item.iIcon" />
            <span
              slot="title"
              :style="item.vueStyle"
              v-html="getDateString(item.fieldType,scope.row,item.propName,item.defaultContent)"
            />
          </span>
          <!-- 日期内容 -->
          <span v-if="item.tfElTag">
            <el-tag :style="item.tagStyle" :type="item.tagType">
              <i
                v-if="item.tfIcon"
                :class="item.iIcon"
              >{{ getDateString(item.fieldType, scope.row, item.propName, item.defaultContent) }}</i>
            </el-tag>
          </span>
        </template>
      </el-table-column>
      <!--  表头是数据或操作内容 -->
      <el-table-column v-if="buttonTF" label="操作" align="center" :width="cZWidth" fixed="right">
        <template slot-scope="{ row, $index}">
          <slot name="cz" :row="row" :index="$index" />
        </template>
      </el-table-column>
    </el-table>
    <div style="height: 36px">
      <el-button v-if="layoutTF" type="success" icon="el-icon-upload" @click="elTableConfigUpadte()">保存布局</el-button>
      <pagination style="float: right" />
    </div>
  </div>

</template>

<script>
import { dateFormattedDate, getObjectBySting } from '@/utils/commonUtils'
import pagination from '@crud/Pagination'
import Sortable from 'sortablejs'
import { elTableConfigAllMap, updateElTableConfigS } from '@/api/elTableConfig'

export default {
  name: 'ElTableOne',
  components: { pagination },
  props: {
    // 表格的数据
    elTableData: {
      type: Array,
      default: () => []
    },
    // columns: {
    //   type: Array,
    //   default: () => []
    // },
    formattes: {
      type: String,
      default: () => 'YYYY-MM-DD'
    },
    selectionTF: {
      type: Boolean,
      default: () => true
    }, indexTF: {
      type: Boolean,
      default: () => true
    }, buttonTF: {
      type: Boolean,
      default: () => true
    },
    tableHight: {
      type: Number,
      default: () => 500
    }, cZWidth: {
      type: Number,
      default: () => 120
    },
    headerStyle: {
      type: Object,
      default: function() {
        return { background: '#061a3a', color: '#bfd7fe', borderColor: '#032044' }
      }
    },
    cellStyle: {
      type: Object,
      default: function() {
        return { background: '#071026', color: '#ffffff', borderColor: '#032044' }
      }
    },
    routerPath: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      // 展示的配置信息
      columns: undefined,
      // 布局的开关
      layoutTF: false,
      // 排序前面有的个数
      beforeNumber: 0,
      elTableConfigInput: {
        updateElTableConfigDtoS: []
      }
    }
  },
  watch: {
    tableHight: {
      handler(newName, oldName) {
        this.tableHight = newName
        this.$nextTick(function() {
          // 调用需要执行的方法
          this.$refs.table.doLayout()
        })
      },
      deep: true
    },
    elTableData: {
      handler(newName, oldName) {
        this.elTableData = newName
        // this.$nextTick(function(){
        // 调用需要执行的方法
        this.$refs.table.doLayout()
        // })
      },
      deep: true
    }
  },
  created() {
    this.beforeNumberValue()
    this.columnDrop()
  },
  mounted() {
    setTimeout(() => {
      // 方法区
      this.$refs.table.doLayout()
    }, 500)
    this.$nextTick(function() {
      // 调用需要执行的方法
      this.$refs.table.doLayout()
    })
  },
  methods: {
    beforeNumberValue() {
      const dataList = this.$store.state.elTable.elTableDataMap.size === 0 ? undefined : this.$store.state.elTable.elTableDataMap.get(this.routerPath)
      if (dataList === undefined) {
        this.initData()
      } else {
        this.columns = dataList
      }
      if (this.selectionTF) {
        this.beforeNumber += 1
      }
      if (this.indexTF) {
        this.beforeNumber += 1
      }
    },
    // 获取带.的值
    getDataValue(data, string) {
      return getObjectBySting(data, string)
    },
    // 日期格式化
    getDateFormattedDate(date) {
      return dateFormattedDate(date, this.formattes)
    },
    // 获取数据内容
    getDateString(type, data, string, defaultContent) {
      if (data == null) {
        return defaultContent
      }
      let data_ = null
      if (type === 'stringType') {
        data_ = this.getDataValue(data, string)
        return data_ != null ? data_ : defaultContent
      } else if (type === 'dateType') {
        data_ = this.getDataValue(data, string)
        return data_ != null ? this.getDateFormattedDate(data_) : defaultContent
      }
    },
    // 列宽改变
    headerDragend(newWidth, oldWidth, column) {
      // 显示保存布局
      this.layoutTF = true
      this.columns.forEach((e) => {
        if (e.propName === column.property) {
          e.width = Math.round(newWidth)
        }
      })
      this.$nextTick(() => {
        this.columnDrop()
      })
      this.$refs.table.doLayout()
    },
    columnDrop() {
      const tHeader = document.querySelector('.el-table__header-wrapper tr')
      Sortable.create(tHeader, {
        disabled: false, // 是否开启拖拽
        animation: 180,
        /** 延迟 */
        delay: 1,
        onEnd: (evt) => {
          // 显示保存布局
          this.layoutTF = true
          // 前面有几个要忽略
          const beforeNumber_ = this.beforeNumber
          // 临时数组
          const listData_ = this.columns
          // 第几个
          const oldItem = listData_[evt.oldIndex - beforeNumber_]
          listData_.splice(evt.oldIndex - beforeNumber_, 1)
          listData_.splice(evt.newIndex - beforeNumber_, 0, oldItem)
          this.columns = listData_
          setTimeout(() => {
            // 方法区
            this.$refs.table.doLayout()
          }, 200)
        }
      })
    },
    initData() {
      // 加载数据
      elTableConfigAllMap({}).then(res => {
        const map = new Map(Object.entries(res))
        for (const key of map.keys()) {
          this.$store.dispatch('elTable/elTableDataMapAdd', { key: key, value: map.get(key) })
        }
        this.columns = this.$store.state.elTable.elTableDataMap.get(this.routerPath)
      })
    },
    // 保存布局
    elTableConfigUpadte() {
      this.elTableConfigInput.updateElTableConfigDtoS = this.columns
      updateElTableConfigS(this.elTableConfigInput).then(res => {
        // 显示保存布局
        this.layoutTF = false
        this.$message.success('保存成功')
        this.$store.dispatch('elTable/elTableDataMapAdd', { key: this.routerPath, value: this.columns })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-table {
  background-color: #071026 !important;
  color: #fff !important;
}

//鼠标滑过行的颜色
::v-deep .el-table__body tr:hover > td {
  background-color: #052650 !important;
}

//点击后的颜色设置
::v-deep .el-table__body tr.current-row > td {
  background-color: #052650 !important;
}
</style>
