<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.roleName" placeholder="角色名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-button v-waves class="filter-item" type="info" @click="clearListQuery">清空</el-button>
      <el-button v-waves class="filter-item" type="primary" @click="handleFilter">查询</el-button>
    </div>
    <div style="margin-top: 20px;">
      <el-button type="primary" @click="addRole">添加</el-button>
      <el-button type="warning" @click="editRole">修改</el-button>
      <el-button type="danger" @click="deleteRole">删除</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="roleList"
      border
      fit
      highlight-current-row
      style="width: 100%; margin-top: 20px;"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="角色名称" align="center">
        <template slot-scope="scope">
          <span @click="handleLook(scope.row.id)" style="color: #409EFF;cursor: pointer">{{ scope.row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色描述" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.createDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改人" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updateName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.updateDate) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination v-show="total>0" :total="total" :current-page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" :page-sizes="[5, 10, 20, 30]" @pagination="getList" /> -->
    <el-pagination
      :total="total"
      :current-page="listQuery.pageNum"
      :page-sizes="[5, 10, 20, 30]"
      :page-size="listQuery.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"/>

  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from 'vuex'
import waves from '@/directive/waves' // Waves directive
import { parseTime } from '@/utils'

export default {
  computed: {
    ...mapState('role', {
      roleList: s => s.roleList,
      total: s => s.total
    })
  },
  directives: { waves },
  data() {
    var _self = this
    return {
      events: {
        click: (e) => {
          // _self.postData.Coordinate = e.lnglat.lat + ',' + e.lnglat.lng
          _self.detail.longitude = e.lnglat.lng
          _self.detail.latitude = e.lnglat.lat
        }
      },
      markers: [],
      searchOption: {
        city: '南京',
        citylimit: false
      },
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 20,
        roleName: undefined
      },
      tableKey: 0,
      downloadLoading: false,
      selectedIds: [] // 选择的id集合
    }
  },
  created() {
    this.getList()
  },
  methods: {
    ...mapMutations('role', {
    }),
    ...mapActions('role', [
      'FetchRoleList',
      'DeleteRoles'
    ]),
    setCurrent(item) {
      this.setDetail({ ...item })
    },
    getList() {
      this.listLoading = true
      this.FetchRoleList(this.listQuery).then(() => {
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
        console.log('get list error')
      })
    },
    clearListQuery() {
      this.listQuery.pageNum = 1
      this.listQuery.pageSize = 20
      this.listQuery.roleName = undefined
      this.getList()
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    handleSelectionChange(data) {
      // 设置为 空
      this.selectedIds = []
      for (let i = 0; i < data.length; i++) {
        this.selectedIds.push(data[i].id)
      }
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.listQuery.pageNum = val
      this.getList()
    },
    addRole(){
      this.$router.push({ name: 'role-add' })
    },
    editRole(){
      const ids = this.selectedIds
      if (ids.length > 1) {
        this.$message.error('只能选择一行数据进行修改!')
        return
      }
      if (ids < 1) {
        this.$message.error('请选择一行数据进行修改!')
        return
      }
      this.$router.push({ name: 'role-edit', params: { id: ids[0] }})
    },
    deleteRole(){
      const ids = this.selectedIds
      if (ids < 1) {
        this.$message.error('请选择数据!')
        return
      }
      this.listLoading = true
      this.DeleteRoles(ids).then((res) => {
        if (res.code === '0') {
          this.$message({
            message: res.message,
            type: 'success'
          })
          this.getList()
          this.listLoading = false
          return
        }
      }).catch(() => {
        this.loading = false
        console.log('get list error')
      })

    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    handleUpdate(row) {
      this.setCurrent(row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      this.getEditCityList()
      this.getEditDistrictList()
    },
    handleLook(id) {
      this.$router.push({ name: 'role-info', params: { id: id }})
    },
    handleCreate() {
      this.resetDetail()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    padDate(value) {
      value = value < 10 ? '0' + value : value
      return value
    },
    formatDate(val) {
      if (val === null) {
        return ''
      }
      var value = new Date(val)
      var year = value.getFullYear()
      var month = this.padDate(value.getMonth() + 1)
      var day = this.padDate(value.getDate())
      var hour = this.padDate(value.getHours())
      var minutes = this.padDate(value.getMinutes())
      var seconds = this.padDate(value.getSeconds())
      return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
  }
}
</script>
