<template>
  <XDialog v-if="visible"
           class="x-sort-panel"
           title="排序"
           @size-change="handleSizeChange"
           @opened="handleOpen"
           @close="handleClose"
           :stopPropagation="false"
           :maximizable="false"
           :minimizable="false"
           :visible.sync="visible"
           v-bind="dialog"
           v-on="$listeners">
    <div class="x-sort-panel__body">
      <div class="x-sort-panel__toolbar">
        <ElButton type="primary" icon="el-icon-plus" @click="addSort">添加条件</ElButton>
        <ElButton type="warning" icon="el-icon-delete" @click="removeSort">删除条件</ElButton>
      </div>
      <div class="x-sort-panel__table">
        <vxe-grid ref="vxeGrid"
                  :height="tableHeight"
                  auto-resize
                  :columns="columns"
                  border
                  v-bind="tableConfig"></vxe-grid>
      </div>
    </div>
    <template v-slot:footer>
      <ElButton type="primary" @click="submit">确定</ElButton>
      <ElButton @click="handleClose">取消</ElButton>
    </template>
  </XDialog>
</template>

<script>
/**
 * 表格排序管理模块
 * @module XSortPanel
 */
import { XDialog } from '@newpearl/ui';
import { Button as ElButton } from 'element-ui';
import { Grid } from 'vxe-table';

export default {
  name: 'XSortPanel',
  components: {
    XDialog,
    ElButton,
    [Grid.name]: Grid
  },
  /**
   * 属性参数
   * @property {object} [dialog] 弹窗配置对象
   * @property {boolean} [visible] 显示，支持sync修饰符
   * @property {function} [getSortList] 自定义获取表格排序的列，默认 $grid.getSortColumns()
   */
  props: {
    dialog: {
      type: Object
    },
    visible: Boolean,
    getSortList: Function
  },
  data() {
    return {
      panelVisible: false,
      tableHeight: 0,
      tableConfig: {
        editConfig: {
          trigger: 'click',
          enabled: true,
          mode: 'cell'
        },
        editRules: {
          field: [{ required: true, message: '请选择排序列' }],
          order: [{ required: true, message: '请选择列排序方式' }]
        }
      },
      columns: [
        {
          type: 'checkbox',
          width: 35
        },
        {
          field: 'field',
          title: '列',
          editRender: {
            name: 'ElSelect',
            options: [
              { label: '字段名称1', value: 'f1' },
              { label: '字段名称2', value: 'f2' }
            ]
          }
        },
        {
          field: 'order',
          title: '次序',
          editRender: {
            name: 'ElSelect',
            options: [
              { label: '升序', value: 'asc' },
              { label: '降序', value: 'desc' }
            ]
          }
        }
      ]
    };
  },
  methods: {
    /**
     * 连接表格
     * @param {VxeTable} grid 表格实例
     */
    connect(grid) {
      if (!grid) return;
      this.$grid = grid;
    },
    handleSizeChange({ height }) {
      this.tableHeight = `${height - 50}px`;
    },
    getColumnOptions() {
      const $grid = this.$grid;
      if (!$grid) return;
      const { fullColumn } = $grid.getTableColumn();
      return fullColumn.filter(n => !n.type).map(n => {
        return {
          label: n.title,
          value: n.property
        };
      });
    },
    handleOpen() {
      const $grid = this.$grid;
      const vxeGrid = this.$refs.vxeGrid;
      if (!$grid || !vxeGrid) return;
      const columnOptions = this.getColumnOptions();
      const columnField = vxeGrid.getColumnByField('field');
      const sortColumns = this.getSortList ? this.getSortList() : $grid.getSortColumns();
      columnField.editRender.options = columnOptions;
      const sortData = sortColumns.map(n => {
        return {
          field: n.property,
          order: n.order
        };
      });
      vxeGrid.loadData(sortData);
    },
    handleClose() {
      this.$emit('update:visible', false);
    },
    addSort() {
      const vxeGrid = this.$refs.vxeGrid;
      const data = vxeGrid.getData();
      data.push({
        field: '', order: ''
      });
      vxeGrid.loadData(data);
    },
    removeSort() {
      const vxeGrid = this.$refs.vxeGrid;
      const records = vxeGrid.getCheckboxRecords(true);
      if (records && records.length > 0) {
        const data = vxeGrid.getData();
        const newData = data.filter(n => !records.includes(n));
        vxeGrid.loadData(newData);
      } else {
        this.$notify.warning('请选择删除行');
      }
    },
    hasDuplicates(array) {
      return array.some((n, i) => {
        return array.findIndex(m => m.field === n.field) !== i;
      });
    },
    async validate() {
      const vxeGrid = this.$refs.vxeGrid;
      const error = await vxeGrid.validate(true);
      if (!error && this.hasDuplicates(vxeGrid.getData())) {
        this.$notify.warning('请删除重复的排序条件');
        return false;
      }
      return !error;
    },
    async submit() {
      const valid = await this.validate();
      if (!valid) return;
      const $grid = this.$grid;
      const vxeGrid = this.$refs.vxeGrid;
      const result = vxeGrid.getData();
      const data = result.map(n => {
        const { field, order } = n;
        return {
          field,
          order
        };
      });
      $grid.sort(data);
      const params = { sortList: $grid.getSortColumns() };
      $grid.$emit('sort-change', params);
      this.handleClose();
    }
  }
};
</script>
