<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>
          {{ 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="100px"
      class="merchant-form"
    >
      <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="应用ID" prop="appId">
            <el-input
              v-model="merchant.appId"
              placeholder="请输入支付宝应用ID(AppId)"
              maxlength="32"
              @input="handleChange"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="权重" prop="weight">
            <el-input-number
              v-model="merchant.weight"
              :min="1"
              :max="100"
              placeholder="请输入权重"
              @change="handleChange"
            />
            <div class="form-tip">权重越高，支付时被选中的概率越大</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="24">
          <el-form-item label="应用私钥" prop="privateKey">
            <el-input
              v-model="merchant.privateKey"
              type="textarea"
              :rows="4"
              placeholder="请输入应用私钥（RSA2私钥）"
              @input="handleChange"
            />
            <div class="form-tip">用于签名请求，请妥善保管</div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="支付宝公钥" prop="publicKey">
            <el-input
              v-model="merchant.publicKey"
              type="textarea"
              :rows="4"
              placeholder="请输入支付宝公钥"
              @input="handleChange"
            />
            <div class="form-tip">用于验证支付宝返回的签名</div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="merchant.remark"
              type="textarea"
              :rows="2"
              placeholder="请输入备注信息（可选）"
              maxlength="200"
              show-word-limit
              @input="handleChange"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </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 { AlipayMerchant } from '@/api/business/config'

// Props
const props = defineProps<{
  /** 商户数据 */
  modelValue: AlipayMerchant
  /** 当前索引 */
  index: number
  /** 是否可以删除 */
  canDelete: boolean
}>()

// Emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: AlipayMerchant): 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)
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入商户名称', trigger: 'blur' },
    { max: 50, message: '商户名称不能超过50个字符', trigger: 'blur' }
  ],
  appId: [
    { required: true, message: '请输入应用ID', trigger: 'blur' },
    { max: 32, message: '应用ID不能超过32个字符', trigger: 'blur' }
  ],
  privateKey: [
    { required: true, message: '请输入应用私钥', trigger: 'blur' }
  ],
  publicKey: [
    { required: true, message: '请输入支付宝公钥', trigger: 'blur' }
  ],
  weight: [
    { required: true, message: '请输入权重', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '权重必须在1-100之间', trigger: 'blur' }
  ]
}

// 处理数据变化
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>
