<template>
  <div class="p-4">
    <VbenTabs v-model:active-key="activeTab" type="card">
      <!-- 支付宝设置 -->
      <VbenTabPane key="alipay" tab="支付宝">
        <VbenForm
          ref="alipayFormRef"
          :schema="alipayFormSchema"
          :form-options="{
            layout: 'vertical',
            labelCol: { span: 24 },
            wrapperCol: { span: 24 },
          }"
          @submit="handleSaveAlipay"
        >
          <template #submitButton>
            <div class="flex gap-2">
              <VbenButton type="primary" :loading="saveLoading" @click="handleSaveAlipay">
                保存配置
              </VbenButton>
              <VbenButton @click="handleTestAlipay">
                测试支付
              </VbenButton>
            </div>
          </template>
        </VbenForm>
      </VbenTabPane>

      <!-- 微信支付设置 -->
      <VbenTabPane key="wechat" tab="微信支付">
        <VbenForm
          ref="wechatFormRef"
          :schema="wechatFormSchema"
          :form-options="{
            layout: 'vertical',
            labelCol: { span: 24 },
            wrapperCol: { span: 24 },
          }"
          @submit="handleSaveWechat"
        >
          <template #submitButton>
            <div class="flex gap-2">
              <VbenButton type="primary" :loading="saveLoading" @click="handleSaveWechat">
                保存配置
              </VbenButton>
              <VbenButton @click="handleTestWechat">
                测试支付
              </VbenButton>
            </div>
          </template>
        </VbenForm>
      </VbenTabPane>

      <!-- 通用设置 -->
      <VbenTabPane key="general" tab="通用设置">
        <VbenForm
          ref="generalFormRef"
          :schema="generalFormSchema"
          :form-options="{
            layout: 'vertical',
            labelCol: { span: 24 },
            wrapperCol: { span: 24 },
          }"
          @submit="handleSaveGeneral"
        >
          <template #submitButton>
            <div class="flex gap-2">
              <VbenButton type="primary" :loading="saveLoading" @click="handleSaveGeneral">
                保存配置
              </VbenButton>
            </div>
          </template>
        </VbenForm>
      </VbenTabPane>
    </VbenTabs>

    <!-- 测试支付对话框 -->
    <VbenModal
      v-model:open="testDialogVisible"
      title="测试支付"
      width="500px"
      @ok="handleCreateTestOrder"
    >
      <VbenForm
        ref="testFormRef"
        :schema="testFormSchema"
        :form-options="{
          layout: 'vertical',
          labelCol: { span: 24 },
          wrapperCol: { span: 24 },
        }"
      />
    </VbenModal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { VbenForm, VbenButton, VbenModal, VbenTabs, VbenTabPane } from '@vben/components'
import { message } from 'ant-design-vue'
import type { FormSchema } from '@vben/types'
import {
  getPaymentConfigApi,
  updatePaymentConfigApi,
  testPaymentApi,
  resetPaymentConfigApi,
  type PaymentConfig,
} from '@/api/common/payment'

const alipayFormRef = ref()
const wechatFormRef = ref()
const generalFormRef = ref()
const testFormRef = ref()
const saveLoading = ref(false)
const testDialogVisible = ref(false)
const activeTab = ref('alipay')

