<template>
  <el-card class="miniprogram-card" shadow="hover">
    <template #header>
      <div class="miniprogram-header">
        <span class="miniprogram-title">
          <el-tag :type="miniprogram.is_default === 1 ? 'success' : 'info'" size="small">
            {{ miniprogram.is_default === 1 ? '默认' : '非默认' }}
          </el-tag>
          {{ miniprogram.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="miniprogram"
      :rules="formRules"
      label-width="100px"
      class="miniprogram-form"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="小程序名称" prop="name">
            <el-input
              v-model="miniprogram.name"
              placeholder="请输入小程序名称"
              maxlength="50"
              @input="handleChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="AppId" prop="appid">
            <el-input
              v-model="miniprogram.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="miniprogram.appsecret"
              type="password"
              placeholder="请输入小程序AppSecret"
              show-password
              @input="handleChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="订单前缀" prop="order_prefix">
            <el-input
              v-model="miniprogram.order_prefix"
              placeholder="请输入2位订单前缀"
              maxlength="2"
              @input="handleChange"
            />
            <div class="form-tip">必须为2位字符，用于区分不同小程序的订单</div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="是否默认" prop="is_default">
            <el-radio-group v-model="miniprogram.is_default" @change="handleDefaultChange">
              <el-radio :value="1">是</el-radio>
              <el-radio :value="0">否</el-radio>
            </el-radio-group>
            <div class="form-tip">默认小程序用于未匹配域名时的兜底</div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联商户" prop="merchants">
            <el-select
              v-model="miniprogram.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">选择该小程序可使用的微信支付商户</div>
          </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 { MiniprogramConfig, WeixinPayMerchant } from '@/api/business/config'

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

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

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

// 小程序数据（双向绑定）
const miniprogram = 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
  }
  // 检查唯一性（排除当前小程序）
  const otherPrefixes = props.existingPrefixes.filter((_, i) => i !== props.index)
  if (otherPrefixes.includes(value)) {
    callback(new Error('订单前缀已被其他小程序使用'))
    return
  }
  callback()
}

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入小程序名称', trigger: 'blur' },
    { max: 50, message: '小程序名称不能超过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 (miniprogram.value.is_default === 1) {
    emit('defaultChange', props.index)
  }
  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>
.miniprogram-card {
  margin-bottom: 16px;
}

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

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

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

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