<template>
  <!-- 右侧工具栏 -->
  <div class="tool_warper">
    <div title="格式工具" class="tool-item" @click="formatDrawer = true">
      <img src="../assets/images/brush-no.png" width="24" height="24" />
    </div>
    <div
      title="打印物流面单"
      class="tool-item"
      @click="getLogisticDrawer = true;isAutoPrint=false"
    >
      <img src="../assets/images/printer.png" width="24" height="24" />
    </div>
    <div
      title="生产单查询"
      class="tool-item"
      @click="searchVisible = true"
    >
      <img src="../assets/images/saoma.png" width="24" height="24" />
    </div>
  </div>

  <!-- 格式工具 -->
  <span>
    <el-drawer
      v-model="formatDrawer"
      class="format-drawer"
      title="格式工具"
      direction="rtl"
      size="45%"
    >
      <el-input
        v-model="textareaT"
        style="width: 100%"
        :rows="10"
        type="textarea"
        placeholder="请输入"
        @input="confimTools"
      />
      <div
        style="
          margin-top: 10px;
          height: 250px;
          overflow: auto;
          border: 1px solid #ddd;
          padding: 10px;
        "
      >
        {{ newTextareaT }}
      </div>
      <template #footer>
        <span style="display: flex; justify-content: center">
          <el-button @click="formatDrawer = false"> 取 消 </el-button>
          <el-button type="primary" @click="copy"> 拷 贝 </el-button>
        </span>
      </template>
    </el-drawer>
  </span>

  <!-- 打印物流面单 -->
  <span>
    <el-dialog
      v-model="getLogisticDrawer"
      class="get-logistic-dialog"
      title="打印物流面单"
      width="1300px"
      :before-close="
        () => {
          getLogisticDrawer = false
          content = ''
          tableData = {}
          productCount = null
        }
      "
    >
      <ElSelect
        v-model="sheetPrinter"
        placeholder="请选择打印机"
        style="width: 200px; margin-right: 10px"
        @change="handlePrinterChange"
      >
        <ElOption
          v-for="item in printDeviceList"
          :key="item"
          :label="item"
          :value="item"
        />
      </ElSelect>
      <el-input
        v-model="content"
        placeholder="请输入单号"
        style="width: 700px; margin-right: 10px"
        clearable
        @keyup.enter="getLogistic"
      />
      <el-button type="primary" @click="getLogistic">查 询</el-button>
      <el-button type="success" @click="printLogistic">打印面单</el-button>
      <el-checkbox v-model="isAutoPrint" :disabled="!printDeviceList" style="margin-left: 5px;position: relative;top: 5px" type="success" >自动打印面单</el-checkbox>
      <div style="font-size: 20px; margin: 20px 0px; color: #666666">
        <div style="margin-bottom: 10px; display: flex; gap: 20px">
          <div style="width: 400px">店铺单号: {{ tableData.shopNumber }}</div>
          <div>
            包含产品数:
            <span style="color: red">{{ tableData.purchaseNumber }}</span>
          </div>
        </div>
        <div>物流跟踪号: {{ tableData.trackingNumber }}</div>
      </div>
      <TableView :columns="tableColumns" :data="tableData.productList">
        <template #warehouseSkuImage="scope">
          <span
            style="
              display: flex;
              align-items: center;
              justify-content: center;
              gap: 10px;
            "
          >
            <img
              :src="scope.row.warehouseSkuImage"
              alt="商品图片"
              height="50"
              style="cursor: pointer"
              @click="handlePictureCardPreview(scope.row.warehouseSkuImage)"
            />
            <span
              class="mark-tag"
              :title="handleMark(scope.row.productMark).label"
              :style="{
                background: handleMark(scope.row.productMark).color,
                width: handleMark(scope.row.productMark).width || '20px',
              }"
            >
              {{ handleMark(scope.row.productMark).name }}
            </span>
          </span>
        </template>
      </TableView>
    </el-dialog>
  </span>
  <el-dialog v-model="searchVisible" title="生产单查询" width="100%" fullscreen>
    <SearchProductOrder v-if="searchVisible" />
  </el-dialog>
  <!-- 预览图片 -->
  <el-dialog v-model="dialogVisible" width="35%">
    <img :src="dialogImageUrl" alt="商品预览图片" />
  </el-dialog>
