<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="handleAddMiniprogram">
              <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="miniprograms.length === 0"
        description="暂无小程序配置，请点击添加小程序"
      >
        <el-button type="primary" @click="handleAddMiniprogram">
          <el-icon><Plus /></el-icon>添加小程序
        </el-button>
      </el-empty>

      <!-- 小程序列表 -->
      <div v-else class="miniprogram-list">
        <MiniprogramForm
          v-for="(_miniprogram, index) in miniprograms"
          :key="index"
          ref="miniprogramFormRefs"
          v-model="miniprograms[index]"
          :index="index"
          :can-delete="miniprograms.length > 1"
          :existing-prefixes="existingPrefixes"
          :weixin-merchants="weixinMerchants"
          @delete="handleDeleteMiniprogram"
          @change="handleMiniprogramChange"
          @default-change="handleDefaultChange"
        />
      </div>

      <!-- 底部操作栏 -->
      <div v-if="miniprograms.length > 0" class="footer-actions">
        <el-button type="primary" @click="handleAddMiniprogram">
          <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 {
  getMiniprogramSetting,
  updateMiniprogramSetting,
  getWeixinPaySetting,
  type MiniprogramConfig,
  type MiniprogramSetting,
  type WeixinPayMerchant
} from '@/api/business/config'
import MiniprogramForm from './components/MiniprogramForm.vue'

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

// 小程序列表
const miniprograms = ref<MiniprogramConfig[]>([])

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

// 小程序表单引用
const miniprogramFormRefs = ref<InstanceType<typeof MiniprogramForm>[]>([])

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

// 创建默认小程序
const createDefaultMiniprogram = (): MiniprogramConfig => ({
  name: '',
  appid: '',
  appsecret: '',
  order_prefix: '',
  is_default: miniprograms.value.length === 0 ? 1 : 0, // 第一个默认为默认小程序
  merchants: []
})

// 加载微信支付商户列表
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 loadData = async () => {
  loading.value = true
  try {
    // 并行加载小程序配置和微信支付商户列表
    await Promise.all([
      loadMiniprogramSetting(),
      loadWeixinMerchants()
    ])
  } finally {
    loading.value = false
  }
}

// 加载小程序配置
const loadMiniprogramSetting = async () => {
  try {
    const res = await getMiniprogramSetting()
    if (res.data?.value?.miniprograms && res.data.value.miniprograms.length > 0) {
      miniprograms.value = res.data.value.miniprograms.map(m => ({
        name: m.name || '',
        appid: m.appid || '',
        appsecret: m.appsecret || '',
        order_prefix: m.order_prefix || '',
        is_default: m.is_default ?? 0,
        merchants: m.merchants || []
      }))
    } else {
      // 如果没有配置，添加一个默认小程序
      miniprograms.value = [createDefaultMiniprogram()]
    }
  } catch (error) {
    ElMessage.error('加载配置失败')
    console.error('加载配置失败:', error)
    // 加载失败时也添加一个默认小程序
    miniprograms.value = [createDefaultMiniprogram()]
  }
}

// 添加小程序
const handleAddMiniprogram = () => {
  miniprograms.value.push(createDefaultMiniprogram())
  ElMessage.success('已添加新小程序，请填写配置信息')
}

// 删除小程序
const handleDeleteMiniprogram = async (index: number) => {
  if (miniprograms.value.length <= 1) {
    ElMessage.warning('至少保留一个小程序配置')
    return
  }

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

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

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

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

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

  const results = await Promise.all(
    miniprogramFormRefs.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 (miniprograms.value.length === 0) {
    ElMessage.warning('至少需要配置一个小程序')
    return
  }

  // 验证必须有一个默认小程序
  const hasDefault = miniprograms.value.some(m => m.is_default === 1)
  if (!hasDefault) {
    ElMessage.warning('必须设置一个默认小程序')
    return
  }

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

  saving.value = true
  try {
    const submitData: MiniprogramSetting = {
      miniprograms: miniprograms.value
    }

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

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