<template>
  <schema-table
    ref="table"
    :schema="schema"
  >
    <template #pagination="{ options, pagination }">
      <div class="l-flex__none u-text-center">
        <el-button-group
          v-if="options.params.pageNum > 1 || options.totalCount > options.params.pageSize"
          class="has-top-padding"
        >
          <el-button
            class="o-pagination-button"
            type="primary"
            size="mini"
            :disabled="options.params.pageNum === 1"
            @click="onFirstPage(options, pagination)"
          >
            首页
          </el-button>
          <el-button
            class="o-pagination-button"
            type="primary"
            size="mini"
            icon="el-icon-arrow-left"
            :disabled="options.params.pageNum === 1"
            @click="onPresentPage(options, pagination)"
          >
            上一页
          </el-button>
          <el-button
            class="o-pagination-button"
            type="primary"
            size="mini"
            :disabled="options.totalCount <= options.params.pageSize"
            @click="onNextPage(options, pagination)"
          >
            下一页
            <i class="el-icon-arrow-right el-icon--right" />
          </el-button>
        </el-button-group>
      </div>
    </template>
    <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="仅可包含数字、字母"
        >
          <el-input
            v-model.trim="account.username"
            placeholder="4~20个字符"
            maxlength="20"
            clearable
          />
        </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: {
        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: {
    onFirstPage (options, pagination) {
      options.params.pageNum = 1
      pagination()
    },
    onPresentPage (options, pagination) {
      options.params.pageNum -= 1
      pagination()
    },
    onNextPage (options, pagination) {
      options.params.pageNum += 1
      pagination()
    },
    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>
