<template>
  <ElDrawer
    v-model="visible"
    :title="t('store.detail.title')"
    size="60%"
    direction="rtl"
    @closed="handleClosed"
  >
    <div class="px-4 pb-4" v-loading="loading">
      <div class="mb-4 flex flex-wrap items-center justify-between gap-3">
        <div>
          <div class="text-lg font-semibold">
            {{ store?.name || t('store.detail.empty') }}
          </div>
          <div class="text-sm text-[var(--el-text-color-secondary)]">
            {{ store?.code || '-' }}
          </div>
        </div>
      </div>

      <ElTabs v-if="storeId" v-model="activeTab">
        <ElTabPane :label="t('store.detail.tabs.basic')" name="basic">
          <ElDescriptions v-if="store" :column="2" border>
            <ElDescriptionsItem :label="t('store.detail.fields.name')">
              {{ store.name }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.detail.fields.code')">
              {{ store.code }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.detail.fields.auditStatus')">
              <ElTag :type="getAuditStatusType(store.auditStatus)">
                {{ getAuditStatusText(store.auditStatus) }}
              </ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.detail.fields.businessStatus')">
              <ElTag :type="getBusinessStatusType(store.businessStatus)">
                {{ getBusinessStatusText(store.businessStatus) }}
              </ElTag>
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.detail.fields.ownershipType')">
              {{ getOwnershipTypeText(store.ownershipType) }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.detail.fields.phone')">
              {{ store.phone || '-' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.detail.fields.address')">
              {{ formatFullAddress(store) }}
            </ElDescriptionsItem>
            <ElDescriptionsItem :label="t('store.detail.fields.createdAt')">
              {{ formatDateTime(store.createdAt) }}
            </ElDescriptionsItem>
          </ElDescriptions>
        </ElTabPane>
        <ElTabPane :label="t('store.detail.tabs.qualification')" name="qualification">
          <StoreQualificationPanel :store-id="storeId" :tenant-id="store?.tenantId" />
        </ElTabPane>
        <ElTabPane :label="t('store.detail.tabs.businessHours')" name="businessHours">
          <BusinessHoursPanel :store-id="storeId" />
        </ElTabPane>
        <ElTabPane :label="t('store.detail.tabs.temporaryHours')" name="temporaryHours">
          <TemporaryHoursPanel :store-id="storeId" />
        </ElTabPane>
        <ElTabPane :label="t('store.detail.tabs.deliveryZone')" name="deliveryZone">
          <DeliveryZoneMapEditor :store-id="storeId" :store="store" />
        </ElTabPane>
        <ElTabPane :label="t('store.detail.tabs.fee')" name="fee">
          <StoreFeePanel :store-id="storeId" />
        </ElTabPane>
      </ElTabs>

      <ElEmpty v-else :description="t('store.detail.empty')" />
    </div>
  </ElDrawer>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { useI18n } from 'vue-i18n'
  import {
    ElDescriptions,
    ElDescriptionsItem,
    ElDrawer,
    ElEmpty,
    ElTabPane,
    ElTabs,
    ElTag
  } from 'element-plus'
  import { fetchStoreDetail } from '@/api/store'
  import { StoreAuditStatus } from '@/enums/StoreAuditStatus'
  import { StoreBusinessStatus } from '@/enums/StoreBusinessStatus'
  import { StoreOwnershipType } from '@/enums/StoreOwnershipType'
  import { formatDateTime } from '@/utils/billing'
  import StoreQualificationPanel from '@/views/store/store-detail/components/StoreQualificationPanel.vue'
  import BusinessHoursPanel from '@/views/store/store-detail/components/BusinessHoursPanel.vue'
  import TemporaryHoursPanel from '@/views/store/store-detail/components/TemporaryHoursPanel.vue'
  import DeliveryZoneMapEditor from '@/views/store/store-detail/components/DeliveryZoneMapEditor.vue'
  import StoreFeePanel from '@/views/store/store-detail/components/StoreFeePanel.vue'

  defineOptions({ name: 'StoreDetailDrawer' })

  type StoreDetailTab =
    | 'basic'
    | 'qualification'
    | 'businessHours'
    | 'temporaryHours'
    | 'deliveryZone'
    | 'fee'

  // 1. 基础状态
  const { t } = useI18n()
  const visible = ref(false)
  const loading = ref(false)
  const storeId = ref('')
  const store = ref<Api.Store.StoreDto | null>(null)
  const activeTab = ref<StoreDetailTab>('basic')
  const currentLoadToken = ref(0)

  // 2. 详情加载
  const loadStore = async (token: number) => {
    if (!storeId.value) {
      store.value = null
      return
    }

    loading.value = true
    try {
      // 1. 拉取门店详情
      const result = await fetchStoreDetail(storeId.value, { showErrorMessage: false })
      if (token !== currentLoadToken.value) {
        return
      }
      store.value = result
    } finally {
      if (token === currentLoadToken.value) {
        loading.value = false
      }
    }
  }

  // 3. 抽屉控制
  const open = async (id: string) => {
    visible.value = true

    // 1. 初始化抽屉状态
    storeId.value = String(id)
    activeTab.value = 'basic'
    store.value = null

    // 2. 拉取详情数据
    const token = ++currentLoadToken.value
    await loadStore(token)
  }

  const handleClosed = () => {
    // 1. 关闭时清理状态，避免残留
    currentLoadToken.value += 1
    storeId.value = ''
    store.value = null
    activeTab.value = 'basic'
    loading.value = false
  }

  const formatFullAddress = (target: Api.Store.StoreDto) =>
    `${target.province ?? ''}${target.city ?? ''}${target.district ?? ''}${target.address ?? ''}` ||
    '-'

  // 4. 状态展示
  const getAuditStatusType = (status: StoreAuditStatus) => {
    switch (status) {
      case StoreAuditStatus.Draft:
        return 'info'
      case StoreAuditStatus.Pending:
        return 'warning'
      case StoreAuditStatus.Activated:
        return 'success'
      case StoreAuditStatus.Rejected:
        return 'danger'
      default:
        return 'info'
    }
  }
  const getAuditStatusText = (status: StoreAuditStatus) => {
    switch (status) {
      case StoreAuditStatus.Draft:
        return t('store.auditStatus.draft')
      case StoreAuditStatus.Pending:
        return t('store.auditStatus.pending')
      case StoreAuditStatus.Activated:
        return t('store.auditStatus.activated')
      case StoreAuditStatus.Rejected:
        return t('store.auditStatus.rejected')
      default:
        return t('store.auditStatus.unknown')
    }
  }
  const getBusinessStatusType = (status: StoreBusinessStatus) => {
    switch (status) {
      case StoreBusinessStatus.Open:
        return 'success'
      case StoreBusinessStatus.Resting:
        return 'warning'
      case StoreBusinessStatus.ForceClosed:
        return 'danger'
      default:
        return 'info'
    }
  }
  const getBusinessStatusText = (status: StoreBusinessStatus) => {
    switch (status) {
      case StoreBusinessStatus.Open:
        return t('store.businessStatus.open')
      case StoreBusinessStatus.Resting:
        return t('store.businessStatus.resting')
      case StoreBusinessStatus.ForceClosed:
        return t('store.businessStatus.forceClosed')
      default:
        return t('store.businessStatus.unknown')
    }
  }
  const getOwnershipTypeText = (type?: StoreOwnershipType) => {
    switch (type) {
      case StoreOwnershipType.SameEntity:
        return t('store.ownership.same')
      case StoreOwnershipType.DifferentEntity:
        return t('store.ownership.different')
      default:
        return '-'
    }
  }

  defineExpose({ open })
</script>
