<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <div :class="advanced ? null: 'fold'">
          <a-row >
            <a-col :md="12" :sm="24" >
              <a-form-item
                label="部门名称"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 18, offset: 1}">
                <a-input v-model="queryParams.departmentName"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" >
              <a-form-item
                label="创建时间"
                :labelCol="{span: 5}"
                :wrapperCol="{span: 18, offset: 1}">
                <range-date @change="handleDateChange" ref="createTime"></range-date>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
        <span style="float: right; margin-top: 3px;">
          <a-button type="primary" @click="search">查询</a-button>
          <a-button style="margin-left: 8px" @click="reset">重置</a-button>
        </span>
      </a-form>
    </div>
    <div>
      <div class="operator">
        <a-button v-hasPermission="['authDepartment:add']" type="primary" ghost @click="addItem">新增</a-button>
        <a-button v-hasPermission="['updateDepartment:delete']" @click="batchDelete">删除</a-button>
        <a-dropdown v-hasPermission="['dept:export']">
          <a-menu slot="overlay">
            <a-menu-item key="export-data" @click="exportExcel">导出Excel</a-menu-item>
          </a-menu>
          <a-button>
            更多操作 <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>
      <!-- 表格区域 -->
      <a-table
              ref="TableInfo"
              :bordered="true"
              :columns="columns"
              :dataSource="dataSource"
              :pagination="pagination"
              :loading="loading"
              :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
              @change="handleTableChange"
              :scroll="{ x: 1000 }"
              size="small">
        <template slot="operation" slot-scope="text, record">
          <a-button type="primary" size="small"  @click="itemEdit(record)" v-hasPermission="['authDepartment:updateItem']">
            修改部门
          </a-button>
        </template>
      </a-table>
    </div>
    <!--信息修改-->
    <ItemEdit
            ref="ItemEdit"
            :itemEditData="itemData.data"
            :editVisible="itemData.editVisible"
            @close="handleEditClose"
            @success="handleEditSuccess">
    </ItemEdit>
    <!-- 信息新增-->
    <ItemAdd
            @close="handleItemAddClose"
            @success="handleItemAddSuccess"
            :addVisible="itemData.addVisible">
    </ItemAdd>
  </a-card>
</template>
<script>

import ImportExcel from '@/components/import/ImportExcel'
import UploadItem from '@/components/upload-item/UploadItem'
import RangeDate from '@/components/datetime/RangeDate'
import ItemAdd from './ItemAdd'
import ItemEdit from './ItemEdit'
import baseUtils from '@/utils/baseUtils'

export default {
  name: 'ItemList',
  components: {UploadItem,ImportExcel,baseUtils,ItemAdd, ItemEdit, RangeDate},
  data () {
    return {
      advanced: false,
      dataSource: [],
      selectedRowKeys: [],
      queryParams: {},
      sortedInfo: null,
      pagination: {
        defaultPageSize: 10000000,
        hideOnSinglePage: true,
        indentSize: 100
      },
      loading: false,
      itemData:{ //行信息
        data:{},
        particularsVisible:false,
        editVisible: false,
        addVisible: false
      },
    }
  },
  computed: {
    columns () {
      let { sortedInfo } = this
      sortedInfo = sortedInfo || {}
      return [
        {
          title: '名称',
          dataIndex: 'text',
          align:'center',
        },
        {
          title: '排序',
          dataIndex: 'order',
          align:'center',
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
          align:'center',
          sorter: true,
          sortOrder: sortedInfo.columnKey === 'createTime' && sortedInfo.order
        },
        {
          title: '修改时间',
          dataIndex: 'updateTime',
          align:'center',
          sorter: true,
          sortOrder: sortedInfo.columnKey === 'updateTime' && sortedInfo.order
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align:'center',
          width: 300,
          scopedSlots: { customRender: 'operation' }
        }
      ]
    }
  },
  mounted () {
    this.fetch()
  },
  methods: {
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    handleItemAddClose(){
      console.log('handleItemAddClose')
      this.itemData.addVisible = false
    },
    handleItemAddSuccess(){
      console.log('handleItemAddSuccess')
      this.itemData.addVisible = false
      this.$message.success('新增成功')
      this.search()
    },
    addItem () {
      this.itemData.addVisible = true
    },
    handleEditSuccess () {
      this.itemData.editVisible = false
      this.$message.success('更新成功')
      this.search()
    },
    handleEditClose () {
      this.itemData.editVisible = false
      this.search()
    },
    itemEdit (record) {
      let departmentName = record.text
      let orderNum = record.order
      let departmentId = record.key

      record.departmentName = departmentName
      record.orderNum = orderNum
      record.departmentId = departmentId

      this.itemData.data = record
      this.itemData.editVisible = true
    },
    handleDateChange (value) {
      if (value) {
        this.queryParams.beginTime = value[0]
        this.queryParams.endTime = value[1]
      }
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的记录')
        return
      }
      let that = this
      this.$confirm({
        title: '确定删除所选中的记录?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除，如果其包含子记录，也将一并删除！',
        centered: true,
        onOk () {
          console.log(JSON.stringify(that.selectedRowKeys.join(',')));
          that.$delete('api/v1/authDepartment/deleteDepartment/' + that.selectedRowKeys.join(',')).then(() => {
            that.$message.success('删除成功')
            that.selectedRowKeys = []
            that.fetch()
          })
        },
        onCancel () {
          that.selectedRowKeys = []
        }
      })
    },
    exportExcel () {
      let {sortedInfo} = this
      let sortField, sortOrder
      // 查询当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.$exportData('dept/excel', {
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams
      })
    },
    search () {
      let {sortedInfo} = this
      let sortField, sortOrder
      // 查询当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field
        sortOrder = sortedInfo.order
      }
      this.fetch({
        sortField: sortField,
        sortOrder: sortOrder,
        ...this.queryParams
      })
    },
    reset () {
      // 取消选中
      this.selectedRowKeys = []
      // 重置列排序规则
      this.sortedInfo = null
      // 重置查询参数
      this.queryParams = {}
      // 清空时间选择
      this.$refs.createTime.reset()
      this.fetch()
    },
    handleTableChange (pagination, filters, sorter) {
      this.sortedInfo = sorter
      this.fetch({
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...this.queryParams,
        ...filters
      })
    },
    fetch (params = {}) {
      this.loading = true
      this.$postBodyRequest('api/v1/authDepartment/queryAllDepartmentTreeList', {
        ...params
      }).then((r) => {
        let data = r.data.data
        this.loading = false
        this.dataSource.splice(0,this.dataSource.length)
        //console.log('部门查询结果: '+JSON.stringify(data))
        if(data && data.rows){
          console.log('this.dataSource : '+JSON.stringify(this.dataSource))
          if(!baseUtils.isNull(data.rows.children) && data.rows.children.length > 0 ){
            this.dataSource = data.rows.children
          }
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
/*webpack 会以~符号作为前缀的路径视为依赖模块去解析*/
  @import "~@static/less/Common";
</style>
