<template>
  <div class="content-container">
    <el-row class="tool-bar">
      <el-col :span="6" class="left">
        <div class="content-title">
          {{ title }}
        </div>
      </el-col>
      <el-col :span="16" class="right">
        <el-input v-model="conditions.keywords" class="search-input m-right-15" placeholder="请输入内容">
          <el-button slot="append" icon="el-icon-search" @click="getData()" />
        </el-input>
        <el-button type="primary" @click="handleAddUser">新增用户</el-button>
      </el-col>
    </el-row>

    <el-row class="content-body">
      <el-table v-loading="listLoading" class="page-table" :data="dataList" height="calc(100vh - 240px)">
        <el-table-column type="index" align="center" label="序号" width="70" />

        <el-table-column align="center" header-align="center" label="头像" width="50">
          <template v-slot="{row}">
            <el-avatar :size="30" :src="row.accountAvatar" />
          </template>
        </el-table-column>

        <el-table-column align="center" width="100" label="账号">
          <template v-slot="{row}">
            <span>{{ row.accountName }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" width="100" label="姓名">
          <template v-slot="{row}">
            <span>{{ row.accountRealName }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" width="100" label="工号">
          <template v-slot="{row}">
            <span>{{ row.accountStaffNo }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" width="120" label="联系方式">
          <template v-slot="{row}">
            <span>{{ row.accountPhone }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="所在部门">
          <template v-slot="{row}">
            <span>{{ row.groupName }}</span>
          </template>
        </el-table-column>

        <!-- <el-table-column align="center" width="100" label="岗位">
          <template v-slot="{row}">
            <span>{{ row.positionName }}</span>
          </template>
        </el-table-column> -->

        <el-table-column align="center" label="状态" width="140">
          <template v-slot="{row}">
            <div v-if="row.isFixed !== 1">
              <el-switch
                v-model="row.status"
                active-text="正常"
                inactive-text="锁定"
                :active-value="1"
                :inactive-value="2"
                @change="(status)=>handlerChangeUserStatus(status, row)"
              />
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" header-align="center" align="center" width="210">
          <template v-slot="{row}">
            <el-button size="mini" @click="handleEditUser(row)">修改</el-button>
            <el-button v-if="row.isFixed !== 1" size="mini" type="danger" @click="handleDeleteUser(row)">删除</el-button>
            <el-dropdown v-if="row.isFixed !== 1" class="el-dropdown-link" @command="(command)=>handlerCommand(command, row)">
              <el-button size="mini" type="primary">
                更多<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <template v-if="row.grantGroupId > 0">
                  <el-dropdown-item command="editGrantGroup">编辑授权</el-dropdown-item>
                  <el-dropdown-item command="delGrantGroup">解除授权</el-dropdown-item>
                </template>
                <template v-else>
                  <el-dropdown-item command="addGrantGroup">添加授权</el-dropdown-item>
                </template>
                <el-dropdown-item command="resetPwd">重置密码</el-dropdown-item>
                <el-dropdown-item command="handlePermit">权限配置</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <pagination v-show="total>0" :total="total" :page.sync="conditions.page" :limit.sync="conditions.limit" @pagination="getData" />
      </div>

    </el-row>
    <user ref="AddUser" @formSuccess="getData" />
    <user ref="EditUser" title="编辑用户" @formSuccess="getData" />
    <grant-group ref="AddGrantGroup" title="添加授权" @formSuccess="getData" />
    <grant-group ref="EditGrantGroup" title="变更授权" @formSuccess="getData" />
    <account-permit ref="AccountPermit" title="权限配置" />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import AccountPermit from '@/views/system/permit/account'
import GrantGroup from './GrantGroup.vue'
import User from './User.vue'
import { deleteUserById, getUserByPage, resetPassword, updateUserStatus } from '@/api/system/userApi'
import { mapGetters } from 'vuex'

export default {
  name: 'UserList',
  components: { Pagination, User, GrantGroup, AccountPermit },
  props: { },
  data() {
    return {
      title: '用户管理',
      dataList: [],
      total: 0,
      listLoading: false,
      conditions: {
        page: 1,
        limit: 10,
        keyword: '',
        groupId: null,
        groupName: ''
      }
    }
  },

  computed: {
    ...mapGetters([
      'userData'
    ])
  },

  mounted() {
  },

  methods: {

    // Change User "Status"
    handlerChangeUserStatus(status, data) {
      updateUserStatus(data.accountId, status).then((resp) => {
        const { code, msg } = resp
        if (code === 0) {
          this.$message.success(msg)
        } else {
          this.$message.error(msg)
        }
      }).catch((error) => {
        console.log(error)
      })
    },

    // Command Handling
    handlerCommand(command, data) {
      switch (command) {
        case 'addGrantGroup':
          this.$refs['AddGrantGroup'].showAddModel(data.accountId)
          break

        case 'editGrantGroup':
          this.$refs['EditGrantGroup'].showEditModel(data.accountId)
          break

        case 'delGrantGroup':
          this.handleDelGrantGroup(data)
          break

        case 'resetPwd':
          this.handleResetPassword(data)
          break

        case 'handlePermit':
          this.handlePermit(data)
          break
      }
    },

    // Load Data
    loadData(groupId, groupName) {
      this.conditions.groupId = groupId
      this.conditions.groupName = groupName
      this.getData()
    },

    // Fetch User Data
    getData() {
      this.listLoading = true
      getUserByPage(this.conditions).then((resp) => {
        this.listLoading = false
        const { code, data, total, msg } = resp
        if (code === 0) {
          this.total = total
          this.dataList = data
        } else {
          this.$message.error(msg)
        }
      }).catch((error) => {
        console.log(error)
      })
    },

    // Click "Add"
    handleAddUser() {
      const groupId = this.conditions.groupId
      const groupName = this.conditions.groupName
      this.$refs['AddUser'].showAddModel(groupId, groupName)
    },

    // Click "Edit"
    handleEditUser(data) {
      const groupId = data.groupId
      const accountId = data.accountId
      this.$refs['EditUser'].showEditModel(groupId, accountId)
    },

    // Click "Reset Password"
    handleResetPassword(data) {
      this.$confirm('温馨提示：系统默认重置密码为 888888', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetPassword(data.accountId).then((resp) => {
          const { code, msg } = resp
          if (code === 0) {
            this.$message.success(msg)
          } else {
            this.$message.error(msg)
          }
        })
      }).catch(() => {
        this.$message.info('已取消重置')
      })
    },

    // 权限管理
    handlePermit(data) {
      const { accountId, positionId } = data
      this.$refs['AccountPermit'].showModel(accountId, positionId)
    },

    // Click "Delete" User
    handleDeleteUser(data) {
      this.$confirm('此操作将永久删除该账号, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteUserById(data.accountId).then((resp) => {
          const { code, msg } = resp
          if (code === 0) {
            this.getData()
            this.$message.success(msg)
          } else {
            this.$message.error(msg)
          }
        })
      }).catch(() => {
        this.$message.info('已取消操作')
      })
    }
  }
}
</script>

<style scoped>
.content-container {
  margin: 10px 10px 10px 0 ;
}

</style>
