<script setup lang="ts">
import { getSubOrderBySubOrder, printProductionQrCode } from '@/api/podOrder.ts'
import { SearchOrderRes } from '@/types/api/podOrder.ts'
import { nextTick, ref } from 'vue'
import { DocumentCopy } from '@element-plus/icons-vue'
import { copyText } from '@/utils'
import useLodop, { LODOPObject } from '@/utils/hooks/useLodop.ts'
import { ElMessage } from 'element-plus'
import { filePath } from '@/api/axios.ts'

const { getCLodop } = useLodop()
const type = {
  A: '正面',
  B: '反面',
  C: '左边',
  D: '右边',
}
const imageList = ref<
  {
    sort: number
    title?: 'A' | 'B' | 'C' | 'D'
    url?: string
  }[]
>([])
const detail = ref<SearchOrderRes>({
  imgList: [],
  id: 0,
})
const printDevice = ref('')
const isPrint = ref(false)
const printList = ref<string[]>([])
type AudioKey = keyof typeof audios // 创建一个类型，确保 key 只能是 audios 对象的键之一
const TrackingNumber = ref('')
const trackingNumberRef = ref(null)
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 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 trackcodeInput = async () => {
  if (!TrackingNumber.value) {
    // ElMessage.warning('请扫描生产单号')
    playAudio('weight_search_error')
    return
  }
  const user = JSON.parse(localStorage.getItem('user') || '{}')

  // let orderNumber: string

  // const underscoreCount = (TrackingNumber.value.match(/_/g) || []).length

  // if (underscoreCount >= 3) {
  //   orderNumber = TrackingNumber.value.split('_')[3]
  // } else {
  //   orderNumber = TrackingNumber.value
  // }

  try {
    const res = await getSubOrderBySubOrder(
      TrackingNumber.value
    )
    if (!res.data) {
      return ElMessage.error('生产单不存在')
    }
    if (printDevice.value && isPrint.value) {
      const data = await printProductionQrCode(
        res.data.id,
        user.factory?.countryCode.toLowerCase(),
      )
      // const path = 'http://10.168.1.209/local_files/factory' + data.message
      const path = filePath + data.message
      print(path)
    }
    res.data.inputNum = TrackingNumber.value
    TrackingNumber.value = ''
    if (typeof res.data.imageAry === 'string') {
      imageList.value = JSON.parse(res.data.imageAry)
    } else {
      imageList.value = []
    }
    const d = JSON.parse(JSON.stringify(res.data))

    if (d.note) {
      d.note = JSON.parse(d.note)
    } else {
      d.note = []
    }
    detail.value = d

    playAudio('weight_search_success')
    nextTick(() => {
      if (trackingNumberRef.value) {
        ;(trackingNumberRef.value as HTMLInputElement).focus()
      }
    })
  } catch (e) {
    console.error(e)
    nextTick(() => {
      if (trackingNumberRef.value) {
        ;(trackingNumberRef.value as HTMLInputElement).focus()
      }
    })
  }
}

// 初始化打印机
const initPrintDevice = () => {
  const lodop = getCLodop(null, null)
  if (!lodop) {
    printList.value = []
    return
  }
  const arr = []
  // 获取打印机数量
  const length = lodop.GET_PRINTER_COUNT()
  for (let i = 0; i < length; i++) {
    // 根据设备序号获取设备名
    const name = lodop.GET_PRINTER_NAME(i)
    if (name) {
      arr.push(name)
    }
  }
  // 获取默认打印机
  // const defaultPrinter = lodop.GET_PRINTER_NAME(0)
  // if (defaultPrinter) {
  //   // printDevice.value = defaultPrinter
  // }
  printList.value = arr
}

const lodopCall = async (fn: (lodop: LODOPObject) => string) => {
  if (!window._lodop) {
    window._lodop = getCLodop(null, null)
    if (window._lodop) {
      window._lodop.On_Return_Remain = true
      window._lodop.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
      window._lodopCallback = {}
      window._lodop.On_Return = function (id, value) {
        const cb = window._lodopCallback[id]
        if (!cb) return
        delete window._lodopCallback[id]
        cb(value)
      }
    }
  }

  return new Promise((resolve) => {
    let id
    if (window._lodop) {
      id = fn(window._lodop)
    }
    window._lodopCallback[id || 0] = resolve
  })
}

