<template>
  <VbenDrawer
    v-model="visible"
    title="支付配置"
    :width="600"
    @cancel="handleCancel"
  >
    <VbenForm
      :schema="formSchema"
      :model="formModel"
      :rules="formRules"
      label-width="120px"
      @submit="handleSubmit"
    >
      <template #form-footer>
        <VbenSpace>
          <VbenButton @click="handleCancel">取消</VbenButton>
          <VbenButton type="primary" native-type="submit">确定</VbenButton>
        </VbenSpace>
      </template>
    </VbenForm>
  </VbenDrawer>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { VbenButton, VbenDrawer, VbenForm, VbenMessage, VbenSpace } from '@vben/common-ui';

import { updatePaymentConfig } from '#/api/core/payment';

import type { PaymentItem } from '../data';

interface Props {
  modelValue: boolean;
  data?: PaymentItem | null;
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void;
  (e: 'reload'): void;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  data: null,
});

const emit = defineEmits<Emits>();

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val),
});

const formModel = ref<Record<string, any>>({});

const formSchema = computed(() => {
  if (!props.data) return [];
  
  const baseSchema = [
    {
      fieldName: 'payment_name',
      label: '支付名称',
      component: 'Input',
      componentProps: {
        placeholder: '支付名称',
        disabled: true,
      },
    },
    {
      fieldName: 'payment_type',
      label: '支付类型',
      component: 'Input',
      componentProps: {
        placeholder: '支付类型',
        disabled: true,
      },
    },
  ];
  
  // 根据支付类型生成不同的配置字段
  const configSchema = getPaymentConfigSchema(props.data.payment_type);
  
  return [...baseSchema, ...configSchema];
});

const formRules = computed(() => {
  const rules: Record<string, any> = {};
  
  formSchema.value.forEach(field => {
    if (field.fieldName && field.fieldName !== 'payment_name' && field.fieldName !== 'payment_type') {
      rules[field.fieldName] = field.rules || 'required';
    }
  });
  
  return rules;
});

function getPaymentConfigSchema(paymentType: string) {
  const configSchemas: Record<string, any[]> = {
    wechat: [
      {
        fieldName: 'app_id',
        label: '应用ID',
        component: 'Input',
        componentProps: {
          placeholder: '请输入微信支付应用ID',
        },
      },
      {
        fieldName: 'mch_id',
        label: '商户号',
        component: 'Input',
        componentProps: {
          placeholder: '请输入微信支付商户号',
        },
      },
      {
        fieldName: 'api_key',
        label: 'API密钥',
        component: 'Input',
        componentProps: {
          placeholder: '请输入微信支付API密钥',
          type: 'password',
        },
      },
      {
        fieldName: 'cert_path',
        label: '证书路径',
        component: 'Input',
        componentProps: {
          placeholder: '请输入微信支付证书路径',
        },
      },
      {
        fieldName: 'key_path',
        label: '密钥路径',
        component: 'Input',
        componentProps: {
          placeholder: '请输入微信支付密钥路径',
        },
      },
    ],
    alipay: [
      {
        fieldName: 'app_id',
        label: '应用ID',
        component: 'Input',
        componentProps: {
          placeholder: '请输入支付宝应用ID',
        },
      },
      {
        fieldName: 'public_key',
        label: '公钥',
        component: 'Textarea',
        componentProps: {
          placeholder: '请输入支付宝公钥',
          rows: 4,
        },
      },
      {
        fieldName: 'private_key',
        label: '私钥',
        component: 'Textarea',
        componentProps: {
          placeholder: '请输入支付宝私钥',
          rows: 4,
        },
      },
    ],
    unionpay: [
      {
        fieldName: 'mer_id',
        label: '商户号',
        component: 'Input',
        componentProps: {
          placeholder: '请输入银联商户号',
        },
      },
      {
        fieldName: 'cert_path',
        label: '证书路径',
        component: 'Input',
        componentProps: {
          placeholder: '请输入银联证书路径',
        },
      },
      {
        fieldName: 'cert_pwd',
        label: '证书密码',
        component: 'Input',
        componentProps: {
          placeholder: '请输入银联证书密码',
          type: 'password',
        },
      },
    ],
    paypal: [
      {
        fieldName: 'client_id',
        label: '客户端ID',
        component: 'Input',
        componentProps: {
          placeholder: '请输入PayPal客户端ID',
        },
      },
      {
        fieldName: 'client_secret',
        label: '客户端密钥',
        component: 'Input',
        componentProps: {
          placeholder: '请输入PayPal客户端密钥',
          type: 'password',
        },
      },
      {
        fieldName: 'sandbox',
        label: '沙箱模式',
        component: 'Switch',
        componentProps: {
          checkedChildren: '是',
          unCheckedChildren: '否',
        },
      },
    ],
  };
  
  return configSchemas[paymentType] || [];
}

watch(
  () => props.data,
  (val) => {
    if (val) {
      formModel.value = {
        payment_name: val.payment_name,
        payment_type: val.payment_type,
        ...val.config,
      };
    } else {
      formModel.value = {};
    }
  },
  { immediate: true }
);

async function handleSubmit() {
  if (!props.data) return;
  
  try {
    const configData = { ...formModel.value };
    delete configData.payment_name;
    delete configData.payment_type;
    
    await updatePaymentConfig(props.data.id, configData);
    VbenMessage.success('配置更新成功');
    handleCancel();
    emit('reload');
  } catch (error) {
    VbenMessage.error('配置更新失败');
  }
}

function handleCancel() {
  visible.value = false;
}
</script>