<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
    >
      <el-form-item :label="t('pay.paymentType')" prop="payType">
        <el-select v-model="formData.payType">
          <el-option :label="t('pay.alipay')" value="aliPay" />
          <el-option :label="t('pay.weChatPayment')" value="wxPay" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('pay.payId')" prop="detailsId">
        <el-select v-model="formData.detailsId">
          <!-- <el-option  :value="tenantId" /> -->
          <el-option :label="t('pay.weChatPaySmallProgram')" :value="'wx_miniapp'+tenantId" />
          <el-option :label="t('pay.weChatPayPublic')" :value="'wx_wechat'+tenantId" />
          <el-option :label="t('pay.weChatPayH5')" :value="'wx_h5'+tenantId" />
          <el-option :label="t('pay.alipayH5')" :value="'ali_h5'+tenantId" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item :label="t('pay.')支付id" prop="detailsId">
        <el-input v-model="formData.detailsId" placeholder="请输入支付id" />
      </el-form-item> -->
      <el-form-item :label="t('pay.applicationId')" prop="appid">
        <el-input v-model="formData.appid" :placeholder="t('pay.pleaseEnterTheAppId')" />
      </el-form-item>
      <el-form-item :label="t('pay.weChatMerchantId')" prop="mchId">
        <el-input v-model="formData.mchId" :placeholder="t('pay.pleaseEnterWeChatMerchantId')" />
      </el-form-item>
      <el-form-item :label="t('pay.alipayMerchantId')" prop="seller">
        <el-input v-model="formData.seller" :placeholder="t('pay.pleaseEnterTheAlipayMerchantId')" />
      </el-form-item>
      <el-form-item :label="t('pay.certificateStorageType')" prop="certStoreType">
        <el-select v-model="formData.certStoreType" :placeholder="t('pay.pleaseSelectTheType')" clearable>
          <el-option label="PATH" value="PATH" />
          <el-option label="STR" value="STR" />
          <el-option label="INPUT_STREAM" value="INPUT_STREAM" />
          <el-option label="CLASS_PATH" value="CLASS_PATH" />
          <el-option label="URL" value="URL" />
        </el-select>
        <div style="color: red;">{{t('pay.noteNeedCertificateOfChoiceDoNotNeedNotChoose')}}</div>
      </el-form-item>
      <el-form-item :label="t('pay.privateKeyOrPrivateKeyCertificate')" prop="keyPrivate">
        <el-input v-model="formData.keyPrivate" :placeholder="t('pay.pleaseEnterThePrivateKeyOrPrivateKeyCertificate')" />
      </el-form-item>
      <el-form-item :label="t('pay.publicKeyOrPublicKeyCertificate')" prop="keyPublic">
        <el-input v-model="formData.keyPublic" :placeholder="t('pay.pleaseEnterThePublicKeyOrPublicKeyCertificate')" />
      </el-form-item>
      <el-form-item :label="t('pay.keyCertificate')" prop="keyCert">
        <el-input v-model="formData.keyCert" :placeholder="t('pay.pleaseEnterTheKeyCertificateAdditionalCertificatesToUseSuchAsSslCertificateOrUnionPayRootLevelCertificates')" />
      </el-form-item>
      <el-form-item :label="t('pay.passwordOfTheCertificate')" prop="keyCertPwd">
        <el-input v-model="formData.keyCertPwd" :placeholder="t('pay.pleaseEnterThePasswordOfThePrivateKeyCertificateOrKeyCertificate')" />
      </el-form-item>
      <el-form-item :label="t('pay.asynchronousCallbackAddress')" prop="notifyUrl">
        <el-input v-model="formData.notifyUrl" :placeholder="t('pay.pleaseEnterTheAsynchronousCallback')" />
      </el-form-item>
      <el-form-item :label="t('pay.synchronousCallbackAddress')" prop="returnUrl">
        <el-input v-model="formData.returnUrl" :placeholder="t('pay.pleaseEnterTheSynchronousCallbackAddressWhichIsMostlyUsedForPageJumpAfterSuccessfulPayment')" />
      </el-form-item>
      <el-form-item :label="t('pay.signature')" prop="signType">
        <el-select v-model="formData.signType" :placeholder="t('pay.pleaseSelectSignatureMethodMd5')">
          <el-option label="RSA" value="RSA" />
          <el-option label="RSA2" value="RSA2" />
          <el-option label="MD5" value="MD5" />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('pay.subappid')" prop="subAppId">
        <el-input v-model="formData.subAppId" :placeholder="t('pay.pleaseEnterTheSubAppid')" />
      </el-form-item>
      <el-form-item :label="t('pay.subMerchantId')" prop="subMchId">
        <el-input v-model="formData.subMchId" :placeholder="t('pay.pleaseEnterTheSubMerchantId')" />
      </el-form-item>
      <el-form-item :label="t('pay.testEnvironment')" prop="isTest">
        <el-radio-group v-model="formData.isTest">
          <el-radio :label="1">{{t('common.yes')}}</el-radio>
          <el-radio :label="0">{{t('common.no')}}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{t('common.confirm')}}</el-button>
      <el-button @click="dialogVisible = false">{{t('common.cancel')}}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as MerchantDetailsApi from '@/api/pay/merchantDetails'
import { getTenantId } from '@/utils/auth'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const tenantId = ref(getTenantId())

console.log('tenantId:',tenantId.value)

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  detailsId: undefined,
  payType: undefined,
  appid: undefined,
  mchId: undefined,
  certStoreType: undefined,
  keyPrivate: undefined,
  keyPublic: undefined,
  keyCert: undefined,
  keyCertPwd: undefined,
  notifyUrl: undefined,
  returnUrl: undefined,
  signType: undefined,
  seller: undefined,
  subAppId: undefined,
  subMchId: undefined,
  inputCharset: undefined,
  isTest: undefined
})
const formRules = reactive({
  payType: [{ required: true, message: t('pay.paymentTypeCannotBeEmpty'), trigger: 'change' }],
  detailsId: [{ required: true, message: t('pay.paymentIdCannotBeEmpty'), trigger: 'change' }],
  appid: [{ required: true, message: t('pay.applicationIdCannotBeEmpty'), trigger: 'change' }],
  signType: [{ required: true, message: t('pay.signatureMethodCannotBeEmpty'), trigger: 'change' }],
  notifyUrl: [{ required: true, message: t('pay.asynchronousCallbackAddressCannotBeEmpty'), trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await MerchantDetailsApi.getMerchantDetails(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as MerchantDetailsApi.MerchantDetailsVO
    if (formType.value === 'create') {
      await MerchantDetailsApi.createMerchantDetails(data)
      message.success(t('common.createSuccess'))
    } else {
      await MerchantDetailsApi.updateMerchantDetails(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    detailsId: undefined,
    payType: undefined,
    appid: undefined,
    mchId: undefined,
    certStoreType: undefined,
    keyPrivate: undefined,
    keyPublic: undefined,
    keyCert: undefined,
    keyCertPwd: undefined,
    notifyUrl: undefined,
    returnUrl: undefined,
    signType: undefined,
    seller: undefined,
    subAppId: undefined,
    subMchId: undefined,
    inputCharset: undefined,
    isTest: 1
  }
  formRef.value?.resetFields()
}
</script>
