<template>
  <el-card class="merchant-card" shadow="hover">
    <template #header>
      <div class="merchant-header">
        <span class="merchant-title">
          <el-tag :type="merchant.is_enabled === '1' ? 'success' : 'info'" size="small">
            {{ merchant.is_enabled === '1' ? '已启用' : '已禁用' }}
          </el-tag>
          <el-tag :type="isV3 ? 'warning' : 'primary'" size="small">
            {{ isV3 ? 'V3' : 'V2' }}
          </el-tag>
          {{ merchant.name || '新商户' }}
        </span>
        <el-button
          type="danger"
          link
          :disabled="!canDelete"
          @click="handleDelete"
        >
          <el-icon><Delete /></el-icon>删除
        </el-button>
      </div>
    </template>

    <el-form
      ref="formRef"
      :model="merchant"
      :rules="formRules"
      label-width="120px"
      class="merchant-form"
    >
      <!-- 基础信息 -->
      <el-divider content-position="left">基础信息</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="商户名称" prop="name">
            <el-input
              v-model="merchant.name"
              placeholder="请输入商户名称"
              maxlength="50"
              @input="handleChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商户号" prop="mch_id">
            <el-input
              v-model="merchant.mch_id"
              placeholder="请输入商户号(MCHID)"
              maxlength="32"
              @input="handleChange"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="订单前缀" prop="order_prefix">
            <el-input
              v-model="merchant.order_prefix"
              placeholder="请输入3位订单前缀"
              maxlength="3"
              @input="handleChange"
            />
            <div class="form-tip">必须为3位字符，用于区分不同商户的订单</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="启用状态" prop="is_enabled">
            <el-switch
              v-model="merchant.is_enabled"
              active-value="1"
              inactive-value="0"
              active-text="启用"
              inactive-text="禁用"
              @change="handleChange"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="支付版本" prop="pay_version">
            <el-select
              v-model="merchant.pay_version"
              placeholder="请选择支付版本"
              style="width: 100%"
              @change="handleVersionChange"
            >
              <el-option
                v-for="(label, value) in PayVersionLabels"
                :key="value"
                :label="label"
                :value="value"
              />
            </el-select>
            <div class="form-tip">V3版本使用更安全的RSA-SHA256签名和AES-GCM加密</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="回调地址" prop="notify_url">
            <el-input
              v-model="merchant.notify_url"
              placeholder="例如: https://api.example.com/api/notify/order_notify"
              @input="handleChange"
            />
            <div class="form-tip">支付成功后微信回调通知的地址，留空使用默认值</div>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- V2 配置项 -->
      <template v-if="!isV3">
        <el-divider content-position="left">V2 配置</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="API密钥" prop="api_key">
              <el-input
                v-model="merchant.api_key"
                type="password"
                placeholder="请输入API密钥(Key)"
                show-password
                @input="handleChange"
              />
              <div class="form-tip">V2版本的32位API密钥，用于MD5签名</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="证书路径" prop="cert_path">
              <el-input
                v-model="merchant.cert_path"
                placeholder="请输入证书路径（可选）"
                @input="handleChange"
              />
              <div class="form-tip">微信支付证书文件路径，用于退款等操作</div>
            </el-form-item>
          </el-col>
        </el-row>
      </template>

      <!-- V3 配置项 -->
      <template v-if="isV3">
        <el-divider content-position="left">V3 配置</el-divider>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="APIv3密钥" prop="api_v3_key">
              <el-input
                v-model="merchant.api_v3_key"
                type="password"
                placeholder="请输入APIv3密钥（32位）"
                show-password
                maxlength="32"
                @input="handleChange"
              />
              <div class="form-tip">V3版本的32位API密钥，用于AES-GCM解密回调通知</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="证书序列号" prop="cert_serial_no">
              <el-input
                v-model="merchant.cert_serial_no"
                placeholder="请输入商户API证书序列号"
                @input="handleChange"
              />
              <div class="form-tip">商户API证书的序列号，可在证书详情中查看</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="商户私钥路径" prop="private_key_path">
              <el-input
                v-model="merchant.private_key_path"
                placeholder="例如: certs/1738725801/apiclient_key.pem"
                @input="handleChange"
              />
              <div class="form-tip">商户API私钥文件路径，用于请求签名</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="微信公钥ID" prop="wechat_public_key_id">
              <el-input
                v-model="merchant.wechat_public_key_id"
                placeholder="请输入微信支付公钥ID"
                @input="handleChange"
              />
              <div class="form-tip">微信支付平台公钥ID</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信公钥路径" prop="wechat_public_key_path">
              <el-input
                v-model="merchant.wechat_public_key_path"
                placeholder="例如: certs/1738725801/pub_key.pem"
                @input="handleChange"
              />
              <div class="form-tip">微信支付平台公钥文件路径</div>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
    </el-form>
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { type WeixinPayMerchant, PayVersion, PayVersionLabels } from '@/api/business/config'

