<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form ref="form" label-width="80px" :model="form" :rules="rules">
      <el-form-item :label="__('用户名')" prop="user_account">
        <el-input v-model.trim="form.user_account" />
      </el-form-item>
      <el-form-item :label="__('密码')" prop="user_password">
        <el-input v-model.trim="form.user_password" type="password" />
      </el-form-item>
      <el-form-item :label="__('角色')" prop="roles">
        <el-checkbox-group v-model="form.roles">
          <el-checkbox
            v-for="(item, index) in roleList"
            :key="index"
            :label="item.rights_group_id"
          >
            {{ __(item.rights_group_name) }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">{{ __('取消') }}</el-button>
      <el-button type="primary" @click="save">{{ __('确定') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { doEdit } from '@/api/user/base'
  import { getRoles } from '@/api/rights/group'
  import { translateTitle as __ } from '@/utils/i18n'

  export default {
    name: 'UserManagementEdit',
    data() {
      return {
        form: {
          roles: [],
          rights_group_id: '',
          is_admin: 'sys',
        },
        rules: {
          user_account: [
            { required: true, trigger: 'blur', message: '请输入用户名' },
          ],
          // email: [{ required: true, trigger: 'blur', message: '请输入邮箱' }],
          roles: [{ required: true, trigger: 'blur', message: '请选择角色' }],
        },
        title: '',
        dialogFormVisible: false,
        roleList: [],
      }
    },
    created() {
      this.getRoles()
    },
    methods: {
      __,
      showEdit(row) {
        if (!row) {
          this.title = '添加'
        } else {
          this.title = '编辑'
          this.form = Object.assign({}, row)
          this.form.is_admin = this.form.is_admin
          this.form.roles = row.rights_group_id
            .split(',')
            .map((item) => Number(item))
        }
        this.dialogFormVisible = true
      },
      close() {
        this.form = this.$options.data().form
        this.$refs['form'].resetFields()
        this.dialogFormVisible = false
      },
      save() {
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            this.form.rights_group_id = this.form.roles.toString()
            const { msg, status } = await doEdit(this.form)
            this.$baseMessage(msg, 'success', false, 'vab-hey-message-success')
            this.$emit('fetch-data')
            this.close()
          } else {
            return false
          }
        })
      },
      async getRoles() {
        const { data } = await getRoles()
        this.roleList = data
      },
    },
  }
</script>
