<script setup lang="ts">
import type { EditableKuaishouEticketShop } from '../../composables/types'
import type {
  AdminKuaishouEticketShopInfoResult,
} from '@/types/admin'
import AdminResultCard from '@/components/admin/AdminResultCard.vue'

type KuaishouEticketStats = {
  configuredShopCount: number
  cookieReadyCount: number
  selectedShopReady: boolean
  detailReady: boolean
  consumed: boolean
}

type Props = {
  kuaishouEticketShops: EditableKuaishouEticketShop[]
  kuaishouEticketForm: {
    baseUrl: string
    selectedShopId: string
  }
  kuaishouEticketSaving: boolean
  kuaishouEticketResolvingShopId: string
  kuaishouEticketResultError: string
  kuaishouEticketShopInfoResult: AdminKuaishouEticketShopInfoResult | null
  activeKuaishouEticketShop: EditableKuaishouEticketShop | null
  kuaishouEticketStats: KuaishouEticketStats
  addKuaishouEticketShop: () => void
  removeKuaishouEticketShop: (id: string) => void
  isKuaishouEticketShopExpanded: (id: string) => boolean
  toggleKuaishouEticketShop: (id: string) => void
  expandAllKuaishouEticketShops: () => void
  collapseAllKuaishouEticketShops: () => void
  setKuaishouEticketDebugShop: (id: string) => void
  describeKuaishouEticketShop: (shop: EditableKuaishouEticketShop) => string
  getKuaishouEticketShopInitial: (shop: EditableKuaishouEticketShop) => string
  handleKuaishouEticketResolveShopInfo: (shop: EditableKuaishouEticketShop) => void | Promise<void>
  handleKuaishouEticketSaveSource: () => void | Promise<void>
}

defineProps<Props>()
</script>

<template>
  <el-card class="section-card">
    <template #header>
      <div class="card-header">
        <div>
          <span class="card-title">快手小店店铺配置</span>
          <p class="card-desc">
            支持多店铺配置，建议先粘贴 Cookie，再用 info 接口自动识别 kshopName /
            shopId，最后统一保存到文件。
          </p>
        </div>
        <div class="card-actions">
          <el-button
            :disabled="kuaishouEticketShops.length === 0"
            @click="expandAllKuaishouEticketShops"
            >全部展开</el-button
          >
          <el-button
            :disabled="kuaishouEticketShops.length === 0"
            @click="collapseAllKuaishouEticketShops"
            >全部折叠</el-button
          >
          <el-button @click="addKuaishouEticketShop">新增店铺</el-button>
          <el-button
            :loading="kuaishouEticketSaving"
            type="primary"
            @click="handleKuaishouEticketSaveSource"
            >保存配置</el-button
          >
        </div>
      </div>
    </template>

    <el-form label-width="auto" label-position="top">
      <el-form-item label="Base URL">
        <el-input
          v-model="kuaishouEticketForm.baseUrl"
          placeholder="https://s.kwaixiaodian.com"
        />
      </el-form-item>
    </el-form>

    <el-empty
      v-if="kuaishouEticketShops.length === 0"
      description="当前还没有快手小店店铺配置，先新增一条。"
    />

    <div v-else class="shop-panels">
      <div class="shop-list">
        <el-collapse
          :model-value="
            kuaishouEticketShops
              .filter((s) => isKuaishouEticketShopExpanded(s.id))
              .map((s) => s.id)
          "
        >
          <el-collapse-item
            v-for="shop in kuaishouEticketShops"
            :key="shop.id"
            :name="shop.id"
            :class="[
              'shop-panel',
              {
                'is-debug': kuaishouEticketForm.selectedShopId === shop.id,
              },
            ]"
          >
            <template #title>
              <div class="shop-title-bar">
                <div class="shop-avatar">
                  <img
                    v-if="shop.userAvatar"
                    :src="shop.userAvatar"
                    :alt="shop.kshopName || shop.shopId || '店铺头像'"
                  />
                  <span v-else>{{ getKuaishouEticketShopInitial(shop) }}</span>
                </div>
                <div class="shop-info">
                  <div class="shop-name-row">
                    <strong>{{ shop.kshopName || shop.shopId || '未命名店铺' }}</strong>
                    <el-tag :type="shop.enabled ? 'success' : 'info'" size="small">{{
                      shop.enabled ? '已启用' : '已停用'
                    }}</el-tag>
                    <el-tag
                      v-if="kuaishouEticketForm.selectedShopId === shop.id"
                      type="primary"
                      size="small"
                      >当前调试</el-tag
                    >
                  </div>
                  <div class="shop-meta">
                    <span>店铺 ID：{{ shop.shopId || '等待 info 自动识别' }}</span>
                    <el-tag
                      :type="Boolean(shop.cookie.trim()) ? 'success' : 'warning'"
                      size="small"
                    >
                      {{ shop.cookie.trim() ? 'Cookie 已粘贴' : '待补 Cookie' }}
                    </el-tag>
                    <el-tag
                      :type="Boolean(shop.userAvatar || shop.shopId.trim()) ? 'success' : 'info'"
                      size="small"
                    >
                      {{ shop.userAvatar || shop.shopId.trim() ? '信息已识别' : '未读取信息' }}
                    </el-tag>
                  </div>
                </div>
              </div>
            </template>

            <el-form label-width="auto" label-position="top">
              <el-row :gutter="16">
                <el-col :span="12">
                  <el-form-item label="kshopName">
                    <el-input v-model="shop.kshopName" placeholder="例如 稚嫩游戏交易店" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="店铺 ID">
                    <el-input
                      v-model="shop.shopId"
                      readonly
                      placeholder="通过 info 接口自动识别"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="Cookie">
                <el-input
                  v-model="shop.cookie"
                  type="textarea"
                  :rows="4"
                  placeholder="直接粘贴该店铺请求头中的完整 Cookie"
                />
              </el-form-item>
            </el-form>

            <div class="shop-footer">
              <div class="footer-left">
                <el-switch v-model="shop.enabled" active-text="启用该店铺" />
                <span v-if="shop.userAvatar" class="text-muted"
                  >已识别头像，可直接作为调试店铺</span
                >
                <span v-else class="text-muted">建议先读取店铺信息确认 Cookie 归属</span>
              </div>
              <div class="footer-actions">
                <el-button
                  :loading="kuaishouEticketResolvingShopId === shop.id"
                  size="small"
                  @click="handleKuaishouEticketResolveShopInfo(shop)"
                >
                  读取店铺信息
                </el-button>
                <el-button
                  size="small"
                  :type="kuaishouEticketForm.selectedShopId === shop.id ? 'success' : 'primary'"
                  @click="setKuaishouEticketDebugShop(shop.id)"
                >
                  {{
                    kuaishouEticketForm.selectedShopId === shop.id
                      ? '当前调试店铺'
                      : '设为调试店铺'
                  }}
                </el-button>
                <el-button size="small" type="danger" @click="removeKuaishouEticketShop(shop.id)"
                  >删除</el-button
                >
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>

      <div class="side-panel">
        <AdminResultCard label="店铺总数" :value="kuaishouEticketStats.configuredShopCount">
          <p>其中 Cookie 就绪 {{ kuaishouEticketStats.cookieReadyCount }} 家。</p>
        </AdminResultCard>
        <AdminResultCard
          label="当前调试店铺"
          :value="
            activeKuaishouEticketShop?.kshopName || activeKuaishouEticketShop?.shopId || '未选择'
          "
        >
          <p>
            {{
              kuaishouEticketStats.selectedShopReady
                ? '已具备调试条件，可直接查询核销信息。'
                : '请选择店铺并补全 Cookie。'
            }}
          </p>
        </AdminResultCard>
        <AdminResultCard
          label="最近识别结果"
          :value="
            kuaishouEticketShopInfoResult?.shop.kshopName ||
            kuaishouEticketShopInfoResult?.shop.shopId ||
            '未执行'
          "
        >
          <p v-if="kuaishouEticketShopInfoResult">
            结算状态 {{ kuaishouEticketShopInfoResult.shop.settleStatus }}
          </p>
          <p v-else>可用"读取店铺信息"校验 Cookie 是否属于预期店铺。</p>
        </AdminResultCard>
        <AdminResultCard label="建议顺序" value="先配置，再调试">
          <p>1. 新增店铺并粘贴 Cookie</p>
          <p>2. 读取店铺信息确认 kshopName / shopId</p>
          <p>3. 设为调试店铺后查询券码并执行核销</p>
        </AdminResultCard>
      </div>
    </div>

    <el-alert
      v-if="kuaishouEticketResultError"
      :title="kuaishouEticketResultError"
      type="error"
      show-icon
      :closable="false"
      class="mt-4"
    />
  </el-card>
