<template>
  <MDialog ref="dialog" title="角色分配" @sure="handleSaveRole">
    <MForm ref="form" :items="roleFormItems" v-model="roleFormValue">
      <template #username>
        <el-tag>{{ roleFormValue.username }}</el-tag>
      </template>
      <template #name>
        <el-tag>{{ roleFormValue.name }}</el-tag>
      </template>
    </MForm>
  </MDialog>
</template>

<script>
import {
  saveUser
} from '@/api/user'

import { getRoleList } from '@/api/menu'
export default {
  name: 'user-role',
  data () {
    return {
      roleFormValue: {
        roleId: null
      },
      itemData: {},
      loading: false
    }
  },
  computed: {
    roleFormItems () {
      return [
        {
          label: '用户账号',
          prop: 'username'
        },
        {
          label: '用户昵称',
          prop: 'name'
        },
        {
          label: '角色',
          prop: 'roleId',
          type: 'select',
          options: {
            multiple: true,
            placeholder: '请选择角色',
            filterable: true,
            remote: true,
            labelText: 'roleName',
            labelValue: 'id',
            remoteMethod: this.remoteMethod,
            valueKey: 'id',
            defaultFirstOption: true,
            loading: this.loading,
            items: this.items
          },
          rules: [
            { required: true, message: '请选择角色', trigger: 'change' }
          ]
        }
      ]
    }
  },
  methods: {
    async open (item) {
      this.itemData = item
      this.roleFormValue = {
        username: item.username,
        name: item.name,
        roleId: item.roleId ? item.roleId.split(',').map(e => +e) : []
      }
      if (this.roleFormValue.roleId.length > 0) {
        try {
          const { data } = await getRoleList({ ids: this.roleFormValue.roleId })
          this.items = data.records
        } catch (error) {
          this.items = []
          this.$message.error(error)
        }
      }
      this.$refs.dialog.open()
    },
    async remoteMethod (str) {
      this.loading = true
      try {
        const { data } = await getRoleList({ size: 50, roleName: str })
        this.items = data.records
      } catch (error) {
        this.items = []
        this.$message.error(error)
      } finally {
        this.loading = false
      }
    },
    async handleSaveRole () {
      this.$refs.form.validate(async valid => {
        if (!valid) {
          return
        }
        try {
          await saveUser({
            id: this.itemData?.id,
            tenantCode: this.itemData.tenantCode,
            roleId: this.roleFormValue.roleId.toString()
          })
          this.$message.success('保存成功')
          this.$refs.dialog.close()
          this.$emit('refresh')
        } catch (error) {
          this.$message.error(error)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