function downloadPDF(url: string) {
  if (!/^https?:/i.test(url)) return url
  let xhr,
    arrybuffer = false,
    dataArray = null
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest()
  } else {
    xhr = new window.ActiveXObject('MSXML2.XMLHTTP')
  }
  xhr.open('GET', url, false) //同步方式
  if (xhr.overrideMimeType)
    try {
      xhr.responseType = 'arraybuffer'
      arrybuffer = true
    } catch (err) {
      xhr.overrideMimeType('text/plain; charset=x-user-defined')
    }
  xhr.send(null)
  const data = xhr.response || xhr.responseBody
  if (typeof Uint8Array !== 'undefined') {
    if (arrybuffer) {
      dataArray = new Uint8Array(data)
    } else {
      dataArray = new Uint8Array(data.length)
      for (let i = 0; i < dataArray.length; i++) {
        dataArray[i] = data.charCodeAt(i)
      }
    }
  } else {
    dataArray = window.VBS_BinaryToArray(data).toArray() //兼容IE低版本
  }
  const digits =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  let strData = ''
  for (let i = 0, ii = dataArray.length; i < ii; i += 3) {
    if (isNaN(dataArray[i])) break
    const b1 = dataArray[i] & 0xff,
      b2 = dataArray[i + 1] & 0xff,
      b3 = dataArray[i + 2] & 0xff
    const d1 = b1 >> 2,
      d2 = ((b1 & 3) << 4) | (b2 >> 4)
    const d3 = i + 1 < ii ? ((b2 & 0xf) << 2) | (b3 >> 6) : 64
    const d4 = i + 2 < ii ? b3 & 0x3f : 64
    strData +=
      digits.substring(d1, d1 + 1) +
      digits.substring(d2, d2 + 1) +
      digits.substring(d3, d3 + 1) +
      digits.substring(d4, d4 + 1)
  }
  return strData
}

const print = async (url: string) => {
  const lodop = getCLodop(null, null) //调用getLodop获取LODOP对象
  if (!lodop) return
  lodop.PRINT_INIT('打印内容')
  // SET_PRINTER_INDEX 指定打印设备
  const setPrintRes = lodop.SET_PRINTER_INDEX(printDevice.value)
  if (!setPrintRes) {
    ElMessage.warning('设置面单打印机出错')
    return
  }
  lodop.ADD_PRINT_PDF(0, 0, '100%', '100%', downloadPDF(url))
  console.log(lodop)
  if (lodop.CVERSION) {
    const startTime = Date.now()
    const jobCode = await lodopCall((lodop: LODOPObject) => {
      lodop.SET_PRINT_MODE('CATCH_PRINT_STATUS', true)
      return lodop.PRINT()
    })

    console.log('[LODOP] job ' + jobCode)
    // eslint-disable-next-line no-constant-condition
    while (true) {
      const ok = await lodopCall((lodop: LODOPObject) =>
        lodop.GET_VALUE('PRINT_STATUS_OK', jobCode),
      )
      if (ok == 1) {
        // 打印状态：成功
        return
      }
      // 如果打印状态表示未成功或者返回了空，继续获取任务是否存在
      const exist = await lodopCall((lodop: LODOPObject) =>
        lodop.GET_VALUE('PRINT_STATUS_EXIST', jobCode),
      )
      console.log(
        '[LODOP] PRINT_STATUS OK,EXIST',
        jobCode,
        ok,
        exist,
        `(${Date.now() - startTime}ms)`,
      )
      if (exist == 0) {
        // 任务不存在了
        return
      }

      await new Promise((r) => setTimeout(r, 500))
      if (Date.now() - startTime >= 30000) {
        ElMessage.error('打印超时(30秒)')
        return
      }
    }
  } else {
    lodop.PRINT()
  }
}
// 处理打印机选择变化，保存到 localStorage
const handlePrinterChange = (value: string) => {
  printDevice.value = value
  if (!value) isPrint.value = false
}

onMounted(() => {
  initPrintDevice()
})
</script>

