<!-- eslint-disable unicorn/prefer-ternary -->
<script setup lang="ts">
import { platformService } from '#/api/service/auth/platform'
import { mj_form_input } from '#/components/mj/mj-table'
import hud from '#/utils/hud'
import obj from '#/utils/obj'

defineOptions({ name: 'ApiCfg' })
const props = withDefaults(
  defineProps<{
    modelValue?: boolean
    platform: any
  }>(),
  {
    modelValue: false,
  },
)
const emits = defineEmits(['update:modelValue', 'success'])
const show = computed({
  get() {
    return props.modelValue
  },
  async set(newVal) {
    emits('update:modelValue', newVal)
    if (newVal) {
      formRef.value?.setData(obj.toJSON(props.platform.apiCfg) || {})
    } else {
      formRef.value?.setData({})
    }
  },
})

const formRef = ref()

const title = computed(() => {
  return `【${props.platform?.name}】API配置`
})

const form = {
  titleWidth: 110,
  items: [
    {
      span: 24,
      field: 'validVipUrl',
      title: '验证是否VIP',
      itemRender: {
        name: mj_form_input,
      },
    },
  ],
} as any

const submit = () => {
  hud.load({
    task: async () => {
      await platformService.saveOrUpdate({
        id: props.platform.id,
        apiCfg: obj.toJSONString(formRef.value?.getData()),
      })
      emits('success')
      emits('update:modelValue', false)
    },
    option: '保存',
    hideSuccess: false,
  })
}
</script>

<template>
  <mj-modal
    v-model="show"
    :options="{
      title,
      width: 600,
    }"
  >
    <mj-form ref="formRef" :options="form" @submit="submit" />
  </mj-modal>
</template>

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