<template>
  <div class="page-container">
    <el-card v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>H5配置</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddH5App">
              <el-icon><Plus /></el-icon>添加H5应用
            </el-button>
            <el-button type="success" :loading="saving" @click="handleSave">
              <el-icon><Check /></el-icon>保存配置
            </el-button>
          </div>
        </div>
      </template>

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

      <!-- H5应用列表 -->
      <div v-else class="h5app-list">
        <H5AppForm
          v-for="(_h5app, index) in h5apps"
          :key="index"
          ref="h5appFormRefs"
          v-model="h5apps[index]"
          :index="index"
          :can-delete="h5apps.length > 1"
          :existing-prefixes="existingPrefixes"
          :weixin-merchants="weixinMerchants"
          :alipay-merchants="alipayMerchants"
          @delete="handleDeleteH5App"
          @change="handleH5AppChange"
          @default-change="handleDefaultChange"
        />
      </div>

      <!-- 底部操作栏 -->
      <div v-if="h5apps.length > 0" class="footer-actions">
        <el-button type="primary" @click="handleAddH5App">
          <el-icon><Plus /></el-icon>添加H5应用
        </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 {
  getH5Setting,
  updateH5Setting,
  getWeixinPaySetting,
  getAlipaySetting,
  type H5AppConfig,
  type H5Setting,
  type WeixinPayMerchant,
  type AlipayMerchant
} from '@/api/business/config'
import H5AppForm from './components/H5AppForm.vue'

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

// H5应用列表
const h5apps = ref<H5AppConfig[]>([])

// 微信支付商户列表（用于关联选择）
const weixinMerchants = ref<WeixinPayMerchant[]>([])

// 支付宝商户列表（用于关联选择）
const alipayMerchants = ref<AlipayMerchant[]>([])

// H5应用表单引用
const h5appFormRefs = ref<InstanceType<typeof H5AppForm>[]>([])

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

// 创建默认H5应用
const createDefaultH5App = (): H5AppConfig => ({
  name: '',
  appid: '',
  appsecret: '',
  domain: '',
  order_prefix: '',
  is_default: h5apps.value.length === 0 ? 1 : 0, // 第一个默认为默认H5应用
  pay_type: 'wechat',
  wx_merchants: [],
  ali_merchant_index: -1
})

// 加载微信支付商户列表
const loadWeixinMerchants = async () => {
  try {
    const res = await getWeixinPaySetting()
    if (res.data?.value?.merchants) {
      weixinMerchants.value = res.data.value.merchants
    }
  } catch (error) {
    console.error('加载微信支付商户列表失败:', error)
  }
}

// 加载支付宝商户列表
const loadAlipayMerchants = async () => {
  try {
    const res = await getAlipaySetting()
    if (res.data?.value?.merchants) {
      alipayMerchants.value = res.data.value.merchants
    }
  } catch (error) {
    console.error('加载支付宝商户列表失败:', error)
  }
}

// 加载配置数据
const loadData = async () => {
  loading.value = true
  try {
    // 并行加载H5配置和商户列表
    await Promise.all([
      loadH5Setting(),
      loadWeixinMerchants(),
      loadAlipayMerchants()
    ])
  } finally {
    loading.value = false
  }
}

// 加载H5配置
const loadH5Setting = async () => {
  try {
    const res = await getH5Setting()
    if (res.data?.value?.h5apps && res.data.value.h5apps.length > 0) {
      h5apps.value = res.data.value.h5apps.map(h => ({
        name: h.name || '',
        appid: h.appid || '',
        appsecret: h.appsecret || '',
        domain: h.domain || '',
        order_prefix: h.order_prefix || '',
        is_default: h.is_default ?? 0,
        pay_type: h.pay_type || 'wechat',
        wx_merchants: h.wx_merchants || [],
        ali_merchant_index: h.ali_merchant_index ?? -1
      }))
    } else {
      // 如果没有配置，添加一个默认H5应用
      h5apps.value = [createDefaultH5App()]
    }
  } catch (error) {
    ElMessage.error('加载配置失败')
    console.error('加载配置失败:', error)
    // 加载失败时也添加一个默认H5应用
    h5apps.value = [createDefaultH5App()]
  }
}

// 添加H5应用
const handleAddH5App = () => {
  h5apps.value.push(createDefaultH5App())
  ElMessage.success('已添加新H5应用，请填写配置信息')
}

// 删除H5应用
const handleDeleteH5App = async (index: number) => {
  if (h5apps.value.length <= 1) {
    ElMessage.warning('至少保留一个H5应用配置')
    return
  }

  const isDefault = h5apps.value[index].is_default === 1

  try {
    await ElMessageBox.confirm(
      `确定要删除H5应用"${h5apps.value[index].name || '未命名'}"吗？${isDefault ? '（该应用为默认H5应用，删除后请设置新的默认应用）' : ''}`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    h5apps.value.splice(index, 1)
    
    // 如果删除的是默认H5应用，将第一个设为默认
    if (isDefault && h5apps.value.length > 0) {
      h5apps.value[0].is_default = 1
      ElMessage.info('已将第一个H5应用设为默认')
    }
    
    ElMessage.success('已删除H5应用')
  } catch {
    // 用户取消删除
  }
}

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

// 处理默认状态变化（确保只有一个默认）
const handleDefaultChange = (index: number) => {
  // 将其他H5应用的默认状态设为否
  h5apps.value.forEach((h, i) => {
    if (i !== index) {
      h.is_default = 0
    }
  })
}

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

  const results = await Promise.all(
    h5appFormRefs.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
  }

  // 验证至少有一个H5应用
  if (h5apps.value.length === 0) {
    ElMessage.warning('至少需要配置一个H5应用')
    return
  }

  // 验证必须有一个默认H5应用
  const hasDefault = h5apps.value.some(h => h.is_default === 1)
  if (!hasDefault) {
    ElMessage.warning('必须设置一个默认H5应用')
    return
  }

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

  saving.value = true
  try {
    const submitData: H5Setting = {
      h5apps: h5apps.value
    }

    await updateH5Setting(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;
}

.h5app-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>
