<template>
  <div v-loading="loading" class="card-layout">
    <div v-if="cardData.length > 0" class="card-grid">
      <div
        v-for="item in cardData"
        :key="item.id"
        class="card-grid-item"
        @click="handleCardClick(item)"
      >
        <CommonCard
          :card-item="item"
          :active="isSelected(item)"
          :show-sku="false"
          :show-product-info="false"
          :image-field="'variantImage'"
        >
          <template #bottom_left>
            <span
              v-if="item.factorySubOrderNumber"
              class="operation-number"
              :title="`操作单号:${item.factorySubOrderNumber}`"
              @click.stop="copyText(String(item.factorySubOrderNumber))"
            >
              {{ item.factorySubOrderNumber }}
            </span>
          </template>
          <template #top_right>
            <img
              v-if="item.craftCode && ['ZPZY', 'CXZY', 'THZY'].includes(item.craftCode as string)"
              :src="`/images/pic/${item.craftCode}.png`"
              width="60"
              height="60"
            />
          </template>
          <template #operations>
            <div v-if="item.customizedQuantity" class="quantity-badge">
              {{ item.customizedQuantity }}
            </div>
            <Icon name="caozuorizhi" style="width: 28px; height: 28px">
              <template #title>
                <title>操作日志</title>
              </template>
            </Icon>
            <Icon name="chakanxiangqing">
              <template #title>
                <title>查看详情</title>
              </template>
            </Icon>
          </template>
          <template #info>
            <div class="card-info-grid">
              <div class="card-info-row full">
                <span
                  class="info-value ellipsis"
                  :title="(item.productName as string) || ''"
                >
                  {{ item.productName }}
                </span>
              </div>
              <div class="card-info-row">
                <span class="info-label">工艺：</span>
                <span class="info-value">{{ item.craftName }}</span>
              </div>
              <div class="card-info-row">
                <span class="info-label">店铺单号：</span>
                <span class="info-value">{{ item.shopNumber }}</span>
              </div>
              <div class="card-info-row">
                <span class="info-label">客户号：</span>
                <span class="info-value">{{ item.userMark }}</span>
              </div>
              <div class="card-info-row">
                <span class="info-label">变体SKU</span>
                <span
                  class="info-value clickable ellipsis"
                  :title="(item.variantSku as string) || ''"
                  @click.stop="copyText((item.variantSku as string) || '')"
                >
                  {{ item.variantSku }}
                </span>
              </div>
              <div class="card-info-row">
                <span class="info-label">库存SKU</span>
                <span
                  class="info-value clickable ellipsis"
                  :title="(item.thirdSkuCode as string) || ''"
                  @click.stop="copyText((item.thirdSkuCode as string) || '')"
                >
                  {{ item.thirdSkuCode }}
                </span>
              </div>
              <div class="card-info-row">
                <span class="info-label">款号：</span>
                <span class="info-value">{{ item.supplierProductNo }}</span>
              </div>
              <div v-if="item.batchArrangeNumber" class="card-info-row">
                <span class="info-label">批次号：</span>
                <span class="info-value">{{ item.batchArrangeNumber }}</span>
              </div>
              <div class="card-info-row">
                <span class="info-label">状态：</span>
                <span class="info-value">{{ item.statusName }}</span>
              </div>
            </div>
          </template>
        </CommonCard>
      </div>
    </div>
    <div v-else class="card-empty">暂无数据</div>

    <div class="card-pagination">
      <div class="card-selected-info">
        已选择
        <span class="highlight">{{ selectedItems.length }}</span>
        条数据
      </div>
      <ElPagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[50, 100, 200, 300]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin: 0 auto"
        @size-change="onPageSizeChange"
        @current-change="onCurrentPageChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { getCardLayoutListApi } from '@/api/factoryOrderNew'
import type { PaginationData } from '@/types/api'
import usePageList from '@/utils/hooks/usePageList'

interface CardItem {
  id: number | string
  [key: string]: unknown
}

const props = defineProps<{
  status: string
  queryPayload: Record<string, unknown>
  initPageSize?: number
}>()

const emit = defineEmits<{
  'selection-change': [items: CardItem[]]
}>()

const {
  loading,
  currentPage,
  pageSize,
  total,
  data: cardData,
  onCurrentPageChange,
  onPageSizeChange,
  refresh,
} = usePageList<CardItem>({
  initPageSize: props.initPageSize || 100,
  query: async (current, size) => {
    const payload = {
      ...props.queryPayload,
      statusCode: props.status === 'ALL' ? undefined : props.status,
    }
    const res = await getCardLayoutListApi(payload, current, size)
    return res.data as unknown as PaginationData<CardItem>
  },
})

const selectedItems = ref<CardItem[]>([])

const isSelected = (item: CardItem) =>
  selectedItems.value.some((s) => s.id === item.id)

const handleCardClick = (item: CardItem) => {
  const idx = selectedItems.value.findIndex((s) => s.id === item.id)
  if (idx >= 0) {
    selectedItems.value.splice(idx, 1)
  } else {
    selectedItems.value.push(item)
  }
  emit('selection-change', [...selectedItems.value])
}

const copyText = (text: string) => {
  navigator.clipboard.writeText(text)
  ElMessage.success('复制成功')
}

const clearSelection = () => {
  selectedItems.value = []
  emit('selection-change', [])
}

const getSelectedIds = () => selectedItems.value.map((i) => i.id)

defineExpose({ clearSelection, getSelectedIds, refresh })
</script>

<style scoped lang="scss">
.card-layout {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.card-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: max-content;
  gap: 10px;
  flex: 1;
  overflow-y: auto;
  padding: 5px;
}

.card-grid-item {
  cursor: pointer;
}

.card-empty {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 14px;
}

.card-pagination {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 0;
}

.card-selected-info {
  font-size: 13px;
  color: #606266;

  .highlight {
    color: #f56c6c;
    font-weight: bold;
  }
}

.operation-number {
  font-size: 12px;
  cursor: pointer;
  color: #409eff;

  &:hover {
    text-decoration: underline;
  }
}

.quantity-badge {
  background-color: #e6a23c;
  color: #fff;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.card-info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 4px;
  font-size: 12px;
  margin-top: 6px;

  .full {
    grid-column: 1 / -1;
  }
}

.card-info-row {
  display: flex;
  overflow: hidden;
}

.info-label {
  flex-shrink: 0;
  color: #909399;
}

.info-value {
  flex: 1;
  min-width: 0;

  &.ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  &.clickable {
    cursor: pointer;
    color: #409eff;

    &:hover {
      text-decoration: underline;
    }
  }
}
</style>
