<template>
  <div class="user-form" v-loading="loading">
    <el-form :model="formData" label-width="100px">
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="formData.phone" />
      </el-form-item>
      <el-form-item label="登录账号" prop="loginName">
        <el-input v-model="formData.loginName" />
      </el-form-item>
      <el-form-item label="默认密码">
        <span style="color: #999">abc@123</span>
      </el-form-item>
      <el-form-item label="角色">
        <el-radio-group v-model="formData.roleId">
          <el-radio :label="2">业务人员</el-radio>
          <el-radio :label="3">运营人员</el-radio>
        </el-radio-group>
      </el-form-item>
      <div class="user-form__action">
        <el-button type="primary" @click="submit"><i class="fa fa-save">&nbsp;</i> 保 存</el-button>
        <el-button>取 消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElNotification } from 'element-plus'
import { useModel } from '@/store'

export default {
  setup(props) {
    const loading = ref(false)
    const formData = reactive({})
    const route = useRoute()
    const router = useRouter()

    const { id } = route.query

    const { saveUser, getUser } = useModel('user')
    const { setPageTitle, setBack } = useModel('pageHeader')

    const submit = () => {
      loading.value = true
      saveUser(formData).then(res => {
        loading.value = false
        ElNotification.success({message: '提交成功'})
        router.replace({name: 'user.edit', query: {id: res.userId}})      
      }).catch(e => {
        console.error(e)
        loading.value = false
      })
    }

    onMounted(() => {
      setBack(true)

      if (id) {
        loading.value = true
        getUser(id).then(res => {
          Object.keys(res).forEach(k => {
            formData[k] = res[k]
            loading.value = false
          })
        }).catch(e => {
          console.error(e)
          loading.value = false
        })
      }
    })

    return {
      formData,
      submit
    }
  }
}
</script>

<style lang="less" scoped>
.user-form {
  background-color: #fff;
  padding: 4em 1em;
  display: flex;
  justify-content: center;

  .el-form {
    width: 480px;
  }

  &__action {
    display: flex;
    justify-content: space-around;
  }
}
</style>
