<script setup>
import RPC from '@/utils/rpc'
const props = defineProps({
  type: {
    type: String,
    required: true,
  },
  row: [Object],
  categoryList: {
    type: Array,
    default: [],
  },
})

const emit = defineEmits(['closed', 'onSuccess'])

const dialogVisible = ref(false)

const isAdd = computed(() => props.type === 'add')

onMounted(() => {
  dialogVisible.value = true
})

const formRef = ref(null)
const formField = ref({})
const formRules = reactive({
  username: [{ required: true, message: '不可为空', trigger: 'change' }],
  password: [{ required: true, message: '不可为空', trigger: 'change' }],
})

const loading = ref(false)

function closed() {
  emit('closed')
}

const submitForm = async () => {
  await formRef.value.validate()
  const api = isAdd.value ? '/user/create' : '/user/update'
  const params = {
    ...formField.value,
    id: isAdd.value ? null : props.row.id,
  }
  RPC.post(api, params)
    .then((res) => {
      ElMessage.success('操作成功')
      emit('onSuccess')
      emit('closed')
    })
    .finally(() => {
      loading.value = false
    })
}

if (!isAdd.value) {
  formField.value = {
    ...props.row,
  }
}
</script>

<template>
  <el-dialog
    align-center
    :title="isAdd ? '新增' : '修改'"
    width="80%"
    v-model="dialogVisible"
    @closed="closed"
    :close-on-click-modal="false"
  >
    <el-form
      ref="formRef"
      label-position="right"
      label-suffix=":"
      :model="formField"
      :rules="formRules"
      v-loading="loading"
      label-width="100"
    >
      <el-form-item prop="username" label="用户名">
        <el-input placeholder="请输入" v-model="formField.username" />
      </el-form-item>
      <el-form-item v-if="isAdd" prop="password" label="密码">
        <el-input placeholder="请输入" v-model="formField.password" />
      </el-form-item>
      <el-form-item prop="phone" label="电话">
        <el-input placeholder="请输入" v-model="formField.phone" />
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
        <el-input placeholder="请输入" v-model="formField.email" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closed"> 取 消 </el-button>
        <el-button type="primary" :loading="loading" @click="submitForm"> 确 定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
