<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    top="140px"
    :fullscreen="true"
    :close-on-click-modal="false"
    @close="emit('close')"
  >
    <div class="detail-div">
      <div class="detail-content">
        <div class="left">
          <div class="left-images">
            <el-carousel
              v-if="detail?.imgList.length > 0"
              style="height: 100%"
              :autoplay="false"
              indicator-position="none"
            >
              <el-carousel-item
                v-for="(item, index) in detail?.imgList"
                :key="index"
                style="height: 100%"
              >
                <el-row :gutter="10" style="width: 100%; height: 100%">
                  <el-col
                    v-for="(it, i) in item"
                    :key="i"
                    style="height: 100%"
                    :span="12"
                  >
                    <div class="left-image">
                      <b v-show="it?.title && it?.url">
                        {{ it?.title }}
                        <span
                          v-if="it?.id"
                          style="
                            text-decoration: underline;
                            cursor: pointer;
                            color: blue;
                          "
                        >
                          （DID：{{ it?.id }}）
                        </span>
                      </b>
                      <img :src="it?.url" alt="" />
                    </div>
                  </el-col>
                </el-row>
              </el-carousel-item>
            </el-carousel>
          </div>
        </div>
        <div class="right">
          <div
            v-if="!detailData || Object.keys(detailData).length === 0"
            class="input"
          >
            <el-input
              ref="trackingNumberRef"
              v-model="TrackingNumber"
              :placeholder="placeholderText"
              style="width: 660px; margin-right: 10px"
              clearable
              @keydown.enter="trackcodeInput()"
            ></el-input>
            <el-button type="primary" @click="trackcodeInput()">
              查询
            </el-button>
          </div>
          <div v-if="isJmpod === 'JMPOD'" class="div-text">
            <div class="div-content">
              <div :title="String(detail?.userMark)" class="div-item">
                <span style="font-size: 18px">客户</span>
                <p style="color: red; font-size: 30px">
                  {{ detail?.userMark }}
                </p>
              </div>
              <div
                :title="String(detail?.factoryOrderNumber)"
                class="div-item"
                style="margin-top: 14px"
              >
                <span style="font-size: 18px">订单号</span>
                <p style="color: red; font-size: 22px">
                  {{ detail?.factoryOrderNumber }}
                </p>
              </div>
            </div>
          </div>
          <div class="div-text">
            <b>生产单信息</b>
            <div class="div-content">
              <div :title="detail?.factorySubOrderNumber" class="div-item">
                <span>生产单号</span>
                <p>
                  {{ detail?.factorySubOrderNumber }}
                </p>
              </div>
              <div :title="detail?.thirdSubOrderNumber || ''" class="div-item">
                <span>第三方生产单号</span>
                <p>
                  {{ detail?.thirdSubOrderNumber }}
                </p>
              </div>
              <div :title="String(detail?.process)" class="div-item">
                <span>生产工艺</span>
                <p>
                  {{ detail?.process }}
                </p>
              </div>
              <div :title="detail?.baseSku" class="div-item">
                <span>基版</span>
                <p>{{ detail?.baseSku }}</p>
              </div>
              <div :title="String(detail?.supplierItemNo)" class="div-item">
                <span>货号</span>
                <p>{{ detail?.supplierItemNo }}</p>
              </div>
              <div :title="detail?.variantSku" class="div-item">
                <span>变体SKU</span>
                <p>{{ detail?.variantSku }}</p>
              </div>
              <div :title="String(detail?.num)" class="div-item">
                <span>数量</span>
                <p>{{ detail?.num }}</p>
              </div>
              <!-- <div :title="detail?.categoryName" class="div-item">
                <span>类别</span>
                <p>{{ detail?.categoryName }}</p>
              </div> -->
              <div :title="String(detail?.size)" class="div-item">
                <span>尺寸</span>
                <p>{{ detail?.size }}</p>
              </div>
              <div
                v-if="detail?.sizeType"
                :title="String(detail?.sizeType)"
                class="div-item"
              >
                <span>尺码类型</span>
                <p>
                  {{ sizeList.find((i) => i.value === detail.sizeType)?.name }}
                </p>
              </div>
              <!-- <div
                v-if="isJmpod === 'JMPOD'"
                :title="detail?.supplyMerchantCode"
                class="div-item"
              >
                <span>工厂</span>
                <p>{{ detail?.factoryCode || detail?.supplierCode }}</p>
              </div> -->
              <div :title="detail?.shopNumber" class="div-item">
                <span>店铺单号</span>
                <p>{{ detail?.shopNumber }}</p>
              </div>

              <!-- <div :title="detail?.shopShortName" class="div-item">
                <span>店铺简称</span>
                <p>{{ detail?.shopShortName }}</p>
              </div> -->

              <div :title="detail?.createTime" class="div-item">
                <span>创建时间</span>
                <p>{{ detail?.createTime }}</p>
              </div>
              <div :title="String(detail?.expectDeliveryTime)" class="div-item">
                <span>期望交货时间</span>
                <p>{{ detail?.expectDeliveryTime }}</p>
              </div>
              <div :title="String(detail?.startStockingTime)" class="div-item">
                <span>生产确认时间</span>
                <p>
                  {{ detail?.startStockingTime }}
                </p>
              </div>
            </div>
          </div>

          <div v-if="type !== 2" class="btn">
            <div class="btn-sure">
              <el-button
                v-if="type !== 0"
                style="width: 100%; height: 100%; font-size: 18px"
                size="large"
                type="success"
                @click="changeStatus"
              >
                {{ ['生产完成', '确定发货'][type - 1] }}
              </el-button>
              <div class="check">
                <el-checkbox v-if="type === 1" v-model="isAutoSure">
                  自动完成上一单
                </el-checkbox>
              </div>
            </div>
            <div class="btn-down">
              <div class="check">
                <el-checkbox v-model="isDownloadImage" size="large">
                  扫码下载素材
                </el-checkbox>
              </div>
              <el-button
                style="width: 100%; height: 100%; font-size: 18px"
                type="primary"
                @click="handleDownload"
              >
                下载素材
              </el-button>
            </div>
          </div>
          <div
            v-if="type !== 2"
            class="div-text"
            style="
              flex: 1;
              flex-shrink: 0;
              display: flex;
              flex-direction: column;
            "
          >
            <div v-if="detail?.note" style="height: 100%" class="div-content">
              <b style="position: absolute; top: -12px">客户留言信息</b>
              <div
                v-for="(item, index) in detail?.note"
                :key="index"
                class="div-item"
              >
                <span>{{ item.prop }}:</span>
                <p>
                  {{ item.value }}
                </p>
              </div>
            </div>
          </div>
          <div
            v-if="type === 2"
            class="div-text"
            style="
              flex: 1;
              flex-shrink: 0;
              display: flex;
              flex-direction: column;
            "
          >
            <div style="height: 100%" class="div-content">
              <b style="position: absolute; top: -12px">本次发货数量</b>
              <div
                class="div-item"
                style="
                  display: flex;
                  align-items: center;
                  width: 100%;
                  height: 100%;
                  font-size: 40px;
                  justify-content: center;
                "
              >
                <h2 style="color: red; font-weight: bold">{{ sendNum }}</h2>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script setup lang="tsx">
