<script setup lang="ts">
import { ArrowLeft, CheckCheck, Loader2, X } from 'lucide-vue-next'
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { toast } from 'vue-sonner'

import { BasicPage } from '@/components/global-layout'

interface CardType {
  id: number
  name: string
  billing_type: string
  price: number
}

interface CardTypePermission {
  card_type_id: number
  name: string
  billing_type: string
  price: number
  can_generate: boolean
}

const route = useRoute()
const router = useRouter()
const API_BASE = 'http://localhost:8080/api/v1'

const loading = ref(true)
const saving = ref(false)
const agentAppName = ref('')
const cardTypeForm = ref<CardTypePermission[]>([])

function getBillingTypeText(type: string) {
  const map: Record<string, string> = {
    subscription: '订阅',
    time: '计时',
    point: '点卡',
  }
  return map[type] || type
}

async function fetchData() {
  loading.value = true
  try {
    const token = localStorage.getItem('token')

    const [agentAppRes, cardTypesRes] = await Promise.all([
      fetch(`${API_BASE}/dev/agent-apps/${route.params.id}`, {
        headers: { Authorization: `Bearer ${token}` },
      }),
      fetch(`${API_BASE}/dev/card-types`, {
        headers: { Authorization: `Bearer ${token}` },
      }),
    ])

    const [agentAppData, cardTypesData] = await Promise.all([
      agentAppRes.json(),
      cardTypesRes.json(),
    ])

    if (agentAppData.code === 200 && agentAppData.agent_app) {
      agentAppName.value = `${agentAppData.agent_app.agent_name} - ${agentAppData.agent_app.app_name}`
      const existingPerms = agentAppData.agent_app.card_types || []

      const allCardTypes = cardTypesData.card_types || []
      cardTypeForm.value = allCardTypes.map((ct: CardType) => {
        const existing = existingPerms.find((p: any) => p.card_type_id === ct.id)
        return {
          card_type_id: ct.id,
          name: ct.name,
          billing_type: ct.billing_type,
          price: ct.price,
          can_generate: existing ? existing.can_generate : false,
        }
      })
    }
    else {
      toast.error('获取授权信息失败')
      router.push('/admin/agent-apps')
    }
  }
  catch (error) {
    console.error('获取数据失败:', error)
    toast.error('获取数据失败')
    router.push('/admin/agent-apps')
  }
  finally {
    loading.value = false
  }
}

function selectAll() {
  cardTypeForm.value.forEach(ct => ct.can_generate = true)
}

function clearAll() {
  cardTypeForm.value.forEach(ct => ct.can_generate = false)
}

async function handleSubmit() {
  saving.value = true
  try {
    const token = localStorage.getItem('token')
    const response = await fetch(`${API_BASE}/dev/agent-apps/${route.params.id}/card-types`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        card_types: cardTypeForm.value.map(ct => ({
          card_type_id: ct.card_type_id,
          can_generate: ct.can_generate,
        })),
      }),
    })

    const data = await response.json()
    if (data.code === 200) {
      toast.success('保存成功')
      router.push('/admin/agent-apps')
    }
    else {
      toast.error(data.message || '保存失败')
    }
  }
  catch (error) {
    console.error('保存失败:', error)
    toast.error('保存失败')
  }
  finally {
    saving.value = false
  }
}

function goBack() {
  router.push('/admin/agent-apps')
}

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

<template>
  <BasicPage
    title="卡密权限配置"
    description="配置代理商可生成的卡密类型"
  >
    <template #actions>
      <UiButton variant="outline" @click="goBack">
        <ArrowLeft class="mr-2 h-4 w-4" />
        返回
      </UiButton>
    </template>

    <div v-if="loading" class="flex items-center justify-center py-12">
      <Loader2 class="h-8 w-8 animate-spin text-muted-foreground" />
    </div>

    <div v-else class="space-y-6">
      <UiCard>
        <UiCardHeader>
          <UiCardTitle>授权信息</UiCardTitle>
          <UiCardDescription>
            {{ agentAppName }}
          </UiCardDescription>
        </UiCardHeader>
        <UiCardContent>
          <div class="flex gap-2 mb-4">
            <UiButton variant="outline" size="sm" @click="selectAll">
              <CheckCheck class="mr-2 h-4 w-4" />
              全选
            </UiButton>
            <UiButton variant="outline" size="sm" @click="clearAll">
              <X class="mr-2 h-4 w-4" />
              清空
            </UiButton>
          </div>
        </UiCardContent>
      </UiCard>

      <UiCard>
        <UiCardContent class="p-0">
          <UiTable>
            <UiTableHeader>
              <UiTableRow>
                <UiTableHead class="w-12" />
                <UiTableHead>卡类名称</UiTableHead>
                <UiTableHead>计费类型</UiTableHead>
                <UiTableHead>价格</UiTableHead>
              </UiTableRow>
            </UiTableHeader>
            <UiTableBody>
              <UiTableRow
                v-for="cardType in cardTypeForm"
                :key="cardType.card_type_id"
                :class="cardType.can_generate ? 'bg-accent/50' : ''"
                class="cursor-pointer"
                @click="cardType.can_generate = !cardType.can_generate"
              >
                <UiTableCell>
                  <UiCheckbox
                    :checked="cardType.can_generate"
                    @update:checked="cardType.can_generate = $event"
                    @click.stop
                  />
                </UiTableCell>
                <UiTableCell class="font-medium">
                  {{ cardType.name }}
                </UiTableCell>
                <UiTableCell>
                  <UiBadge variant="outline">
                    {{ getBillingTypeText(cardType.billing_type) }}
                  </UiBadge>
                </UiTableCell>
                <UiTableCell>
                  ¥{{ cardType.price }}
                </UiTableCell>
              </UiTableRow>
            </UiTableBody>
          </UiTable>
        </UiCardContent>
        <UiCardFooter class="flex justify-end gap-2">
          <UiButton variant="outline" @click="goBack">
            取消
          </UiButton>
          <UiButton :disabled="saving" @click="handleSubmit">
            <Loader2 v-if="saving" class="mr-2 h-4 w-4 animate-spin" />
            保存
          </UiButton>
        </UiCardFooter>
      </UiCard>
    </div>
  </BasicPage>
</template>