// 支付宝表单配置
const alipayFormSchema: FormSchema[] = [
  {
    field: 'alipay_app_id',
    label: '应用ID',
    component: 'Input',
    required: true,
    colProps: { span: 12 },
  },
  {
    field: 'alipay_gateway_url',
    label: '网关地址',
    component: 'Select',
    required: true,
    colProps: { span: 12 },
    componentProps: {
      options: [
        { label: '正式环境', value: 'https://openapi.alipay.com/gateway.do' },
        { label: '沙箱环境', value: 'https://openapi.alipaydev.com/gateway.do' },
      ],
    },
    defaultValue: 'https://openapi.alipaydev.com/gateway.do',
  },
  {
    field: 'alipay_private_key',
    label: '应用私钥',
    component: 'InputTextArea',
    required: true,
    componentProps: {
      rows: 4,
      placeholder: '请输入应用私钥（PKCS8格式）',
    },
  },
  {
    field: 'alipay_public_key',
    label: '支付宝公钥',
    component: 'InputTextArea',
    required: true,
    componentProps: {
      rows: 4,
      placeholder: '请输入支付宝公钥',
    },
  },
  {
    field: 'alipay_sign_type',
    label: '签名方式',
    component: 'Select',
    required: true,
    colProps: { span: 12 },
    componentProps: {
      options: [
        { label: 'RSA2', value: 'RSA2' },
        { label: 'RSA', value: 'RSA' },
      ],
    },
    defaultValue: 'RSA2',
  },
  {
    field: 'alipay_charset',
    label: '字符集',
    component: 'Select',
    required: true,
    colProps: { span: 12 },
    componentProps: {
      options: [
        { label: 'UTF-8', value: 'utf-8' },
        { label: 'GBK', value: 'gbk' },
      ],
    },
    defaultValue: 'utf-8',
  },
  {
    field: 'alipay_notify_url',
    label: '异步通知地址',
    component: 'Input',
    colProps: { span: 12 },
    helpMessage: '支付结果异步通知地址',
  },
  {
    field: 'alipay_return_url',
    label: '同步返回地址',
    component: 'Input',
    colProps: { span: 12 },
    helpMessage: '支付完成后同步跳转地址',
  },
  {
    field: 'alipay_enabled',
    label: '启用状态',
    component: 'Switch',
    defaultValue: false,
  },
]

// 微信支付表单配置
const wechatFormSchema: FormSchema[] = [
  {
    field: 'wechat_app_id',
    label: '应用ID',
    component: 'Input',
    required: true,
    colProps: { span: 12 },
  },
  {
    field: 'wechat_mch_id',
    label: '商户号',
    component: 'Input',
    required: true,
    colProps: { span: 12 },
  },
  {
    field: 'wechat_key',
    label: '商户密钥',
    component: 'InputPassword',
    required: true,
    colProps: { span: 12 },
  },
  {
    field: 'wechat_secret',
    label: '应用密钥',
    component: 'InputPassword',
    required: true,
    colProps: { span: 12 },
  },
  {
    field: 'wechat_cert_path',
    label: '证书路径',
    component: 'Input',
    helpMessage: '微信支付证书文件路径',
  },
  {
    field: 'wechat_key_path',
    label: '私钥路径',
    component: 'Input',
    helpMessage: '微信支付私钥文件路径',
  },
  {
    field: 'wechat_notify_url',
    label: '异步通知地址',
    component: 'Input',
    colProps: { span: 12 },
    helpMessage: '支付结果异步通知地址',
  },
  {
    field: 'wechat_trade_type',
    label: '支付模式',
    component: 'Select',
    required: true,
    colProps: { span: 12 },
    componentProps: {
      options: [
        { label: 'JSAPI支付', value: 'JSAPI' },
        { label: 'Native支付', value: 'NATIVE' },
        { label: 'APP支付', value: 'APP' },
        { label: 'H5支付', value: 'MWEB' },
      ],
    },
    defaultValue: 'JSAPI',
  },
  {
    field: 'wechat_enabled',
    label: '启用状态',
    component: 'Switch',
    defaultValue: false,
  },
]

