<template>
  <el-card class="h5app-card" shadow="hover">
    <template #header>
      <div class="h5app-header">
        <span class="h5app-title">
          <el-tag :type="h5app.is_default === 1 ? 'success' : 'info'" size="small">
            {{ h5app.is_default === 1 ? '默认' : '非默认' }}
          </el-tag>
          {{ h5app.name || '新H5应用' }}
        </span>
        <el-button
          type="danger"
          link
          :disabled="!canDelete"
          @click="handleDelete"
        >
          <el-icon><Delete /></el-icon>删除
        </el-button>
      </div>
    </template>

    <el-form
      ref="formRef"
      :model="h5app"
      :rules="formRules"
      label-width="100px"
      class="h5app-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="H5名称" prop="name">
            <el-input
              v-model="h5app.name"
              placeholder="请输入H5应用名称"
              maxlength="50"
              @input="handleChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="AppId" prop="appid">
            <el-input
              v-model="h5app.appid"
              placeholder="请输入AppId"
              maxlength="50"
              @input="handleChange"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="AppSecret" prop="appsecret">
            <el-input
              v-model="h5app.appsecret"
              type="password"
              placeholder="请输入AppSecret"
              show-password
              @input="handleChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="域名" prop="domain">
            <el-input
              v-model="h5app.domain"
              placeholder="请输入域名，多个用逗号分隔"
              @input="handleChange"
            />
            <div class="form-tip">用于自动匹配H5应用，多个域名用逗号分隔</div>
          </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="h5app.order_prefix"
              placeholder="请输入2位订单前缀"
              maxlength="2"
              @input="handleChange"
            />
            <div class="form-tip">必须为2位字符，用于区分不同H5应用的订单</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否默认" prop="is_default">
            <el-radio-group v-model="h5app.is_default" @change="handleDefaultChange">
              <el-radio :value="1">是</el-radio>
              <el-radio :value="0">否</el-radio>
            </el-radio-group>
            <div class="form-tip">默认H5应用用于未匹配域名时的兜底</div>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 支付方式选项卡 -->
      <el-form-item label="支付方式" prop="pay_type">
        <el-tabs v-model="h5app.pay_type" type="card" @tab-change="handlePayTypeChange">
          <el-tab-pane label="微信支付" name="wechat">
            <div class="merchant-select-area">
              <el-form-item label="关联商户" label-width="80px">
                <el-select
                  v-model="h5app.wx_merchants"
                  multiple
                  placeholder="请选择关联的微信支付商户"
                  style="width: 100%"
                  @change="handleChange"
                >
                  <el-option
                    v-for="(merchant, idx) in weixinMerchants"
                    :key="idx"
                    :label="merchant.name || `商户${idx + 1}`"
                    :value="merchant.mch_id"
                  />
                </el-select>
                <div class="form-tip">选择该H5应用可使用的微信支付商户</div>
              </el-form-item>
            </div>
          </el-tab-pane>
          <el-tab-pane label="支付宝支付" name="alipay">
            <div class="merchant-select-area">
              <el-form-item label="关联商户" label-width="80px">
                <el-select
                  v-model="h5app.ali_merchant_index"
                  placeholder="请选择关联的支付宝商户"
                  style="width: 100%"
                  @change="handleChange"
                >
                  <el-option
                    :label="'不关联'"
                    :value="-1"
                  />
                  <el-option
                    v-for="(merchant, idx) in alipayMerchants"
                    :key="idx"
                    :label="merchant.name || `商户${idx + 1}`"
                    :value="idx"
                  />
                </el-select>
                <div class="form-tip">选择该H5应用使用的支付宝商户</div>
              </el-form-item>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form-item>
    </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 { H5AppConfig, WeixinPayMerchant, AlipayMerchant } from '@/api/business/config'

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

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

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

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

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

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入H5应用名称', trigger: 'blur' },
    { max: 50, message: 'H5应用名称不能超过50个字符', trigger: 'blur' }
  ],
  appid: [
    { required: true, message: '请输入AppId', trigger: 'blur' },
    { max: 50, message: 'AppId不能超过50个字符', trigger: 'blur' }
  ],
  appsecret: [
    { required: true, message: '请输入AppSecret', trigger: 'blur' }
  ],
  order_prefix: [
    { required: true, message: '请输入订单前缀', trigger: 'blur' },
    { validator: validateOrderPrefix, trigger: 'blur' }
  ]
}

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

// 处理默认状态变化
const handleDefaultChange = () => {
  if (h5app.value.is_default === 1) {
    emit('defaultChange', props.index)
  }
  emit('change')
}

// 处理支付方式切换
const handlePayTypeChange = () => {
  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>
.h5app-card {
  margin-bottom: 16px;
}

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

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

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

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

.merchant-select-area {
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

:deep(.el-tabs__content) {
  padding: 0;
}
</style>
