<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({
  name: [{ required: true, message: '不可为空', trigger: 'change' }],
  code: [{ required: true, message: '不可为空', trigger: 'change' }],
})

const loading = ref(false)

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

const submitForm = async () => {
  await formRef.value.validate()
  const api = isAdd.value ? '/role/create' : '/role/update'
  const params = {
    ...formField.value,
    id: isAdd.value ? null : props.row.id,
  }
  loading.value = true
  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="name" label="名称">
        <el-input placeholder="请输入" v-model="formField.name" />
      </el-form-item>
      <el-form-item prop="code" label="字段">
        <el-input placeholder="请输入" v-model="formField.code" />
      </el-form-item>
      <el-form-item prop="description" label="描述">
        <el-input placeholder="请输入" v-model="formField.description" />
      </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>