</template>

<style scoped>
.section-card {
  border-radius: var(--radius-lg);
}

.card-title {
  font-size: var(--text-lg);
  font-weight: 600;
  color: var(--text-primary);
}

.card-desc {
  margin: var(--space-1) 0 0;
  font-size: var(--text-sm);
  color: var(--text-secondary);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: var(--space-3);
}

.card-actions {
  display: flex;
  gap: var(--space-2);
  flex-shrink: 0;
  flex-wrap: wrap;
}

.shop-panels {
  display: grid;
  grid-template-columns: minmax(0, 1.7fr) minmax(260px, 0.9fr);
  gap: var(--space-4);
  margin-top: var(--space-4);
}

.shop-list {
  min-width: 0;
}

.side-panel {
  display: grid;
  gap: var(--space-3);
  align-content: start;
}

.shop-panel.is-debug {
  border: 1px solid var(--border-hover);
  border-radius: var(--radius-md);
}

.shop-title-bar {
  display: flex;
  align-items: center;
  gap: var(--space-3);
  flex: 1;
  min-width: 0;
  padding-right: var(--space-4);
}

.shop-avatar {
  width: 44px;
  height: 44px;
  border-radius: var(--radius-md);
  overflow: hidden;
  background: linear-gradient(135deg, #dbeafe, #eff6ff);
  color: var(--color-primary-dark);
  font-size: 18px;
  font-weight: 800;
  display: grid;
  place-items: center;
  flex-shrink: 0;
  border: 1px solid var(--border-hover);
}

.shop-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.shop-info {
  min-width: 0;
}

.shop-name-row {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  flex-wrap: wrap;
}

.shop-meta {
  display: flex;
  align-items: center;
  gap: var(--space-2);
  flex-wrap: wrap;
  font-size: var(--text-xs);
  color: var(--text-muted);
  margin-top: 2px;
}

.shop-footer {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  flex-wrap: wrap;
  gap: var(--space-3);
  margin-top: var(--space-3);
  padding-top: var(--space-3);
  border-top: 1px solid var(--border-default);
}

.footer-left {
  display: flex;
  align-items: center;
  gap: var(--space-3);
  flex-wrap: wrap;
}

.footer-actions {
  display: flex;
  gap: var(--space-2);
  flex-wrap: wrap;
}

.text-muted {
  font-size: var(--text-xs);
  color: var(--text-muted);
}

@media (max-width: 900px) {
  .shop-panels {
    grid-template-columns: 1fr;
  }
}
</style>
