<template>
  <div class="card-layout">
    <div v-if="data.length > 0" class="card-grid">
      <div
        v-for="item in data"
        :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
        v-model:current-page="currentPageModel"
        v-model:page-size="pageSizeModel"
        :page-sizes="[50, 100, 200, 300]"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin: 0 auto"
        @size-change="$emit('page-size-change', $event)"
        @current-change="$emit('current-page-change', $event)"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'

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

const props = defineProps<{
  data: CardItem[]
  total: number
  currentPage: number
  pageSize: number
}>()

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

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

const currentPageModel = computed({
  get: () => props.currentPage,
  set: (val) => emit('current-page-change', val),
})
const pageSizeModel = computed({
  get: () => props.pageSize,
  set: (val) => emit('page-size-change', val),
})

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 })
</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>
