<template>
  <schema-table
    ref="table"
    :schema="schema"
  >
    <confirm-dialog
      ref="editDialog"
      title="新增账号"
      @confirm="onSave"
      @cancel="onCancel"
    >
      <div
        v-if="account"
        class="c-grid-form u-align-self--center"
      >
        <span class="c-grid-form__label required">账号：</span>
        <div
          class="c-grid-form__info"
          data-info="仅可包含数字、字母，至少4位"
        >
          <el-input
            v-model.trim="account.username"
            placeholder="请填写用户账号"
            maxlength="20"
            show-word-limit
          />
        </div>
        <span class="c-grid-form__label c-grid-form__auto">分组：</span>
        <div class="c-grid-form__auto u-bold">
          {{ group.label }}
        </div>
      </div>
    </confirm-dialog>
    <el-dialog
      :visible.sync="showSettings"
      title="设置"
      custom-class="c-dialog medium"
    >
      <settings
        v-if="showSettings"
        :user="user"
        :groups="groups"
        @del="onDel"
        v-on="$listeners"
      />
    </el-dialog>
  </schema-table>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  addUser,
  getUsersByGroup
} from '@/api/user'
import Settings from './Settings'

export default {
  name: 'Account',
  components: {
    Settings
  },
  props: {
    groups: {
      type: Array,
      required: true
    },
    group: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      schema: {
        singlePage: true,
        condition: { id: this.group.id },
        list: getUsersByGroup,
        buttons: [
          { type: 'add', on: this.onAdd }
        ],
        cols: [
          { prop: 'username', label: '账号' },
          { prop: 'enabled', type: 'tag', render: ({ id, enabled }) => id === this.userId
            ? null
            : {
              type: enabled ? 'success' : 'danger',
              label: enabled ? '启用' : '禁用'
            } },
          { type: 'invoke', use: ({ id }) => id !== this.userId, render: [
            { label: '设置', on: this.onSettings }
          ] }
        ]
      },
      account: null,
      showSettings: false
    }
  },
  computed: {
    ...mapGetters(['userId', 'isSuperAdmin'])
  },
  watch: {
    group () {
      this.showSettings = false
      this.$refs.table.mergeCondition({ id: this.group.id })
    }
  },
  methods: {
    onSettings (user) {
      this.user = user
      this.showSettings = true
    },
    onDel () {
      this.$message({
        type: 'success',
        message: '注销成功'
      })
      this.showSettings = false
      this.$refs.table.decrease(1)
    },
    onAdd () {
      this.account = {
        username: '',
        group: this.group
      }
      this.$refs.editDialog.show()
    },
    onSave (done) {
      const { username, group } = this.account
      if (!username) {
        this.$message({
          type: 'warning',
          message: '请填写用户账号'
        })
        return
      }
      if (username.length < 4) {
        this.$message({
          type: 'warning',
          message: '用户账号过短'
        })
        return
      }
      if (!/^[\da-zA-Z]{4,}$/.test(username)) {
        this.$message({
          type: 'warning',
          message: '用户账号格式错误'
        })
        return
      }
      if (!group) {
        this.$message({
          type: 'warning',
          message: '请选择用户所属的分组'
        })
        return
      }
      addUser({
        username,
        groups: this.getGroups(group),
        enabled: true,
        credentials: [{ type: 'password', value: process.env.VUE_APP_USER_PASSWORD, temporary: true }]
      }).then(() => {
        done()
        this.onCancel()
        this.$refs.table.pageTo()
      })
    },
    getGroups (group) {
      const groups = [group.path]
      let target = group
      while (target.parentGroup) {
        target = group.parentGroup
        groups.unshift(target.path)
      }
      return groups
    },
    onCancel () {
      this.account = null
    }
  }
}
</script>