import {
  productionQueryApi,
  getSubOrderBySubOrderNumber,
  downloadMaterialApi,
} from '@/api/podOrder'
import { PodOrderRes, ImageItemInter } from '@/types/api/podOrder'
import { showConfirm } from '@/utils/ui'
import { filePath } from '@/api/axios'
import { ref, watch, defineProps, nextTick, defineEmits } from 'vue'
interface HistoryDataItem {
  orderNumber: string
  type: number
  finished: boolean
}
const trackingNumberRef = ref(null)
// const shipForm = ref({ shipmentType: '1' })
// const logistics = ref([])
const historyData = ref<HistoryDataItem[]>([])
const placeholderText = ref('')
const sendNum = ref(0)
const isDownloadImage = ref(false)
const isAutoSure = ref(false)
const detail = ref<PodOrderRes>({
  id: -1,
  podOrderId: -1,
  imgList: [] as ImageItemInter[][],
})
const dialogVisible = ref(false)
// 尺码类型表
const sizeList = ref<{ name: string; value: number }[]>([
  { name: '正常码', value: 1 },
  { name: '大码', value: 2 },
])
// 通过import动态导入音频文件
const audios = {
  weight_warning: new URL('@/assets/audio/weight_warning.mp3', import.meta.url)
    .href,
  weight_success: new URL('@/assets/audio/weight_success.mp3', import.meta.url)
    .href,
  weight_repeat: new URL('@/assets/audio/weight_repeat.mp3', import.meta.url)
    .href,
  weight_search_error: new URL(
    '@/assets/audio/weight_search_error.mp3',
    import.meta.url,
  ).href,
  weight_search_success: new URL(
    '@/assets/audio/weight_search_success.mp3',
    import.meta.url,
  ).href,
}
const productInfo = ref({})
const TrackingNumber = ref('')
const props = defineProps({
  currentStatus: {
    default: 'IN_PRODUCTION',
    type: String,
  },
  title: {
    default: '',
    type: String,
  },
  type: {
    default: 0,
    type: Number,
  },
  detailVisible: {
    default: false,
    type: Boolean,
  },
  detailData: {
    default: null,
    type: Object,
  },
  isJmpod: {
    default: 'POD',
    type: String,
  },
})
const emit = defineEmits(['update:detailVisible', 'close', 'onSuccess'])

