<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 from '@/utils/hooks/useLodop.ts'
import { ElMessage } from 'element-plus'
import { filePath } from '@/api/axios.ts'
import {print} from '@/components/print.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 searchData = 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 getPrintData = async () => {
  if(!searchData.value) return
  const user = JSON.parse(localStorage.getItem('user') || '{}')
  const data = await printProductionQrCode(
    searchData.value.id,
    user.factory?.countryCode.toLowerCase(),
  )
  // const path = 'http://10.168.1.209/local_files/factory' + data.message
  const path = filePath + data.message
  print(path, printDevice.value)
}
const trackcodeInput = async () => {
  if (!TrackingNumber.value) {
    // ElMessage.warning('请扫描生产单号')
    playAudio('weight_search_error')
    return
  }
  // 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('生产单不存在')
    }
    searchData.value = res.data
    if (printDevice.value && isPrint.value) {
      getPrintData()
    }

    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 printPdf = () => {
  if(!printDevice.value) return ElMessage.warning('请选择打印机')
  if(!searchData.value) return ElMessage.warning('请先查询生产单')
  getPrintData()
}

// 处理打印机选择变化，保存到 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-button style="margin-left: 5px" type="primary" @click="printPdf">打印生产码</el-button>
          <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>
