<template>
  <el-dialog title="设置角色" :visible="visible" @close="handleClose" :close-on-click-modal="false"> 
    <el-form label-width="80px" v-if="info" :rules="rules" :model="ruleForm" ref="ruleForm">
      <el-form-item label="手机号">
        <el-input disabled v-model="info.mobile" placeholder="手机号" />
      </el-form-item>

      <el-form-item label="角色" prop="role_id">
        <el-radio-group v-model="ruleForm.role_id">
          <el-radio v-for="role in roles" :label="role.id" :key="role.id">{{role.role_name}}</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item class="flex-end">
        <el-button :loading="loading" type="primary" size="mini" @click="onSubmit">保存</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import asyncRequest from "@/apis/service/operate/account";
export default {
  name:"SetRoleModal",
  props:["info", "visible"],
  computed:{
    _visible:{
      get(){
        return this.visible
      },
      set(newVal){
        this.$emit("update:visible", newVal)
      }
    }
  },
  watch:{
    _visible:{
      handler(newVal){
        if(!newVal) return
        const { role_id } = this.info
        this.ruleForm.role_id = role_id
      },
      immediate:true
    }
  },
  data(){
    return {
      loding:false,
      roles: [],
      ruleForm:{
        role_id:""
      },
      rules:{
        role_id:[
          {
            required:true,
            trigger:'change',
            message:'选择角色'
          }
        ]
      }
    }
  },
  mounted(){
    this.requsetRoles()
  },
  methods:{
    async onSubmit(){
      try{
        await this.$refs.ruleForm.validate()
        this.loading = true
        const response = await asyncRequest.setRole({ id: this.info.id, ...this.ruleForm })
        this.loading = false
        if(response.code === 1) {
           this.$emit("refresh")
           this._visible = false
        }
      }catch(err){
        console.log(err)
      }
    },
    handleClose(){
      this.ruleForm = {role_id:""} 
      this._visible = false
    },
    async requsetRoles(){
      const { code, data } = await asyncRequest.roleQuery({})
      if(code === 1) this.roles = data
    }
  }
}
</script>
