<template>
  <ElDialog
    v-model="visible"
    title="申请补胚"
    width="900px"
    :close-on-click-modal="false"
  >
    <div class="replenish-tip">请选择具体的操作单，申请补胚</div>
    <div v-loading="loading" class="replenish-card-grid">
      <div
        v-for="item in cardList"
        :key="item.id"
        class="replenish-card-item"
        @click="toggleSelect(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}`"
            >
              {{ item.factorySubOrderNumber }}
            </span>
          </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 ellipsis" :title="(item.variantSku as string) || ''">
                  {{ item.variantSku }}
                </span>
              </div>
              <div class="card-info-row">
                <span class="info-label">库存SKU</span>
                <span class="info-value ellipsis" :title="(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 v-if="!loading && cardList.length === 0" class="replenish-empty">
        暂无数据
      </div>
    </div>
    <template #footer>
      <div style="text-align: center">
        <ElButton @click="visible = false">取消</ElButton>
        <ElButton type="primary" :loading="submitting" @click="handleConfirm">
          确定
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import CommonCard from '@/components/CommonCard.vue'
import { applyForReplenishByIdApi } from '@/api/factoryOrderNew'

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

const emit = defineEmits<{
  success: []
}>()

const visible = ref(false)
const loading = ref(false)
const submitting = ref(false)
const cardList = ref<CardItem[]>([])
const selectedItems = ref<CardItem[]>([])
const productId = ref<number | string>()

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

const toggleSelect = (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)
  }
}

const open = async (id: number | string) => {
  productId.value = id
  selectedItems.value = []
  cardList.value = []
  visible.value = true
  loading.value = true
  try {
    const res = await applyForReplenishByIdApi(id)
    cardList.value = Array.isArray(res.data) ? res.data : []
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleConfirm = async () => {
  if (!selectedItems.value.length) {
    return ElMessage.warning('请选择操作单')
  }
  submitting.value = true
  try {
    await applyForReplenishByIdApi(productId.value!)
    ElMessage.success('申请补胚成功')
    visible.value = false
    emit('success')
  } catch (e) {
    console.error(e)
  } finally {
    submitting.value = false
  }
}

defineExpose({ open })
</script>

<style scoped lang="scss">
.replenish-tip {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
}

.replenish-card-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  max-height: 500px;
  overflow-y: auto;
  min-height: 200px;
}

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

.replenish-empty {
  grid-column: 1 / -1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 14px;
  min-height: 200px;
}

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

.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;
  }
}
</style>
