<route lang="yaml">
meta:
  enabled: false
  </route>

<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus'
import { createModule, getModuleById, updateModule } from '@/api/paas/moduleApi'
const emit = defineEmits(['success'])

const formRef = ref<FormInstance>()
const formRules = ref<FormRules>({
  modTitle: [
    { required: true, message: '请输入标题', trigger: 'blur' },
  ],
  modDesc: [
    { required: false, message: '请输入描述', trigger: 'blur' },
  ],
})

const state = reactive({
  title: '',
  dialogVisible: false,
  loading: false,
  formData: {
    modId: 1,
    modTitle: '',
    modDesc: '',
    isFixed: 0,
  },
  actionType: 1,
})

onMounted(() => {})

const getData = async (modId: number) => {
  state.loading = true
  const { data } = await getModuleById(modId)
  state.loading = false
  state.formData = data
}

function onSubmit() {
  formRef.value && formRef.value.validate(async (valid) => {
    if (valid) {
      if (state.actionType === 1) {
        await createModule(state.formData)
        state.dialogVisible = false
        emit('success')
      }
      else {
        await updateModule(state.formData)
        state.dialogVisible = false
        emit('success')
      }
    }
  })
}

function onCancel() {
  state.dialogVisible = false
}

function resetFormData() {
  state.formData = {
    modId: -1,
    modTitle: '',
    modDesc: '',
    isFixed: 0,
  }
}

defineExpose({
  showAddModule() {
    resetFormData()
    state.title = '新增API模块'
    state.actionType = 1
    state.dialogVisible = true
  },
  showEditModule(modId: any) {
    resetFormData()
    state.title = '编辑API模块'
    state.actionType = 2
    state.dialogVisible = true
    getData(modId)
  },

})
</script>

<template>
  <div>
    <el-dialog v-model="state.dialogVisible" :title="state.title" width="600px" :close-on-click-modal="false" append-to-body destroy-on-close>
      <div v-loading="state.loading">
        <el-form ref="formRef" :model="state.formData" :rules="formRules" label-width="120px" label-suffix="：">
          <el-form-item label="API模块名称" prop="modTitle">
            <el-input v-model="state.formData.modTitle" placeholder="请输入标题" />
          </el-form-item>

          <el-form-item label="简要说明" prop="modDesc">
            <el-input v-model="state.formData.modDesc" type="textarea" rows="10" placeholder="请输入标题" />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button size="large" @click="onCancel">
          取消
        </el-button>
        <el-button type="primary" size="large" @click="onSubmit">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
