<template>
  <div class="page-container">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>微信支付配置</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddMerchant">
              <el-icon><Plus /></el-icon>添加商户
            </el-button>
            <el-button type="success" :loading="saving" @click="handleSave">
              <el-icon><Check /></el-icon>保存配置
            </el-button>
          </div>
        </div>
      </template>

      <!-- 商户列表为空提示 -->
      <el-empty
        v-if="merchants.length === 0"
        description="暂无商户配置，请点击添加商户"
      >
        <el-button type="primary" @click="handleAddMerchant">
          <el-icon><Plus /></el-icon>添加商户
        </el-button>
      </el-empty>

      <!-- 商户列表 -->
      <div v-else class="merchant-list">
        <WeixinMerchantForm
          v-for="(_merchant, index) in merchants"
          :key="index"
          ref="merchantFormRefs"
          v-model="merchants[index]"
          :index="index"
          :can-delete="merchants.length > 1"
          :existing-prefixes="existingPrefixes"
          @delete="handleDeleteMerchant"
          @change="handleMerchantChange"
        />
      </div>

      <!-- 底部操作栏 -->
      <div v-if="merchants.length > 0" class="footer-actions">
        <el-button type="primary" @click="handleAddMerchant">
          <el-icon><Plus /></el-icon>添加商户
        </el-button>
        <el-button type="success" :loading="saving" @click="handleSave">
          <el-icon><Check /></el-icon>保存配置
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Check } from '@element-plus/icons-vue'
import {
  getWeixinPaySetting,
  updateWeixinPaySetting,
  type WeixinPayMerchant,
  type WeixinPaySetting,
  PayVersion
} from '@/api/business/config'
import WeixinMerchantForm from './components/WeixinMerchantForm.vue'

// 加载状态
const loading = ref(false)
const saving = ref(false)

// 商户列表
const merchants = ref<WeixinPayMerchant[]>([])

// 商户表单引用
const merchantFormRefs = ref<InstanceType<typeof WeixinMerchantForm>[]>([])

// 计算已存在的前缀列表
const existingPrefixes = computed(() => {
  return merchants.value.map(m => m.order_prefix || '')
})

// 创建默认商户
const createDefaultMerchant = (): WeixinPayMerchant => ({
  name: '',
  mch_id: '',
  order_prefix: '',
  api_key: '',
  cert_path: '',
  is_enabled: '1',
  notify_url: '',
  // V3 字段默认值
  pay_version: PayVersion.V2,
  api_v3_key: '',
  cert_serial_no: '',
  private_key_path: '',
  wechat_public_key_id: '',
  wechat_public_key_path: ''
})

// 加载配置数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await getWeixinPaySetting()
    if (res.data?.value?.merchants && res.data.value.merchants.length > 0) {
      merchants.value = res.data.value.merchants.map(m => ({
        name: m.name || '',
        mch_id: m.mch_id || '',
        order_prefix: m.order_prefix || '',
        api_key: m.api_key || '',
        cert_path: m.cert_path || '',
        is_enabled: m.is_enabled || '1',
        notify_url: m.notify_url || '',
        // V3 字段回显
        pay_version: m.pay_version || PayVersion.V2,
        api_v3_key: m.api_v3_key || '',
        cert_serial_no: m.cert_serial_no || '',
        private_key_path: m.private_key_path || '',
        wechat_public_key_id: m.wechat_public_key_id || '',
        wechat_public_key_path: m.wechat_public_key_path || ''
      }))
    } else {
      // 如果没有配置，添加一个默认商户
      merchants.value = [createDefaultMerchant()]
    }
  } catch (error) {
    ElMessage.error('加载配置失败')
    console.error('加载配置失败:', error)
    // 加载失败时也添加一个默认商户
    merchants.value = [createDefaultMerchant()]
  } finally {
    loading.value = false
  }
}

// 添加商户
const handleAddMerchant = () => {
  merchants.value.push(createDefaultMerchant())
  ElMessage.success('已添加新商户，请填写配置信息')
}

// 删除商户
const handleDeleteMerchant = async (index: number) => {
  if (merchants.value.length <= 1) {
    ElMessage.warning('至少保留一个商户配置')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除商户"${merchants.value[index].name || '未命名'}"吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    merchants.value.splice(index, 1)
    ElMessage.success('已删除商户')
  } catch {
    // 用户取消删除
  }
}

// 商户数据变化
const handleMerchantChange = () => {
  // 可以在这里添加自动保存或其他逻辑
}

// 验证所有商户表单
const validateAllForms = async (): Promise<boolean> => {
  if (!merchantFormRefs.value || merchantFormRefs.value.length === 0) {
    return true
  }

  const results = await Promise.all(
    merchantFormRefs.value.map(form => form?.validate?.() ?? Promise.resolve(true))
  )

  return results.every(result => result === true)
}

// 保存配置
const handleSave = async () => {
  // 验证所有表单
  const isValid = await validateAllForms()
  if (!isValid) {
    ElMessage.warning('请检查表单填写是否正确')
    return
  }

  // 验证至少有一个商户
  if (merchants.value.length === 0) {
    ElMessage.warning('至少需要配置一个商户')
    return
  }

  // 验证前缀唯一性
  const prefixes = merchants.value.map(m => m.order_prefix)
  const uniquePrefixes = new Set(prefixes)
  if (prefixes.length !== uniquePrefixes.size) {
    ElMessage.warning('存在重复的订单前缀，请检查')
    return
  }

  // V3 版本额外验证
  for (const merchant of merchants.value) {
    if (merchant.pay_version === PayVersion.V3) {
      if (!merchant.api_v3_key || !merchant.cert_serial_no || !merchant.private_key_path) {
        ElMessage.warning(`商户"${merchant.name}"使用V3版本，请填写完整的V3配置`)
        return
      }
    }
  }

  saving.value = true
  try {
    const submitData: WeixinPaySetting = {
      merchants: merchants.value
    }

    await updateWeixinPaySetting(submitData)
    ElMessage.success('保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
    console.error('保存配置失败:', error)
  } finally {
    saving.value = false
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.page-container {
  padding: 0;
}

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

.header-actions {
  display: flex;
  gap: 12px;
}

.merchant-list {
  max-width: 1000px;
}

.footer-actions {
  display: flex;
  justify-content: center;
  gap: 12px;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;
}
</style>