// 通用设置表单配置
const generalFormSchema: FormSchema[] = [
  {
    field: 'default_method',
    label: '默认支付方式',
    component: 'Select',
    required: true,
    componentProps: {
      options: [
        { label: '支付宝', value: 'alipay' },
        { label: '微信支付', value: 'wechat' },
        { label: '余额支付', value: 'balance' },
      ],
    },
    defaultValue: 'alipay',
  },
  {
    field: 'timeout',
    label: '支付超时时间（分钟）',
    component: 'InputNumber',
    required: true,
    componentProps: {
      min: 1,
      max: 1440,
    },
    defaultValue: 30,
  },
  {
    field: 'min_amount',
    label: '最小支付金额（元）',
    component: 'InputNumber',
    required: true,
    componentProps: {
      min: 0.01,
      precision: 2,
    },
    defaultValue: 0.01,
  },
  {
    field: 'max_amount',
    label: '最大支付金额（元）',
    component: 'InputNumber',
    required: true,
    componentProps: {
      min: 1,
      precision: 2,
    },
    defaultValue: 50000,
  },
  {
    field: 'success_url',
    label: '支付成功页面',
    component: 'Input',
    helpMessage: '支付成功后跳转的页面地址',
  },
  {
    field: 'fail_url',
    label: '支付失败页面',
    component: 'Input',
    helpMessage: '支付失败后跳转的页面地址',
  },
  {
    field: 'balance_enabled',
    label: '启用余额支付',
    component: 'Switch',
    defaultValue: true,
  },
  {
    field: 'points_enabled',
    label: '启用积分抵扣',
    component: 'Switch',
    defaultValue: false,
  },
  {
    field: 'points_ratio',
    label: '积分抵扣比例',
    component: 'InputNumber',
    show: ({ values }) => values.points_enabled,
    componentProps: {
      min: 1,
      max: 1000,
      addonAfter: '积分 = 1元',
    },
    defaultValue: 100,
    helpMessage: '多少积分等于1元',
  },
]

// 测试表单配置
const testFormSchema: FormSchema[] = [
  {
    field: 'amount',
    label: '支付金额',
    component: 'InputNumber',
    required: true,
    componentProps: {
      min: 0.01,
      precision: 2,
    },
    defaultValue: 0.01,
  },
  {
    field: 'subject',
    label: '商品名称',
    component: 'Input',
    required: true,
    defaultValue: '测试商品',
  },
  {
    field: 'body',
    label: '商品描述',
    component: 'Input',
    defaultValue: '这是一个测试订单',
  },
]

// 加载配置
const loadConfig = async () => {
  try {
    const data = await getPaymentConfigApi()
    alipayFormRef.value?.setFieldsValue(data.alipay || {})
    wechatFormRef.value?.setFieldsValue(data.wechat || {})
    generalFormRef.value?.setFieldsValue(data.general || {})
  } catch (error) {
    message.error('加载配置失败')
  }
}

// 保存支付宝配置
const handleSaveAlipay = async () => {
  try {
    const values = await alipayFormRef.value?.validate()
    if (!values) return

    saveLoading.value = true
    await updatePaymentConfigApi({ type: 'alipay', config: values })
    message.success('支付宝配置保存成功')
  } catch (error) {
    message.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

// 保存微信支付配置
const handleSaveWechat = async () => {
  try {
    const values = await wechatFormRef.value?.validate()
    if (!values) return

    saveLoading.value = true
    await updatePaymentConfigApi({ type: 'wechat', config: values })
    message.success('微信支付配置保存成功')
  } catch (error) {
    message.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

// 保存通用配置
const handleSaveGeneral = async () => {
  try {
    const values = await generalFormRef.value?.validate()
    if (!values) return

    saveLoading.value = true
    await updatePaymentConfigApi({ type: 'general', config: values })
    message.success('通用配置保存成功')
  } catch (error) {
    message.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

// 测试支付宝
const handleTestAlipay = () => {
  testFormRef.value?.setFieldsValue({
    amount: 0.01,
    subject: '支付宝测试商品',
    body: '这是一个支付宝测试订单',
  })
  testDialogVisible.value = true
}

// 测试微信支付
const handleTestWechat = () => {
  testFormRef.value?.setFieldsValue({
    amount: 0.01,
    subject: '微信支付测试商品',
    body: '这是一个微信支付测试订单',
  })
  testDialogVisible.value = true
}

// 创建测试订单
const handleCreateTestOrder = async () => {
  try {
    const values = await testFormRef.value?.validate()
    if (!values) return

    const testData = {
      method: activeTab.value,
      ...values,
    }

    const result = await testPaymentApi(testData)
    message.success('测试订单创建成功')

    // 打开支付页面或显示支付二维码
    if (result.payUrl) {
      window.open(result.payUrl, '_blank')
    }

    testDialogVisible.value = false
  } catch (error) {
    message.error('创建测试订单失败')
  }
}

onMounted(() => {
  loadConfig()
})
</script>

<style scoped>
.p-4 {
  padding: 16px;
}

.flex {
  display: flex;
}

.gap-2 {
  gap: 8px;
}
</style>