<template>
  <div class="detail-div">
    <div class="detail-content">
      <div class="left">
        <div v-if="imageList.length > 0" class="left-images">
          <div v-for="(item, index) in imageList" :key="index" class="img-box">
            <b v-if="item.title">{{ item.title }}({{ type[item.title] }})</b>
            <img :src="item.url" alt="" />
          </div>
        </div>
      </div>
      <div class="right">
        <div class="input">
          <el-input
            ref="trackingNumberRef"
            v-model="TrackingNumber"
            placeholder="扫描枪输入第三方订单号"
            style="width: 660px; margin-right: 10px"
            clearable
            @keydown.enter="trackcodeInput()"
          ></el-input>
          <el-button
            style="width: 138px"
            type="primary"
            @click="trackcodeInput()"
          >
            查询
          </el-button>
        </div>
        <div class="input">
          <el-select
            v-model="printDevice"
            placeholder="请选择打印机"
            clearable
            filterable
            @change="handlePrinterChange"
          >
            <el-option
              v-for="(item, i) in printList"
              :key="i"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
          <el-checkbox
            v-model="isPrint"
            :disabled="!printDevice"
            style="margin-left: 10px"
            >打印生产码</el-checkbox
          >
        </div>
        <div class="div-text">
          <b>生产单信息</b>
          <div class="div-content">
            <h2
              style="
                text-align: center;
                color: black;
                font-size: 16px;
                width: 100%;
              "
            >
              {{ detail.inputNum }}
            </h2>
            <div :title="detail?.factorySubOrderNumber" class="div-item">
              <span>生产单号</span>
              <p>
                {{ detail?.factorySubOrderNumber }}
              </p>
              <el-icon
                v-if="detail?.factorySubOrderNumber"
                class="copy"
                style="cursor: pointer"
                @click="copyText(detail.factorySubOrderNumber)"
              >
                <DocumentCopy />
              </el-icon>
            </div>
            <div :title="detail?.shopNumber" class="div-item">
              <span>店铺单号</span>
              <p>{{ detail?.shopNumber }}</p>
              <el-icon
                v-if="detail?.shopNumber"
                class="copy"
                style="cursor: pointer"
                @click="copyText(detail.shopNumber)"
              >
                <DocumentCopy />
              </el-icon>
            </div>
            <div :title="detail?.thirdSubOrderNumber || ''" class="div-item">
              <span>第三方生产单号</span>
              <p>
                {{ detail?.thirdSubOrderNumber }}
              </p>
              <el-icon
                v-if="detail?.thirdSubOrderNumber"
                class="copy"
                style="cursor: pointer"
                @click="copyText(detail.thirdSubOrderNumber)"
              >
                <DocumentCopy />
              </el-icon>
            </div>
            <div :title="String(detail?.process)" class="div-item">
              <span>生产工艺</span>
              <p>
                {{ detail?.craftName }}
              </p>
            </div>
            <div :title="detail?.createTime" class="div-item">
              <span>创建时间</span>
              <p>{{ detail?.createTime }}</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="String(detail?.size)" class="div-item">
              <span>尺寸</span>
              <p>{{ detail?.size }}</p>
            </div>
            <!--            <div :title="detail?.variantSku" class="div-item">-->
            <!--              <span>变体SKU</span>-->
            <!--              <p>{{ detail?.variantSku }}</p>-->
            <!--            </div>-->
            <div :title="String(detail?.faceCount)" class="div-item">
              <span>打印面数</span>
              <p v-if="detail?.num || imageList.length" style="color: red">
                {{ detail?.faceCount }}({{
                  imageList.map((el) => el.title).join('+')
                }})
              </p>
            </div>
          </div>
        </div>
        <div
          class="div-text"
          style="
            flex: 1;
            margin-top: 15px;
            flex-shrink: 0;
            display: flex;
            flex-direction: column;
          "
        >
          <div 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>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.copy {
  font-weight: bold;
  margin-left: 5px;
}

::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: 92vh;
  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: 500px;
    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;
        text-align: center;

        .div-item {
          width: 100%;
          margin-bottom: 10px;
          display: flex;
          align-items: center;
          font-size: 16px !important;

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

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

          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: 15px 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%;
      gap: 10px;
      justify-content: center;

      .img-box {
        display: flex;
        flex-direction: column;
        gap: 10px;
        width: 50%;
        height: 100%;

        b {
          font-size: 26px;
          font-weight: normal;
        }

        img {
          flex: 1;
          flex-shrink: 0;
          object-fit: cover;
          overflow: hidden;
        }
      }

      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>
