<template>
  <div class="layout-no-cols">
    <!-- <el-toolbar class="no-back">
      <el-col>
        <el-button type="button" class="el-button el-button--default save"  @click="save" priv="Member.Menu.Save"><span><i class="fa fa-save"></i>保存</span></el-button>
      </el-col>
    </el-toolbar> -->
    <div>
      <tree-grid :columns="columns" :tree-structure="true" :need-checkbox="false" :data-source="dataSource" @selection-change="onSelectionChange" draggable :strict="true" @after-sort="afterTreeGridSort" data-read-url="/ui/membermenu" ref="dataTable" :auto-get-data="false">
      </tree-grid>
    </div>
  </div>
</template>

<script>
import TreeGrid from '@src/components/TreeGrid.vue'
import util from '@src/common/util.js'
export default {
  data() {
    return {
      columns: [
        {
          text: '菜单名称',
          dataIndex: 'name'
        },
        {
          text: 'ID',
          dataIndex: 'ID'
        },
        {
          text: 'URL',
          dataIndex: 'URL'
        }
      ],
      // 加载动画
      // 请求到的数据
      dataSource: [],
      // 多选框选中的元素
      selectedRows: [],
      drag: true
    }
  },
  methods: {
    async afterTreeGridSort(data) {
      if (data.oldIndex === data.newIndex) {
        return
      }
      let oldObj = data.initialData[data.oldIndex]
      let newObj = data.initialData[data.newIndex]
      if (!oldObj.checked) {
        this.$alert('菜单未启用无法进行排序！', '提示', {
          type: 'warning'
        })
        this.getMemberMenuList()
        return
      }
      let ID = oldObj.ID
      let targetOrderFlag = newObj.orderFlag
      let res = await axios.put(`/ui/membermenu/${ID}/sort`, {targetOrderFlag})
      util.showResponseMessage(res.data)
      this.getMemberMenuList()
    },
    // 将被选中的元素存入selectedRows中
    onSelectionChange(selection) {
      this.selectedRows = selection
    },

    async getMemberMenuList() {
      await this.$refs.dataTable.getData()
    },

    // 保存
    async save() {
      let data = []
      for (let i = 0; i < this.selectedRows.length; i++) {
        data[i] = {}
        for (let k in this.selectedRows[i]) {
          if (k !== 'children' && k !== '_parent') {
            data[i][k] = this.selectedRows[i][k]
          }
        }
      }
      let dataList = await axios.put('/ui/membermenu', { data })
      if (dataList.data.status === 1) {
        this.getMemberMenuList()
      }
      util.showResponseMessage(dataList.data)
    }
  },
  components: {
    TreeGrid
  },
  mounted() {
    // 加载数据
    this.getMemberMenuList()
  }
}
</script>

<style scoped>

</style>