watch(
  () => props.detailVisible,
  (newVal: boolean) => {
    dialogVisible.value = newVal
    if (newVal) {
      const history = localStorage.getItem('historyData')
      historyData.value = history ? JSON.parse(history) : []
      historyData.value.forEach((el: HistoryDataItem) => {
        el.type = Number(el.type)
      })
      const len = historyData.value.filter(
        (el: HistoryDataItem) => el.type === props.type,
      )
      if (len.length > 0) {
        confirmQuery(len, 0)
      }
      TrackingNumber.value = ''
      isAutoSure.value = false
      if (props.type === 1) {
        placeholderText.value =
          '扫描枪输入第三方订单号，录入下一单本单自动生产完成，最后一单扫两次完成生产'
      } else if (props.type === 2) {
        placeholderText.value =
          '扫描枪输入第三方订单号，录入下一单本单自动发货完成，最后一单扫两次完成发货'
      }
      sendNum.value = 0
      // canlogisticsList('GNKD').then((res) => {
      //   logistics.value = res.data[0].logisticsWayList
      // })
      // shipForm.value = { shipmentType: '1' }
      nextTick(() => {
        if (trackingNumberRef.value) {
          ;(trackingNumberRef.value as HTMLInputElement).focus()
        }
      })
    }
  },
)
watch(
  () => props.detailData,
  (newVal) => {
    detail.value = {
      id: -1,
      podOrderId: -1,
      imgList: [],
    }
    if (newVal && Object.keys(newVal).length > 0) {
      const d = JSON.parse(JSON.stringify(newVal))
      if (d.note) {
        d.note = JSON.parse(d.note)
      } else {
        d.note = []
      }
      let arr = []
      if (!d.imageAry) {
        arr = [
          { url: d.variantImage, title: '正面', id: d.designId },
          { url: d.negativeImage, title: '反面', id: d.negativeDesignId },
        ].filter((el) => el.url)
      } else {
        arr = Array.isArray(d.imageAry)
          ? d.imageAry
          : typeof d.imageAry === 'string'
          ? (() => {
              try {
                const parsed = JSON.parse(d.imageAry)
                return parsed
              } catch {
                return [{ url: d.imageAry }]
              }
            })()
          : [d.imageAry]?.filter?.((v) => v != null) || []
        // arr =
        //   typeof d.imageAry == 'string' ? JSON.parse(d.imageAry) : d.imageAry
        arr = arr.concat([
          { url: d.negativeImage, title: '反面', id: d.negativeDesignId },
        ])
      }
      arr = arr.filter((el: ImageItemInter) => el.url)
      arr = arr.map((el: ImageItemInter) => {
        return {
          ...el,
          ...{
            url: el.url.includes('http')
              ? el.url
              : window.location.origin + '/upload/erp' + el.url,
          },
        }
      })
      arr = arr.filter((el: ImageItemInter) => el.url)
      const result = []
      for (let i = 0; i < arr.length; i += 2) {
        result.push(arr.slice(i, i + 2))
      }
      d.imgList = result as ImageItemInter[][]
      detail.value = d
    }
    console.log(newVal, 'detail.value', detail.value)
  },
  { deep: true },
)
const confirmQuery = (len: HistoryDataItem[], i: number) => {
  const el = len[i]
  showConfirm(
    `生产单号 ${el.orderNumber} 未${
      el.type === 1 ? '生产完成' : '确定发货'
    }，取消则不提醒?`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(async () => {
      TrackingNumber.value = el.orderNumber
      await trackcodeInput()
      await setData(el.orderNumber)
      ElMessage.success(el.type === 1 ? '生产完成' : '确定发货')
      if (len[i + 1]) {
        confirmQuery(len, i + 1)
      }
    })
    .catch(() => {
      const index = historyData.value.findIndex(
        (item: HistoryDataItem) =>
          item.orderNumber === el.orderNumber && item.type === props.type,
      )
      if (index >= 0) {
        historyData.value.splice(index, 1)
        localStorage.setItem('historyData', JSON.stringify(historyData.value))
      }
      if (len[i + 1]) {
        confirmQuery(len, i + 1)
      }
    })
}

const changeStatus = async () => {
  if (!detail.value || Object.keys(detail.value).length <= 1) {
    return ElMessage.warning('请扫码生产单号')
  }
  showConfirm(`确定${props.type === 1 ? '生产完成' : '确定发货'}？`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    setData(detail.value.factorySubOrderNumber || '')
  })
}
const setData = async (orderNumber: string) => {
  if (detail.value && detail.value?.id != -1) {
    try {
      const id = detail.value?.id
      await productionQueryApi(id)
      if (props.type === 2) {
        sendNum.value = sendNum.value + 1
      }
      if (orderNumber) {
        const index = historyData.value.findIndex(
          (el: HistoryDataItem) =>
            el.type === props.type && el.orderNumber === orderNumber,
        )
        if (index >= 0) {
          // 扫单完成删除
          historyData.value.splice(index, 1)
          localStorage.setItem('historyData', JSON.stringify(historyData.value))
        }
      }
      emit('onSuccess')
      playAudio('weight_success')
      detail.value = { id: -1, podOrderId: -1, imgList: [] }
    } catch (e) {
      console.error(e)
      detail.value = { id: -1, podOrderId: -1, imgList: [] }
      playAudio('weight_search_error')
    }
  }
}

