<script>
import {
  humpToLine,
  setOrder,
  bizCodeMapping,
  getCodeOptions
} from '@/util/util'
import _ from 'lodash'

export default {
  name: 'TableScript',
  data() {
    return {
      query: {
        page: 1,
        size: this.$defaultPageSize()
      },
      rowKey: 'id',
      selectedRowKeys: [],
      selectedRows: [],
      total: 0,
      loading: false,
      dataSource: [],
      isFirstLoad: true,

      toolbar: [],
      // reset时保留的query属性
      retainFields: [],

      options: {},
      codeMapping: {},
      codes: [[], []],
      columns: [],
      useYScroll: false, // 是否只使用纵向滚动
      useScroll: false, // 是否使用表格内滚动, 想要生效需要给列配置宽度
      heightFix: 330, // 默认高度修正
      widthFix: 233, // 默认宽度修正
      /** 是否使用分页  */
      pagination: true,
      /** 是否使用列选择 */
      useSelection: true,
      // 标题
      title: '列表',
      keep: true, // 保持状态
      useSearch: true, // 显示搜索
      customClass: '',
      useTitle: true,
      expandedRowKeys: [],
      bordered: false,
      childrenColumnName: 'children',
      searchHeight: 0, // 搜索框高度
      defaultExpandAllRows: false
    }
  },
  computed: {
    /* 滚动设置 */
    scroll() {
      if (this.useYScroll) {
        return {
          y: this.$store.getters.size[1] - this.heightFix - this.searchHeight
        }
      }
      const width = this.columns
        .map((c) => c.width || 0)
        .reduce((w1, w2) => w1 + w2)
      return this.useScroll
        ? {
            x: width - this.widthFix,
            y: this.$store.getters.size[1] - this.heightFix - this.searchHeight
          }
        : undefined
    },
    /* 最终过滤后的列 */
    finalColumns() {
      return this.columns.filter((c) => !c.hidden)
    },

    filters() {
      return this.columns.filter((c) => !!c.filter)
    },

    defaultPageSize: function () {
      return this.$defaultPageSize()
    },

    paginationConfig: function () {
      if (this.pagination) {
        return {
          onChange: this.pageChange,
          current: this.query.page,
          defaultPageSize: this.$defaultPageSize(),
          pageSizeOptions: this.$pageSizeOptions,
          onShowSizeChange: this.sizeChange,
          total: this.total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: this.$showTotal
        }
      }
      return false
    }
  },

  methods: {
    reset() {
      this.query = _.pick(this.query, ['page', 'size', ...this.retainFields])
      this.loadData()
    },

    handleChange({ fileList }) {
      this.isUpdateSuccess(fileList)
      this.fileList = fileList
    },

    // eslint-disable-next-line no-unused-vars
    changeClassName(row, index) {
      return ''
    },

    loadData(size) {
      this.loading = true
      this.selectedRowKeys = []
      if (size && !isNaN(size)) {
        this.query.size = size
      }
      this.queryData(this.query).then((response) => {
        if (response && response.code == SYS_CONST.REQUEST.SUCCEED) {
          if (this.pagination) {
            let respData = response.data
            this.dataSource = respData.list
            this.total = respData.total
          } else {
            this.dataSource = response.data
          }
        }
        this.loading = false
        if (this.loadSuccess) {
          this.loadSuccess()
        }
      })
    },
    search() {
      this.query.page = 1
      this.loadData()
    },
    /* 新增数据 */
    addNew() {
      this.editRow()
    },
    /* 编辑行 */
    // eslint-disable-next-line no-unused-vars
    editRow(row) {},
    async deleteOne() {},
    deleteRow(id) {
      this.deleteOne(id).then((response) => {
        if (response && response.code == SYS_CONST.REQUEST.SUCCEED) {
          this.loadData()
        }
      })
    },
    onDelete(row) {
      let _this = this
      this.$confirm({
        title: '提示',
        content: '确定删除这条记录吗？',
        onOk() {
          _this.deleteRow(row.id)
        },
        onCancel() {}
      })
    },

    onDeleteBatch() {
      if (this.selectedRowKeys.length == 0) {
        return
      }
      let _this = this
      this.$confirm({
        title: '提示',
        content: '确定删除选中的记录吗？',
        onOk() {
          _this.deleteBatch()
        },
        onCancel() {}
      })
    },
    updateSelect(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },

    pageChange(page) {
      this.query.page = page
      this.loadData()
    },
    sizeChange(current, size) {
      this.query.page = 1
      this.query.size = size
      this.loadData()
    },
    sortChange(pagination, filters, sorter) {
      this.query.sort = humpToLine(sorter.field)
      this.query.order = setOrder(sorter.order)
      this.loadData()
    },
    getTypes() {
      console.info('getType')
    },

    beforeFirstLoad() {},
    queryData() {
      return new Promise((resolve) => resolve({ data: {} }))
    },
    init() {
      this.beforeFirstLoad && this.beforeFirstLoad()
      if (this.isFirstLoad == true) {
        this.loadData(this.defaultPageSize)
        this.isFirstLoad = false
      } else {
        let isModify = this.$route.query.isModify
        if (isModify == true) {
          this.loadData()
        } else if (isModify != undefined) {
          this.query.page = 1
          this.loadData()
        }
      }
    },
    onCollapse(gap) {
      console.info('gap', gap)
      this.searchHeight = gap
    }
  },

  mounted() {
    // 加载编码
    this.codes[0].length &&
      getCodeOptions(this.codes[0]).then(([codeMapping, options]) => {
        this.options = { ...this.options, ...options }
        this.codeMapping = codeMapping
      })

    this.codes[1].length &&
      this.codes[1].forEach((c) => {
        bizCodeMapping[c] &&
          bizCodeMapping[c]().then((ops) => {
            this.options = { ...this.options, [c]: ops }
            const bizCodeMap = {}
            ops.forEach((op) => (bizCodeMap[op.value] = op.label))
            this.codeMapping = { ...this.codeMapping, [c]: bizCodeMap }
          })
      })
    if (!this.$route.meta.keepAlive) {
      this.init()
    }
  },

  activated() {
    if (this.$route.meta.keepAlive) {
      this.init()
    }
  },
  deactivated() {
    if (!this.keep) {
      this.dataSource = []
      this.query = { page: 1, size: this.query.size }
    }
  }
}
</script>
