<template>
  <div class="app-container">
    <el-button
        type="primary"
        @click="handleCreateAdmin"
    >
      {{$t('admin.addAdmin')}}
    </el-button>

    <el-table
        :data="adminList"
        style="width: 100%;margin-top:30px;"
        border
    >
      <el-table-column
          align="center"
          label="帐号名"
      >
        <template slot-scope="{row}">
          {{row.username}}
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          label="显示名"
      >
        <template slot-scope="{row}">
          {{row.showname}}
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          label="角色"
      >
        <template slot-scope="{row}">
          {{ row.roles.join(',') }}
        </template>
      </el-table-column>
      <el-table-column
          align="header-center"
          label="备注"
      >
        <template slot-scope="{row}">
          {{row.comment}}
        </template>
      </el-table-column>
      <el-table-column
          align="center"
          label="操作"
      >
        <template slot-scope="scope">
          <el-button
              type="primary"
              size="small"
              @click="handleEdit(scope)"
          >
            {{$t('admin.editAdmin')}}
          </el-button>
          <el-button
              type="danger"
              size="small"
              @click="handleDelete(scope)"
          >
            {{$t('permission.delete')}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
        :visible.sync="dialogVisible"
        :title="dialogType==='edit'?'Edit Admin':'New Admin'"
    >
      <el-form
          :model="record"
          label-width="80px"
          label-position="left"
      >
        <el-form-item label="用户名">
          <el-input
              v-model="record.username"
              placeholder="用户名"
          />
        </el-form-item>
        <el-form-item label="密码" v-if="dialogType==='edit'">
          <el-input
              type="password"
              v-model="record.password"
              placeholder="不修改就留空"
          />
        </el-form-item>
        <el-form-item label="密码" v-if="dialogType!=='edit'">
          <el-input
              type="password"
              v-model="record.password"
              placeholder="密码"
          />
        </el-form-item>
        <el-form-item label="显示名">
          <el-input
              v-model="record.showname"
              placeholder="显示名"
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="record.sex">
            <el-radio label="0" >未指定</el-radio>
            <el-radio label="1" >男</el-radio>
            <el-radio label="2" >女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色">
          <el-checkbox-group v-model="record.roles">
            <el-checkbox v-for="role in roleList"
                         :key="role.key"
                :label="role.key"
                name="type"
            >{{role.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="锁定">
          <el-switch v-model="record.locked" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
              v-model="record.comment"
              :autosize="{minRows: 2, maxRows: 4}"
              type="textarea"
              placeholder="备注"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button
            type="danger"
            @click="dialogVisible=false"
        >
          {{$t('permission.cancel')}}
        </el-button>
        <el-button
            type="primary"
            @click="confirmRole"
        >
          {{$t('permission.confirm')}}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { cloneDeep } from 'lodash'
import { Component, Vue } from 'vue-property-decorator'
import { getRoles } from '@/api/roles'
import TagInput from '@/components/TagInput/index.vue'
import { getUsers, deleteAdmin, saveAdmin } from '@/api/admins'
import { IRole } from '@/views/system/role.vue'

interface IAdmin {
  id: string
  username: string
  showname: string
  comment: string
  locked: boolean
  roles: string[]
  sex: string
  avatar: string
  password: string
}

const defaultAdmin: IAdmin = {
  id: '',
  username: '',
  showname: '',
  comment: '',
  locked: false,
  roles: [],
  sex: '0',
  password: '',
  avatar: ''
}

@Component({
  name: 'AdminSystem',
  components: {
    TagInput
  }
})
export default class extends Vue {
  private record = Object.assign({}, defaultAdmin)
  private adminList: IAdmin[] = []
  private roleList: IRole[] = []
  private dialogVisible = false
  private dialogType = 'new'
  private checkStrictly = false
  private defaultProps = {
    children: 'children',
    label: 'title'
  }

  created() {
    this.getRecords()
    this.getAllRole()
  }

  private async getRecords() {
    const { data } = await getUsers({ /* Your params here */ })
    this.adminList = data
  }

  private async getAllRole() {
    const { data } = await getRoles({ /* Your params here */ })
    this.roleList = data
  }

  private handleCreateAdmin() {
    this.record = Object.assign({}, defaultAdmin)

    this.dialogType = 'new'
    this.dialogVisible = true
  }

  private handleEdit(scope: any) {
    this.dialogType = 'edit'
    this.dialogVisible = true
    this.checkStrictly = true
    this.record = cloneDeep(scope.row)
  }

  private handleDelete(scope: any) {
    const { $index, row } = scope
    this.$confirm('Confirm to remove the record?', 'Warning', {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel',
      type: 'warning'
    })
      .then(async() => {
        await deleteAdmin(row.id)
        this.adminList.splice($index, 1)
        this.$message({
          type: 'success',
          message: 'Deleted!'
        })
      })
      .catch(err => {
        console.log(err)
      })
  }
  // TODO: 验证数据完整性
  private async confirmRole() {
    const isEdit = this.dialogType === 'edit'
    const { data } = await saveAdmin(this.record)
    console.log(data)
    if (isEdit) {
      for (let index = 0; index < this.adminList.length; index++) {
        if (this.adminList[index].id === this.record.id) {
          this.adminList.splice(index, 1, Object.assign({}, this.record))
          break
        }
      }
    } else {
      this.adminList.push(data)
    }

    const { username, showname } = this.record
    this.dialogVisible = false
    this.$notify({
      title: 'Success',
      dangerouslyUseHTMLString: true,
      message: `
          <div>Admin Username: ${username}</div>
          <div>Admin Showname: ${showname}</div>
        `,
      type: 'success'
    })
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }

  .permission-tree {
    margin-bottom: 30px;
  }
}

read-only {
  color: #a09d9d;
}
</style>