</template>
<script lang="ts" setup>
import SearchProductOrder from './searchProdOrder.vue'
import { ref, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {print} from './print.ts'
import useLodop from '@/utils/hooks/useLodop'
import { getLogisticUSApi, getLogisticCNApi } from '@/api/common'
import { filePath, FileCnPath } from '@/api/axios'
import { LogisticBill } from '@/types/api/podMakeOrder'

import TableView from '@/components/TableView.vue'

const formatDrawer = ref(false)
const searchVisible = ref(false)
const getLogisticDrawer = ref(false)

const textareaT = ref('')
const newTextareaT = ref('')
const content = ref('')

const printDeviceList = ref<string[]>([])
const sheetPrinter = ref('')

// 表格列配置
const tableColumns = computed(() => [
  {
    label: '图片',
    prop: 'warehouseSkuImage',
    align: 'center',
    width: 150,
    slot: 'warehouseSkuImage',
  },
  {
    label: '商品sku',
    prop: 'warehouseSku',
    align: 'center',
  },
  {
    label: '店铺sku',
    prop: 'shopSku',
    align: 'center',
  },
  {
    label: 'sku名称',
    prop: 'warehouseSkuName',
    align: 'center',
  },
  {
    label: '数量',
    prop: 'purchaseNumber',
    align: 'center',
    width: 80,
  },
  {
    label: '包裹号',
    prop: 'orderItemId',
    align: 'center',
  },
  {
    label: '生产单号',
    prop: 'podJomallNo',
    align: 'center',
  },
])

// 商品标记
const handleMark = (v: string) => {
  switch (v) {
    case 'virtual':
      return {
        name: 'VIR',
        color: '#ff9900',
        label: '虚拟商品',
      }
    case 'normal':
      return {
        name: 'G',
        color: '#67C23A',
        label: '普通商品',
      }
    case 'pod':
      return {
        name: 'P',
        color: '#F56C6C',
        label: 'pod商品',
      }
    case 'custom':
      return {
        name: 'C',
        color: '#6d9eeb',
        label: '一件定制商品',
      }
    case 'custom_part':
      return {
        name: 'CP',
        color: '#6d9eeb',
        label: '一件定制局部印商品',
      }
    case 'custom_full':
      return {
        name: 'CF',
        color: '#6d9eeb',
        label: '一件定制满印商品',
      }
    default:
      return {
        name: '',
        color: '#FFFFFF',
        width: '0',
      }
  }
}

// 格式工具输入格式化
const confimTools = (v: string) => {
  // 先处理结尾的多个空格，只保留一个
  let text = v.replace(/\s+$/, ' ')

  // 处理开头的多个空格，只保留一个
  text = text.replace(/^\s+/, ' ')

  // 将多个连续空格替换为单个空格
  text = text.replace(/\s+/g, ' ')

  // 然后将所有空格和换行符替换为逗号
  text = text.replace(/(\s|[\r\n])/g, ',')

  // 如果结尾是逗号，则删除
  if (text.slice(-1) === ',') {
    newTextareaT.value = text.slice(0, -1)
  } else {
    newTextareaT.value = text
  }
}

// 复制
const copy = () => {
  const oInput = document.createElement('input')
  oInput.value = newTextareaT.value
  document.body.appendChild(oInput)
  oInput.select() // 选择对象
  document.execCommand('Copy') // 执行浏览器复制命令
  oInput.className = 'oInput'
  oInput.style.display = 'none'
  document.body.removeChild(oInput)
  ElMessage({
    message: '复制成功',
    type: 'success',
  })
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
// 放大图片
const handlePictureCardPreview = (fileUrl: string) => {
  dialogImageUrl.value = fileUrl
  dialogVisible.value = true
}

const { getCLodop } = useLodop()

// 初始化打印机
const initPrintDevice = () => {
  const lodop = getCLodop(null, null)
  if (!lodop) {
    printDeviceList.value = []
    return
  }

  try {
    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) {
      sheetPrinter.value = defaultPrinter
    }
    printDeviceList.value = arr
  } catch (error) {
    console.error('初始化打印机失败:', error)
    printDeviceList.value = []
  }
}

// 处理打印机选择变化，保存到 localStorage
const handlePrinterChange = (value: string) => {
  sheetPrinter.value = value
  localStorage.setItem('sheetPrinter', JSON.stringify(value))
}

const tableData = ref<LogisticBill>({})
const productCount = ref<number | null>(null)
const isAutoPrint = ref(false)
const type = ref('')

// 查询并打印物流面单
const getLogistic = () => {
  content.value = content.value.trim()
  if (!content.value) {
    ElMessage.warning('请输入单号')
    return
  }
  // 按_分割字符串
  const parts = content.value.split('_')
  // 检查是否有足够的_分隔符
  if (parts.length < 4) {
    ElMessage.error('单号格式错误，请检查输入')
    return
  }
  // 获取第三个_后面的内容
  type.value = parts[3]

  if (type.value.startsWith('USPSC')) {
    // 美国物流
    getLogisticUSApi(content.value).then((res) => {
      if (res.code === 200) {
        tableData.value = res.data
        productCount.value = tableData.value.productList?.length || 0
        if(isAutoPrint.value) printLogistic()
        // window.open(filePath + tableData.value.expressSheet, '_blank')
      }
    })
  } else if (type.value.startsWith('JMPSC')) {
    // 中国物流
    getLogisticCNApi(content.value).then((res) => {
      if (res.code === 200) {
        tableData.value = res.data
        productCount.value = tableData.value.productList?.length || 0
        if(isAutoPrint.value) printLogistic()
        // window.open(FileCnPath + tableData.value.expressSheet, '_blank')
      }
    })
  } else {
    ElMessage.error('单号格式错误，请检查输入')
  }
}

// 手动打印面单
const printLogistic = () => {
  if (!tableData.value.expressSheet) {
    ElMessage.warning('请先查询面单')
    return
  }
  if(!sheetPrinter.value){
    ElMessage.warning('请选择打印机')
    return
  }
  const path =  type.value.startsWith('USPSC')?filePath :FileCnPath
  // let path =  'http://10.168.31.142:80/upload/factory'
  print(path + tableData.value.expressSheet,sheetPrinter.value)
}

// 监听打印机状态
watch(getLogisticDrawer, async (value: boolean) => {
  if (value) {
    initPrintDevice()
    const locaclPrinter = localStorage.getItem('sheetPrinter')
    if (
      locaclPrinter &&
      Array.isArray(printDeviceList.value) &&
      printDeviceList.value.length > 0
    ) {
      try {
        const savedPrinter = JSON.parse(locaclPrinter)
        // 检查保存的打印机是否在当前打印机列表中
        if (printDeviceList.value.includes(savedPrinter)) {
          sheetPrinter.value = savedPrinter
        } else {
          // 如果保存的打印机不在当前列表中，清空 localStorage 并设置为空
          localStorage.removeItem('sheetPrinter')
          sheetPrinter.value = ''
        }
      } catch (error) {
        console.error('解析保存的打印机信息失败:', error)
        localStorage.removeItem('sheetPrinter')
        sheetPrinter.value = ''
      }
    }
  }
})
</script>

<style lang="scss" scoped>
.tool_warper {
  position: absolute;
  top: 50px;
  right: 0;
  bottom: 0;
  width: 40px;
  background: #001529;
  z-index: 999;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

// 格式工具
::v-deep(.format-drawer.el-drawer.rtl) {
  height: 650px !important;
  right: 40px;
  top: calc(50% - 325px) !important;
}

// 打印物流面单
::v-deep(.el-dialog.get-logistic-dialog) {
  height: 700px !important;
  padding: 30px;
}

.tool-item {
  width: 24px;
  height: 24px;
  cursor: pointer;
  margin-bottom: 10px;
}

.mark-tag {
  display: inline-block;
  background: #f56c6c;
  width: 20px;
  height: 20px;
  border-radius: 11px;
  line-height: 20px;
  color: white;
}
</style>
