<template>
  <ElDialog
    v-model="showDialog"
    :close-on-click-modal="false"
    destroy-on-close
    width="fit-content"
    @close="dialogCloseHandler">
    <ElForm :model="formData"
      ref="endpointForm"
      :rules="rules"
      class="form-panel"
      label-width="auto">

      <ElFormItem label="请求方式" prop="requestMethod">
        <ElSelect
          v-model="formData.requestMethod"

          placeholder="请求方式">
          <ElOption label="GET 请求" value="GET"/>
          <ElOption label="POST 请求" value="POST"/>
          <ElOption label="PUT 请求" value="PUT"/>
          <ElOption label="DELETE 请求" value="DELETE"/>
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="路由前缀" prop="routingPath">
        <ElInput
          v-model="formData.routingPath"

          placeholder="以 / 开头 或 为空"/>
      </ElFormItem>
      <ElFormItem label="端点地址" prop="endpointPath">
        <ElInput
          v-model="formData.endpointPath"

          placeholder="以 / 开头"/>
      </ElFormItem>
      <ElFormItem label="访问模式" prop="accessModel">
        <ElSelect
          v-model="formData.accessModel"

          placeholder="访问模式">
          <ElOption label="允许匿名访问" value="Anonymous"/>
          <ElOption label="允许已登录用户访问" value="Logined"/>
          <ElOption label="仅拥有权限的用户访问" value="Authenticated"/>
          <ElOption label="禁止访问" value="Forbidden"/>
        </ElSelect>
      </ElFormItem>
      <ElFormItem label="备注" prop="memo">
        <ElInput
          v-model="formData.memo"

          placeholder="备注"/>
      </ElFormItem>
    </ElForm>
    <template #footer>
      <ElButton @click="showDialog = false">{{ status === 'view' ? '关闭' : '取消' }}</ElButton>
      <ElButton v-if="status !== 'view'" :loading="submiting" type="primary" @click="submitHandler">提交</ElButton>
    </template>
  </ElDialog>
</template>

<script lang="ts" setup>
import EndpointApi from '@/pages/sys/endpoint/endpoint-api.ts'
import Strings from '@/common/utils/strings.ts'
import FormUtil from '@/common/utils/formUtil.ts'
import {
  ElMessage,
  type FormInstance,
  type FormRules,
} from 'element-plus'
import type { InternalRuleItem } from 'async-validator/dist-types/interface'

const emits = defineEmits([ 'editSucc' ])
const showDialog = ref(false)
const submiting = ref(false)
const status = ref<'add' | 'view' | 'modify'>('add')

const endpointFormIns = useTemplateRef<FormInstance>('endpointForm')

const formData = ref<EndpointTypes.SearchEndpointResult>({})
const rules = reactive<FormRules<EndpointTypes.SearchEndpointResult>>({
  requestMethod: [ {required: true, message: '请选择请求方式', trigger: 'blur'} ],
  routingPath: [ {
    validator(_: InternalRuleItem, value: string, callback: (error?: string | Error) => void) {
      if (!Strings.isEmpty(value)) {
        if (!value.startsWith('/')) {
          callback('必须以“/”开头')
          return
        }
      }
      callback()
    }, message: '请填写路由前缀', trigger: 'blur',
  } ],
  endpointPath: [ {
    required: true, validator(_: InternalRuleItem, value: string, callback: (error?: string | Error) => void) {
      if (Strings.isBlank(value)) {
        callback(new Error('请填写端点地址'))
        return
      }
      if (!Strings.isEmpty(value)) {
        if (!value.startsWith('/')) {
          callback(new Error('必须以“/”开头'))
          return
        }
      }
      callback()
    }, trigger: 'blur',
  } ],
  accessModel: [ {required: true, message: '请选择访问模式', trigger: 'blur'} ],
})

function dialogCloseHandler() {
  formData.value = {}
}

function submitHandler() {
  if (status.value === 'view') return
  submiting.value = true
  if (formData.value.id != null) {
    FormUtil.submit(endpointFormIns, () => EndpointApi.modify(formData.value))
      .then(() => {
        ElMessage.success('修改成功')
        emits('editSucc')
        showDialog.value = false
      })
      .finally(() => {
        submiting.value = false
      })
  } else {
    FormUtil.submit(endpointFormIns, () => EndpointApi.add(formData.value))
      .then(() => {
        ElMessage.success('添加成功')
        emits('editSucc')
        showDialog.value = false
      })
      .finally(() => {
        submiting.value = false
      })
  }
}

defineExpose({
  open(data: EndpointTypes.SearchEndpointResult = {}) {
    showDialog.value = true
    if (!Strings.isBlank(data.id)) {
      status.value = 'modify'
      EndpointApi.detail(data.id!)
        .then(res => {
          formData.value = res.data
        })
    } else {
      status.value = 'add'
      formData.value = data
    }
  },
})
</script>

<style lang="stylus" scoped>
.form-panel {
  padding 20px
}
</style>