const handleDownload = () => {
  if (!detail.value || Object.keys(detail.value).length <= 1) {
    return ElMessage.warning('请扫码生产单号')
  }
  download()
}
const download = async () => {
  if (detail.value && detail.value?.id != -1) {
    try {
      const id = detail.value.id
      if (id !== undefined) {
        const res = await downloadMaterialApi([id])
        const { data } = res
        data.forEach((item: string) => {
          // window.open(filePath + item)
          const a = document.createElement('a')
          a.href = filePath + item
          a.download = item
          a.target = '_blank'
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        })
      }
    } catch (e) {
      // showError(e)
      console.error(e)
    }
  }
}
type AudioKey = keyof typeof audios // 创建一个类型，确保 key 只能是 audios 对象的键之一
const playAudio = (key: AudioKey, message?: string) => {
  let text = ''
  switch (key) {
    case 'weight_search_success':
      text = ''
      break
    case 'weight_search_error':
      text = '请录入生产单号'
      break
    case 'weight_success':
      text = ''
      break
    case 'weight_repeat':
      text = '称重复录入'
      break
    default:
      text = '请录入跟踪号或重量'
      break
  }
  if (message || text) ElMessage.warning(message || text)
  const audio = new Audio()
  if (audios[key]) {
    audio.src = audios[key] // 获取对应 key 的音频路径
    audio.play().catch((err) => console.error('Audio play failed:', err)) // 捕获音频播放失败的错误
  } else {
    console.error(`No audio found for key: ${key}`)
  }
}
// 上一单数据
const lastOrderNumber = ref('')
const trackcodeInput = async () => {
  if (!TrackingNumber.value) {
    // ElMessage.warning('请扫描生产单号')
    playAudio('weight_search_error')
    return
  }
  const item = historyData.value.find(
    (el: HistoryDataItem) =>
      el.orderNumber === TrackingNumber.value && el.type === props.type,
  )
  if (!item) {
    // 记录扫单
    historyData.value.push({
      orderNumber: TrackingNumber.value,
      type: props.type,
      finished: false,
    })
    localStorage.setItem('historyData', JSON.stringify(historyData.value))
  }

  const orderNumber = TrackingNumber.value
  TrackingNumber.value = ''
  if (props.type === 1) {
    if (isAutoSure.value) {
      await setData(lastOrderNumber.value)
      lastOrderNumber.value = orderNumber
    }
  } else {
    await setData(orderNumber)
  }
  // AAAB_60527128-9_1_JMSC250121017 新版示例
  // const regex = /^[A-Z]{4}_/ //是否以四个大写字母加下划线开头
  // if (regex.test(orderNumber)) {
  //   orderNumber =
  //     orderNumber.split('_')[0] +
  //     '-' +
  //     orderNumber.split('_')[orderNumber.split('_').length - 1]
  // }
  try {
    const res = await getSubOrderBySubOrderNumber(orderNumber)
    if (!res.data) {
      return ElMessage.error('生产单不存在')
    }
    const d = JSON.parse(JSON.stringify(res.data))

    if (d.note) {
      d.note = JSON.parse(d.note)
    } else {
      d.note = []
    }
    let arr = []
    if (!d.imageAry) {
      arr = [
        { url: d.variantImage, title: '正面', id: d.designId },
        { url: d.negativeImage, title: '反面', id: d.negativeDesignId },
      ].filter((el) => el.url)
    } else {
      arr = Array.isArray(d.imageAry)
        ? d.imageAry
        : typeof d.imageAry === 'string'
        ? (() => {
            try {
              const parsed = JSON.parse(d.imageAry)
              return parsed
            } catch {
              return [{ url: d.imageAry }]
            }
          })()
        : [d.imageAry]?.filter?.((v) => v != null) || []

      // arr = typeof d.imageAry == 'string' ? JSON.parse(d.imageAry) : d.imageAry
      arr = arr.concat([
        { url: d.negativeImage, title: '反面', id: d.negativeDesignId },
      ])
      arr.forEach((item: { url: string; id: string; title: string }) => {
        if (item.url && item.url.startsWith('/')) {
          item.url = 'https://img.jomalls.com/upload/erp' + item.url
        }
      })
    }
    const result = []
    arr = arr.filter((el: ImageItemInter) => el.url)
    arr = arr.map((el: ImageItemInter) => {
      return {
        ...el,
        ...{
          url: el.url.includes('http')
            ? el.url
            : window.location.origin + '/upload/erp' + el.url,
        },
      }
    })

    for (let i = 0; i < arr.length; i += 2) {
      result.push(arr.slice(i, i + 2))
    }
    d.imgList = result
    detail.value = d
    if (detail.value?.importFactory) {
      ElMessage.warning('只支持自有工厂的订单')
      return
    }
    if (isDownloadImage.value) {
      download()
    }
    playAudio('weight_search_success')
    nextTick(() => {
      if (trackingNumberRef.value) {
        ;(trackingNumberRef.value as HTMLInputElement).focus()
      }
    })
  } catch (e) {
    console.error(e)
    productInfo.value = {}
    nextTick(() => {
      if (trackingNumberRef.value) {
        ;(trackingNumberRef.value as HTMLInputElement).focus()
      }
    })
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  box-sizing: border-box;
  flex: 1;
  flex-shrink: 0;
  overflow: hidden;
}

::v-deep .el-dialog {
  display: flex;
  height: calc(100% - 50px);
  margin-top: 50px;
  flex-direction: column;
}

.sure-btn {
  position: absolute;
  right: 62px;
  top: 14px;
}

.detail-div {
  display: flex;
  height: 100%;
  flex-direction: column;
  justify-content: space-between;

  .detail-images {
    .scroll-list {
      background: #ececec;
      display: flex;
      height: 100px;
      width: 100%;
      padding: 5px;

      .scroll-content {
        margin-left: 10px;
        overflow-x: auto;
        overflow-y: hidden;
        flex: 1;
        display: flex;
        flex-wrap: nowrap;
        flex-shrink: 0;

        .scroll-item {
          height: 100%;
          min-width: 100px;
          background: white;
          margin-right: 5px;
        }
      }

      .img-title {
        display: flex;
        flex-direction: column;
        justify-content: center;
        background: white;
        padding: 10px;

        b {
          text-align: center;
          color: black;
          font-weight: bold;
          font-size: 16px;
          margin-bottom: 15px;
        }

        .id {
          display: flex;
          align-items: center;
          padding: 3px 5px;
          background: #ececec;
          justify-content: center;

          img {
            width: 15px;
            margin-right: 8px;
          }
        }
      }
    }
  }

  .detail-content {
    display: flex;
    width: 100%;
    flex: 1;
    margin-bottom: 10px;
    flex-shrink: 0;
    justify-content: space-between;
  }

  .right {
    width: 730px;
    height: 100%;
    display: flex;
    flex-direction: column;

    .btn {
      margin: 20px 0;
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 50px;
      width: 100%;

      .btn-sure,
      .btn-down {
        width: 49%;
        position: relative;

        .check {
          position: absolute;
          width: 144px;
          height: 100%;
          background: transparent;
          display: flex;
          align-items: center;
          justify-content: center;
          right: 0;
          top: 1px;
        }
      }
    }

    .div-text {
      .div-content {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        align-items: flex-start;
        padding: 15px 10px;
        box-sizing: border-box;

        .div-item {
          width: 50%;
          margin-bottom: 10px;
          display: flex;
          align-items: center;

          p {
            font-weight: 400;
            color: black;
          }

          span {
            display: inline-block;
            text-align: right;
            width: 120px;
          }

          span::after {
            content: ':';
            margin: 0 3px;
          }
        }
      }

      b {
        position: relative;
        background: white;
        top: 9px;
        left: 13px;
        padding: 0 10px;
        font-size: 18px;
        color: black;
        z-index: 3;
      }

      .div-content {
        position: relative;
        border: 1px solid #ececec;
      }
    }

    .input {
      display: flex;
      align-items: center;
      margin: 30px 0;
    }
  }

  .left {
    flex: 1;
    flex-shrink: 0;
    margin-right: 20px;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;

    .left-image {
      display: flex;
      height: 100%;
      flex-direction: column;
      justify-content: center;

      img {
        height: auto;
        width: 100%;
        max-height: 90%;
      }

      b {
        color: black;
        font-size: 18px;
        margin-bottom: 15px;
      }
    }

    .left-images {
      display: flex;
      width: 95%;
      height: 100%;
      flex-direction: column;

      b {
        color: black;
        text-align: center;
        margin-bottom: 15px;
      }
    }
  }
}

::v-deep .el-carousel__container {
  height: 100%;
}

::v-deep .el-form-item__label {
  font-weight: bold;
  color: white;
}

::v-deep .el-dialog__title {
  font-weight: bold;
  font-size: 37px;
  color: black;
  position: relative;
  left: 47%;
  top: 13px;
}

.btn {
  position: relative;

  ::v-deep .el-button {
    span {
      position: relative;
      left: -30px;
    }
  }

  .check {
    ::v-deep .el-checkbox__inner {
      background-color: transparent !important;
      border-color: white !important;
      width: 12px;
      height: 12px;
    }

    ::v-deep .el-checkbox__inner::after {
      left: 3px;
    }

    ::v-deep .el-checkbox__label {
      padding-left: 5px;
      font-size: 12px;
      color: white !important;
    }
  }
}
.warning {
  font-size: 18px;
  font-weight: bold;
  color: #ff9900;
  margin-left: 10px;
  cursor: pointer;
}
</style>
