<!-- 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: 'WxPayCfg' })
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.wxPayCfg) || {})
    } else {
      formRef.value?.setData({})
    }
  },
})

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

const formRef = ref()
const form = {
  titleWidth: 120,
  items: [
    {
      required: true,
      span: 24,
      field: 'notifyUrl',
      title: '回调地址',
      itemRender: {
        name: mj_form_input,
      },
    },
    {
      required: true,
      span: 24,
      field: 'merchantId',
      title: '商户ID',
      itemRender: {
        name: mj_form_input,
      },
    },
    {
      required: true,
      span: 24,
      field: 'merchantSn',
      title: '商户SN',
      itemRender: {
        name: mj_form_input,
      },
    },
    {
      required: true,
      span: 24,
      field: 'apiV3Key',
      title: 'APIv3密钥',
      itemRender: {
        name: mj_form_input,
        props: {
          type: 'password',
        },
      },
    },
    {
      required: true,
      span: 24,
      field: 'privateKey',
      title: '私钥',
      itemRender: {
        name: mj_form_input,
        props: {
          type: 'password',
        },
      },
    },
    {
      span: 24,
      field: 'publicKeyId',
      title: '公钥ID',
      itemRender: {
        name: mj_form_input,
      },
    },
    {
      span: 24,
      field: 'publicKey',
      title: '公钥',
      itemRender: {
        name: mj_form_input,
      },
    },
  ],
} as any

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

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

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