// Props
const props = defineProps<{
  /** 商户数据 */
  modelValue: WeixinPayMerchant
  /** 当前索引 */
  index: number
  /** 是否可以删除 */
  canDelete: boolean
  /** 已存在的前缀列表（用于唯一性验证） */
  existingPrefixes: string[]
}>()

// Emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: WeixinPayMerchant): void
  (e: 'delete', index: number): void
  (e: 'change'): void
}>()

// 表单引用
const formRef = ref<FormInstance>()

// 商户数据（双向绑定）
const merchant = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 是否为V3版本
const isV3 = computed(() => merchant.value.pay_version === PayVersion.V3)

// 订单前缀唯一性验证
const validateOrderPrefix = (_rule: unknown, value: string, callback: (error?: Error) => void) => {
  if (!value) {
    callback(new Error('请输入订单前缀'))
    return
  }
  if (value.length !== 3) {
    callback(new Error('订单前缀必须为3位字符'))
    return
  }
  // 检查唯一性（排除当前商户）
  const otherPrefixes = props.existingPrefixes.filter((_, i) => i !== props.index)
  if (otherPrefixes.includes(value)) {
    callback(new Error('订单前缀已被其他商户使用'))
    return
  }
  callback()
}

// V3必填字段验证
const validateV3Required = (fieldName: string) => {
  return (_rule: unknown, value: string, callback: (error?: Error) => void) => {
    if (isV3.value && !value) {
      callback(new Error(`V3版本必须填写${fieldName}`))
      return
    }
    callback()
  }
}

// 表单验证规则
const formRules = computed<FormRules>(() => ({
  name: [
    { required: true, message: '请输入商户名称', trigger: 'blur' },
    { max: 50, message: '商户名称不能超过50个字符', trigger: 'blur' }
  ],
  mch_id: [
    { required: true, message: '请输入商户号', trigger: 'blur' },
    { max: 32, message: '商户号不能超过32个字符', trigger: 'blur' }
  ],
  order_prefix: [
    { required: true, message: '请输入订单前缀', trigger: 'blur' },
    { validator: validateOrderPrefix, trigger: 'blur' }
  ],
  pay_version: [
    { required: true, message: '请选择支付版本', trigger: 'change' }
  ],
  // V2 字段验证
  api_key: [
    { 
      validator: (_rule: unknown, value: string, callback: (error?: Error) => void) => {
        if (!isV3.value && !value) {
          callback(new Error('V2版本必须填写API密钥'))
          return
        }
        callback()
      }, 
      trigger: 'blur' 
    }
  ],
  // V3 字段验证
  api_v3_key: [
    { validator: validateV3Required('APIv3密钥'), trigger: 'blur' },
    { 
      validator: (_rule: unknown, value: string, callback: (error?: Error) => void) => {
        if (isV3.value && value && value.length !== 32) {
          callback(new Error('APIv3密钥必须为32位字符'))
          return
        }
        callback()
      }, 
      trigger: 'blur' 
    }
  ],
  cert_serial_no: [
    { validator: validateV3Required('证书序列号'), trigger: 'blur' }
  ],
  private_key_path: [
    { validator: validateV3Required('商户私钥路径'), trigger: 'blur' }
  ]
}))

// 处理版本变化
const handleVersionChange = () => {
  // 清除表单验证状态
  formRef.value?.clearValidate()
  handleChange()
}

// 处理数据变化
const handleChange = () => {
  emit('change')
}

// 处理删除
const handleDelete = () => {
  emit('delete', props.index)
}

// 验证表单
const validate = async (): Promise<boolean> => {
  if (!formRef.value) return false
  try {
    await formRef.value.validate()
    return true
  } catch {
    return false
  }
}

// 暴露方法
defineExpose({
  validate
})
</script>

<style scoped>
.merchant-card {
  margin-bottom: 16px;
}

.merchant-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.merchant-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.merchant-form {
  padding-top: 8px;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 4px;
}
</style>
