<template>
  <div class="app-container">
    <div v-loading.fullscreen.lock="loadingFull" />
    <div class="filter-container">
      <el-button
        type="primary"
        icon="el-icon-edit"
        class="filter-item"
        @click="handleAddAccount"
      >
        添加账号
      </el-button>
    </div>

    <el-table
      :data="table"
      :header-cell-style="{ background: '#f8fbfc' }"
      class="tableBorder"
      border
      stripe
    >
      <el-table-column
        prop="id"
        align="center"
        label="ID"
        width="100px"
      />
      <el-table-column
        prop="name"
        align="center"
        label="账户名"
      />
      <el-table-column
        prop="role"
        align="center"
        label="角色"
      >
        <template
          slot-scope="{ row: { role } }"
        >
          {{ (role && role.name) || '角色名不存在' }}
        </template>
      </el-table-column>
      <el-table-column
        prop="created_at"
        align="center"
        label="创建时间"
      />
      <el-table-column
        prop="status"
        align="center"
        label="状态"
        width="150"
      >
        <template
          slot-scope="scope"
        >
          <el-tag
            :type="scope.row.status === 1 ? 'success' : 'danger'"
          >
            {{ scope.row.status === 1 ? '正常' : '已禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="300px"
      >
        <template
          slot-scope="scope"
        >
          <el-button
            type="primary"
            size="mini"
            @click="handleEdit(scope.row)"
          >
            修改账户
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
          <el-button
            type="primary"
            size="mini"
            @click="handleChange(scope.row)"
          >
            {{ scope.row.status === 1 ? '禁用' : '启用' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :total="tableTotal"
      :limit="searchParams.page_size"
      :page="searchParams.page_index"
      @pagination="changePagination"
      @update:limit="changePagination"
    />

    <el-dialog
      :title="dialogType === 'add' ? '添加账号' : '修改账号'"
      top="50px"
      :visible.sync="dialogVisible"
    >
      <el-form
        ref="accountForm"
        :model="account"
        :rules="accountRules"
        label-width="100px"
      >
        <el-form-item label="登陆账户:" prop="username">
          <el-input
            v-model="account.username"
            style="width:300px"
            minlength="5"
            maxlength="12"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="登陆密码:" prop="password">
          <el-input
            v-model="account.password"
            style="width:300px"
            minlength="6"
            maxlength="12"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="所属角色:" prop="role">
          <el-select
            v-model="account.role"
            placeholder="请选择角色"
            style="width:300px"
          >
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号:">
          <el-input
            v-model="account.mobile"
            type="text"
            placeholder="手机号"
            maxlength="11"
            show-word-limit
            style="width:300px"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirmAccount">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import {
  getRolesList
} from '@/api/roles'

import {
  addAccount,
  getAccountList,
  deleteAccount,
  changeAccountStatus,
  editAccount
} from '@/api/account'

export default {
  data() {
    return {
      accountRules: {
        username: [
          { required: true, message: '请输入登录账户名', trigger: 'blur' },
          { min: 5, max: 12, message: '长度在 5 到 12 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: 'blur' }
        ],
        role: [
          { required: true, message: '请选择角色', trigger: 'change' }
        ]
      },
      account: {
        username: '',
        password: '',
        role: '',
        mobile: ''
      },
      searchParams: {
        page_size: 20,
        page_index: 1
      },
      rolesList: [],
      tableTotal: 0,
      table: [],
      dialogVisible: false,
      dialogType: 'add',
      editId: '',
      loadingFull: false
    }
  },
  created() {
    this.getRolesList()
    this.getAccountList()
  },
  methods: {
    handleAddAccount() {
      this.dialogVisible = true
      this.dialogType = 'add'
    },
    // 取消
    handleCancel() {
      this.$refs.accountForm.resetFields()
      this.dialogVisible = false
    },
    // 获取角色
    async getRolesList() {
      try {
        const { data } = await getRolesList()
        this.rolesList = data.filter(item => item.name !== 'root')
      } catch (e) {
        this.rolesList = []
      }
    },
    // 分页页码变化
    changePagination(data) {
      const { page, limit } = data
      this.searchParams.page_size = limit
      this.searchParams.page_index = page
      this.getAccountList()
    },
    // 获取列表
    async getAccountList() {
      this.loadingFull = true
      try {
        const { page_size, page_index } = this.searchParams
        const res = await getAccountList({
          page_size,
          page_index
        })
        const { data } = res
        const { list, total } = data
        let count = 0
        this.table = list.filter(item => {
          if (item.role && item.role.name === 'root') count++
          return (item.role && item.role.name !== 'root')
        })
        this.tableTotal = total - count
      } catch (e) {
        console.log(`获取账户信息失败: ${e}`)
      }
      this.loadingFull = false
    },
    // 添加/修该账户
    async handleConfirmAccount() {
      this.$refs.accountForm.validate((valid) => {
        if (valid) {
          const type = this.dialogType
          const { username, password, role, mobile } = this.account
          if (type === 'add') {
            addAccount({
              name: username,
              password,
              role_id: role,
              mobile
            }).then(res => {
              try {
                const { message, code } = res
                if (code === 200) {
                  this.dialogVisible = false
                  this.$refs.accountForm.resetFields()
                  this.getAccountList()
                }
                this.$message({
                  message,
                  type: code === 200 ? 'success' : 'error'
                })
              } catch (e) {
                const message = e.message ? e.message : '请求失败'
                this.message.error(message)
              }
            })
          } else {
            editAccount({
              id: this.editId,
              name: username,
              password,
              role_id: role,
              mobile
            }).then(res => {
              try {
                const { message, code } = res
                if (code === 200) {
                  this.dialogVisible = false
                  this.$refs.accountForm.resetFields()
                  this.getAccountList()
                }
                this.$message({
                  message,
                  type: code === 200 ? 'success' : 'error'
                })
              } catch (e) {
                const message = e.message ? e.message : '请求失败'
                this.message.error(message)
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 删除
    handleDelete(row) {
      this.$confirm('确定要删除这个账号吗?', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const { id } = row
        this.deleteAccount(id)
      })
    },
    // 删除
    async deleteAccount(id) {
      const res = await deleteAccount({ id })
      try {
        const { message, code } = res
        this.$message({
          message,
          type: code === 200 ? 'success' : 'error'
        })
        if (code === 200) {
          this.getAccountList()
        }
      } catch (e) {
        let message = res.message ? res.message : e.message
        message = e.message ? e.message : '请求失败'
        this.$message.error(message)
      }
    },
    // 禁用启用
    async handleChange(row) {
      const { id } = row
      const res = await changeAccountStatus({ id })
      try {
        const { message, code } = res
        this.$message({
          message,
          type: code === 200 ? 'success' : 'error'
        })
        if (code === 200) {
          this.getAccountList()
        }
      } catch (e) {
        let message = res.message ? res.message : e.message
        message = e.message ? e.message : '请求失败'
        this.$message.error(message)
      }
    },
    // 修改
    handleEdit(row) {
      const { id, name, role_id, mobile } = row
      this.dialogVisible = true
      this.dialogType = 'edit'
      this.editId = id
      this.account.username = name
      this.account.role = role_id
      this.account.mobile = mobile
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
