<template>
  <ElDialog
    v-model="visible"
    :title="title"
    width="1500px"
    :close-on-click-modal="false"
  >
    <div class="operate-order-details-content">
      <div v-if="!pickable" class="operate-order-tip">
        请选择具体的操作单，申请补胚
      </div>
      <div v-else class="pick-data">
        <div class="pick-data-item">
          <span>商品名称: </span>
          <span>{{ selectedRow?.productName }}</span>
        </div>
        <div class="pick-data-item">
          <span>库存SKU: </span>
          <span>{{ selectedRow?.thirdSkuCode }}</span>
        </div>
        <div class="pick-data-item">
          <span>仓库: </span>
          <span>{{ selectedRow?.warehouseName }}</span>
        </div>
        <div class="pick-data-item" style="color: red">
          <span>当前拣胚数量: </span>
          <span>{{ selectedItems.length }}</span>
        </div>
        <div class="pick-data-item">
          <span>库存数量: </span>
          <span>{{ selectedRow?.inventory }}</span>
        </div>
        <div class="pick-data-item">
          <span>生产中数量: </span>
          <span>{{ selectedRow?.producingQuantity }}</span>
        </div>
      </div>
      <div v-loading="loading" class="operate-order-card-grid">
        <div
          v-for="item in cardList"
          :key="item.id"
          class="operate-order-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
                class="operation-number"
                :title="`操作单号:${item.operationNo}`"
                @click.stop="String(item.operationNo)"
              >
                {{ item.operationNo }}
              </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 #images>
              <div class="flex-between">
                <div class="images-position">
                  <div v-if="item.imageAry" class="images-container">
                    <div
                      v-for="(img, index) in JSON.parse(item.imageAry as string)"
                      :key="index"
                      :title="img.title"
                      class="item-image"
                    >
                      <el-image
                        :src="img?.url"
                        height="50"
                        :preview-src-list="JSON.parse(item.imageAry as string).map((i: any) => i.url)"
                      />
                    </div>
                  </div>
                </div>
                <div class="flex-row flex-row-gap15">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    :content="'用户编码: ' + item?.userMark"
                    placement="bottom"
                  >
                    <span
                      style="
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        width: 100%;
                        display: inline-block;
                      "
                      @click.stop="copyText(String(item?.userMark || ''))"
                    >
                      {{ item?.userMark || 'AAAF' }}
                    </span>
                  </el-tooltip>
                  <img
                    v-if="item.platform"
                    :src="`/images/icon/${getPlatformImg(item.platform as string)}`"
                    style="width: 30px; height: 30px"
                  />
                </div>
              </div>
            </template>
            <template #operations>
              <div class="flex-row flex-row-gap6">
                <div
                  v-if="item.customizedQuantity"
                  class="quantity-badge"
                  :class="
                    item.customizedQuantity === 1
                      ? 'single-quantity-badge-color'
                      : 'multiple-quantity-badge-color'
                  "
                  :title="`类型:${
                    item.customizedQuantity === 1 ? '单面' : '双面'
                  }`"
                >
                  {{ item.customizedQuantity === 1 ? '单' : '多' }}
                </div>
              </div>
            </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-value clickable ellipsis"
                    :title="`变体SKU:${(item.variantSku as string) || ''}`"
                    @click.stop="copyText((item.variantSku as string) || '')"
                  >
                    {{ item.variantSku }}
                  </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-value clickable ellipsis"
                    :title="`库存SKU:${(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 clickable ellipsis"
                    :title="`店铺单号:${(item.shopNumber as string) || ''}`"
                    @click.stop="copyText((item.shopNumber as string) || '')"
                    >{{ item.shopNumber }}</span
                  >
                </div>
                <div class="card-info-row">
                  <span class="info-label">款号：</span>
                  <span
                    class="info-value clickable ellipsis"
                    :title="`款号:${(item.supplierProductNo as string) || ''}`"
                    @click.stop="
                      copyText((item.supplierProductNo as string) || '')
                    "
                    >{{ item.supplierProductNo }}</span
                  >
                </div>
                <div class="card-info-row">
                  <span class="info-label">客户单号：</span>
                  <span
                    class="info-value clickable ellipsis"
                    :title="`客户单号:${(item.thirdOrderNumber as string) || ''}`"
                    @click.stop="
                      copyText((item.thirdOrderNumber as string) || '')
                    "
                    >{{ item.thirdOrderNumber }}</span
                  >
                </div>
                <div class="card-info-row">
                  <span class="info-label">批次号：</span>
                  <span
                    class="info-value clickable ellipsis"
                    :title="`批次号:${(item.batchArrangeNumber as string) || ''}`"
                    @click.stop="
                      copyText((item.batchArrangeNumber as string) || '')
                    "
                    >{{ item.batchArrangeNumber }}</span
                  >
                </div>
                <div class="card-info-row" style="color: red">
                  <span class="info-label">状态：</span>
                  <span class="info-value ellipsis">{{ item.statusName }}</span>
                </div>
              </div>
            </template>
          </CommonCard>
        </div>
        <div v-if="!loading && cardList.length === 0" class="replenish-empty">
          暂无数据
        </div>
      </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 {
  applyForProductByIdApi,
  applyForReplenishByIdApi,
} from '@/api/factoryOrderNew'
import platformJson from '../../../../json/platform.json'
import type {
  operateOrderListData,
  PickCompleteData,
} from '@/types/api/factoryOrderNew'
const emit = defineEmits(['adjustPickOrderSuccess'])

const props = defineProps<{
  title: string
  pickable?: boolean
}>()

const visible = ref(false)
const loading = ref(false)
const submitting = ref(false)
const cardList = ref<operateOrderListData[]>([])
const selectedItems = ref<operateOrderListData[]>([])
const selectedRow = ref<PickCompleteData | null>(null)

const isSelected = (item: operateOrderListData) => {
  return selectedItems.value.some((s) => s.id === item.id)
}

const toggleSelect = (item: operateOrderListData) => {
  const idx = selectedItems.value.findIndex((s) => s.id === item.id)
  if (idx >= 0) {
    selectedItems.value.splice(idx, 1)
  } else {
    selectedItems.value.push(item)
  }
}
const copyText = (text: string) => {
  navigator.clipboard.writeText(text)
  ElMessage.success('复制成功')
}

const open = async ({
  row,
  ids,
  url,
}: {
  row: PickCompleteData
  ids: (number | string)[]
  url: string
}) => {
  selectedItems.value = []
  cardList.value = []
  loading.value = true
  try {
    const res = props.pickable
      ? await applyForReplenishByIdApi(ids, url)
      : await applyForProductByIdApi(ids[0] as string, url)
    if (res.code !== 200) return
    cardList.value = Array.isArray(res.data) ? res.data : []
    if (row.availableOrderIds?.length) {
      selectedItems.value = cardList.value.filter((item) => {
        return row.availableOrderIds?.includes(item.id)
      })
    }
    visible.value = true
    selectedRow.value = row
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}
const getPlatformImg = (code: string) => {
  const lowerCode = code.toLowerCase()
  const item = platformJson.find((el) =>
    el.type.toLowerCase().includes(lowerCode),
  )
  if (item) {
    return item.icon.split('/').pop()
  }
  return ''
}

const handleConfirm = async () => {
  if (!selectedItems.value.length) {
    return ElMessage.warning('请选择操作单')
  }
  if (props.pickable) {
    if (
      selectedItems.value.length >
      (selectedRow.value?.availableOrderIds?.length ?? 0)
    ) {
      return ElMessageBox.confirm(
        `<div>
        <span>当前库存数量: ${selectedRow.value?.inventory}</span>
        <span style="margin: 0 4px">生产中数量: ${selectedRow.value?.producingQuantity}</span>
        <span>最多只能拣胚 ${selectedRow.value?.availableOrderIds?.length} 个</span>
        <div>请重新选择!</div>
      </div>`,
        '提示',
        {
          type: 'warning',
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
        },
      )
    }
  }
  emit(
    'adjustPickOrderSuccess',
    null,
    selectedItems.value.map((item) => item.id),
    selectedRow.value,
  )
  visible.value = false
}

defineExpose({ open })
</script>

<style scoped lang="scss">
.operate-order-details-content {
  height: 600px;
}
.operate-order-tip {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
}

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

.operate-order-card-item {
  cursor: pointer;
}

.operate-order-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;
}

.card-info-grid {
  display: grid;
  grid-template-columns: 1fr 90px;
  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;
    }
  }
}

.flex-row {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 15px;
}
.flex-row-gap15 {
  gap: 15px;
}
.flex-row-gap6 {
  gap: 6px;
}
.quantity-badge {
  background-color: #f56c6c;
  color: #fff;
  padding: 5px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.multiple-quantity-badge-color {
  background-color: #e6a23c;
}
.pick-data {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 10px;
}
</style>
