<template>
  <div class="mod-config">
    <el-form :inline="true" label-position="top">
      <el-form-item label="入库状态">
        <el-select v-model="queryHeaderData.inStockFlag" placeholder="请选择" style="width: 120px;">
          <el-option label="全部" value=""></el-option>
          <el-option label="未入库" value="X"></el-option>
          <el-option label="已出库" value="N"></el-option>
          <el-option label="在库" value="Y"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="物料编号">
        <el-input style="width: 120px;" v-model="queryHeaderData.partNo" placeholder="请输入物料编号" @keyup.enter.native="getDataList()"></el-input>
      </el-form-item>
      <el-form-item label="批次号">
        <el-input style="width: 120px;" v-model="queryHeaderData.batchNo" placeholder="请输入批次号" @keyup.enter.native="getDataList()"></el-input>
      </el-form-item>
      <el-form-item label="库位">
        <el-input style="width: 120px;" v-model="queryHeaderData.locationId" placeholder="请输入库位" @keyup.enter.native="getDataList()"></el-input>
      </el-form-item>
      <el-form-item label="标签号">
        <el-input style="width: 120px;" v-model="queryHeaderData.unitId" placeholder="请输入标签号" @keyup.enter.native="getDataList()"></el-input>
      </el-form-item>
      <el-form-item label="物料描述">
        <el-input style="width: 120px;" v-model="queryHeaderData.partDesc" placeholder="请输入物料描述" @keyup.enter.native="getDataList()"></el-input>
      </el-form-item>
      <el-form-item style="margin-top: 20px;">
        <el-button @click="getDataList()" type="primary">查询</el-button>
        <el-button @click="resetQuery()" type="default">重置</el-button>
        <el-button @click="showOtherInboundDialog()" type="success">其它入库标签打印</el-button>
        <el-button @click="showFailedPrintTasksDialog()" type="warning">失败打印任务重试</el-button>
        <!-- 导出按钮 - rqrq -->
        <download-excel
          :fields="fields()"
          :data="exportData"
          type="xls"
          :name="exportName"
          :header="exportHeader"
          :footer="exportFooter"
          :fetch="createExportData"
          :before-generate="startDownload"
          :before-finish="finishDownload"
          worksheet="导出信息"
          class="el-button el-button--primary el-button--medium">
          {{ '导出' }}
        </download-excel>
      </el-form-item>
    </el-form>

    <el-table
      id="labelQueryTable"
      :height="height"
      :data="dataList"
      border
      v-loading="dataListLoading || printLoading"
      :element-loading-text="loadingText"
      style="width: 100%; margin-bottom: 15px;">

      <!-- 动态列配置 - rqrq -->
      <el-table-column
        v-for="(item,index) in columnList" :key="index"
        :sortable="item.columnSortable"
        :prop="item.columnProp"
        :header-align="item.headerAlign"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :align="item.align"
        :fixed="item.fixed==''?false:item.fixed"
        :min-width="item.columnWidth"
        :label="item.columnLabel">
        <template slot-scope="scope">
          <span v-if="item.columnProp === 'inStockFlag'">
            <span v-if="scope.row.inStockFlag === 'Y'" type="success">在库</span>
            <span v-else-if="scope.row.inStockFlag === 'N'" type="info">已出库</span>
            <span v-else-if="scope.row.inStockFlag === 'X'" type="warning">未入库</span>
            <span v-else>{{ scope.row.inStockFlag }}</span>
          </span>
          <span v-else-if="item.columnProp === 'lastPrintDate' || item.columnProp === 'createdDate'">
            {{ formatDate(scope.row[item.columnProp]) }}
          </span>
          <span v-else-if="item.columnProp === 'reserveFlag'">
            {{ scope.row.reserveFlag === 'Y' ? '是' : '否' }}
          </span>
          <span v-else>{{ scope.row[item.columnProp] }}</span>
        </template>
      </el-table-column>

      <!-- 操作列 - rqrq -->
      <el-table-column label="操作" min-width="150" fixed="right" header-align="center" align="center">
        <template slot-scope="scope">
          <a
           @click="reprintLabel(scope.row)"
           type="primary"
           :loading="scope.row.printing">
           重打标签
          </a>
          <a
           @click="deleteLabel(scope.row)"
           type="danger"
           style="color: #f56c6c;">
           删除
          </a>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>

    <!-- 其它入库标签打印弹窗 -->
    <el-dialog
      title="其它入库标签打印"
      :visible.sync="otherInboundVisible"
      width="450px"
      :close-on-click-modal="false">
      <el-form :model="otherInboundForm" ref="otherInboundForm" class="other-inbound-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="物料编码" prop="partNo" class="form-item-vertical">
              <el-input v-model="otherInboundForm.partNo" placeholder="请输入物料编码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料描述" prop="partDesc" class="form-item-vertical">
              <el-input v-model="otherInboundForm.partDesc" placeholder="请输入物料描述"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="批次号" prop="batchNo" class="form-item-vertical">
              <el-input v-model="otherInboundForm.batchNo" placeholder="请输入批次号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="WDR" prop="wdr" class="form-item-vertical">
              <el-input v-model="otherInboundForm.wdr" placeholder="请输入WDR" value="*"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数量" prop="qty" class="form-item-vertical">
              <el-input
                v-model="otherInboundForm.qty"
                :min="0.01"
                :precision="2"
                style="width: 100%"
                placeholder="请输入数量">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="包装数" prop="packageCount" class="form-item-vertical">
              <el-input
                v-model="otherInboundForm.packageCount"
                :min="1"
                style="width: 100%"
                placeholder="请输入包装数">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="高度(mm)" prop="height" class="form-item-vertical">
              <el-input v-model="otherInboundForm.height"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效日期" class="form-item-vertical">
              <el-date-picker
                v-model="otherInboundForm.expiredDate"
                type="date"
                placeholder="请选择失效日期"
                style="width: 100%"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="otherInboundVisible = false">取消</el-button>
        <el-button type="primary" @click="createOtherInboundHU()" :loading="otherInboundLoading">保存并打印</el-button>
      </div>
    </el-dialog>

    <!-- 失败打印任务重试弹窗 -->
    <el-dialog
      title="失败打印任务列表"
      :visible.sync="failedPrintTasksVisible"
      width="600px"
      :close-on-click-modal="false">
      <el-table
        :data="failedPrintTasksList"
        border
        stripe
        v-loading="failedPrintTasksLoading"
        max-height="400"
        style="width: 100%">
        <el-table-column
          prop="unitId"
          label="标签号"
          min-width="150"
          align="center"
          header-align="center">
        </el-table-column>
        <el-table-column
          prop="printerIp"
          label="打印机IP"
          min-width="120"
          align="center"
          header-align="center">
        </el-table-column>
        <el-table-column
          prop="retryCount"
          label="打印次数"
          width="80"
          align="center"
          header-align="center">
        </el-table-column>
        <el-table-column
          prop="createdDate"
          label="创建时间"
          min-width="150"
          align="center"
          header-align="center">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createdDate) }}
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="failedPrintTasksVisible = false">取消</el-button>
        <el-button type="primary" @click="retryAllFailedTasks()" :loading="retryLoading">重试全部</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getHandlingUnitLabelList, reprintLabel, deleteLabel, getFailedPrintTasks, retryFailedPrintTasks } from '@/api/warehouse/labelQuery'
import { searchSysLanguagePackList, saveUserFavorite, searchUserFavorite } from '@/api/sysLanguage'
import { createOtherInboundHU, printLabel } from '@/api/warehouse/otherInbound'

export default {
  data() {
    return {
      dataForm: {
        key: ''
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 50,
      totalPage: 0,
      dataListLoading: false,
      printLoading: false,
      loadingText: '加载中...',
      dataListSelections: [],
      favorite: false,
      height: 500,
      // 表格列配置 - rqrq
      columnList: [
        {
          columnProp: "unitId",
          headerAlign: "center",
          align: "center",
          columnLabel: "标签号",
          columnWidth: 150,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "partNo",
          headerAlign: "center",
          align: "center",
          columnLabel: "物料编号",
          columnWidth: 120,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "partDesc",
          headerAlign: "center",
          align: "center",
          columnLabel: "物料描述",
          columnWidth: 150,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "batchNo",
          headerAlign: "center",
          align: "center",
          columnLabel: "批次号",
          columnWidth: 120,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "locationId",
          headerAlign: "center",
          align: "center",
          columnLabel: "库位",
          columnWidth: 100,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "warehouseId",
          headerAlign: "center",
          align: "center",
          columnLabel: "仓库",
          columnWidth: 100,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "wdr",
          headerAlign: "center",
          align: "center",
          columnLabel: "WDR",
          columnWidth: 100,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "engChgLevel",
          headerAlign: "center",
          align: "center",
          columnLabel: "engChgLevel",
          columnWidth: 100,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "expiredDate",
          headerAlign: "center",
          align: "center",
          columnLabel: "expiredDate",
          columnWidth: 130,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "qty",
          headerAlign: "center",
          align: "right",
          columnLabel: "数量",
          columnWidth: 80,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "inStockFlag",
          headerAlign: "center",
          align: "center",
          columnLabel: "入库状态",
          columnWidth: 80,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "printCount",
          headerAlign: "center",
          align: "center",
          columnLabel: "打印次数",
          columnWidth: 80,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "lastPrintDate",
          headerAlign: "center",
          align: "center",
          columnLabel: "最后打印时间",
          columnWidth: 150,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "createdDate",
          headerAlign: "center",
          align: "center",
          columnLabel: "创建时间",
          columnWidth: 150,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "height",
          headerAlign: "center",
          align: "right",
          columnLabel: "高度(mm)",
          columnWidth: 100,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "reserveFlag",
          headerAlign: "center",
          align: "center",
          columnLabel: "是否预留",
          columnWidth: 80,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "reserveOrderRef1",
          headerAlign: "center",
          align: "center",
          columnLabel: "预留单号1",
          columnWidth: 120,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "reserveOrderRef2",
          headerAlign: "center",
          align: "center",
          columnLabel: "预留单号2",
          columnWidth: 120,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        },
        {
          columnProp: "reserveOrderRef3",
          headerAlign: "center",
          align: "center",
          columnLabel: "预留单号3",
          columnWidth: 120,
          columnSortable: false,
          showOverflowTooltip: true,
          fixed: ""
        }
      ],
      queryHeaderData: {
        inStockFlag: '',
        partNo: '',
        batchNo: '',
        locationId: '',
        unitId: '',
        partDesc: ''
      },
      // 打印相关配置
      reportId: 'HU_LABEL', // 默认报表ID，可根据实际情况调整
      zplCode: '', // ZPL代码
      paperSize: 'A4',
      orientation: 'portrait',
      dpi: 203,
      // 其它入库标签打印相关
      otherInboundVisible: false,
      otherInboundLoading: false,
      otherInboundForm: {
        partNo: '',
        partDesc: '',
        batchNo: '',
        locationId: '',
        warehouseId: '',
        wdr: '*',
        qty: 1,
        umId: '个',
        packageCount: 1,
        manufactureDate: '',
        expiredDate: '',
        remark: ''
      },
      // 导出相关 - rqrq
      exportData: [],
      exportName: '标签查询' + this.dayjs().format('YYYYMMDDHHmmss'),
      exportHeader: ["标签查询"],
      exportFooter: [],
      otherInboundRules: {
        partNo: [
          { required: true, message: '物料编码不能为空', trigger: 'blur' }
        ],
        partDesc: [
          { required: true, message: '物料描述不能为空', trigger: 'blur' }
        ],
        batchNo: [
          { required: true, message: '批次号不能为空', trigger: 'blur' }
        ],
        locationId: [
          { required: true, message: '库位不能为空', trigger: 'blur' }
        ],
        warehouseId: [
          { required: true, message: '仓库不能为空', trigger: 'blur' }
        ],
        qty: [
          { required: true, message: '数量不能为空', trigger: 'blur' },
          { type: 'number', min: 0.01, message: '数量必须大于0', trigger: 'blur' }
        ],
        umId: [
          { required: true, message: '单位不能为空', trigger: 'blur' }
        ],
        packageCount: [
          { required: true, message: '包装数不能为空', trigger: 'blur' },
          { type: 'number', min: 1, message: '包装数必须大于等于1', trigger: 'blur' }
        ]
      },
      // 失败打印任务相关
      failedPrintTasksVisible: false,
      failedPrintTasksLoading: false,
      failedPrintTasksList: [],
      retryLoading: false
    }
  },
  activated() {
    this.getDataList()
    this.getHeight()
  },
  mounted() {
    this.getDataList()
    this.getHeight()
  },
  methods: {
    // 获取数据列表
    getDataList() {
      this.dataListLoading = true
      const params = {
        page: this.pageIndex,
        size: this.pageSize,
        site: localStorage.getItem('site'),
        ...this.queryHeaderData
      }

      getHandlingUnitLabelList(params).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.list || []
          this.totalPage = data.page.totalCount || 0
        } else {
          this.dataList = []
          this.totalPage = 0
          this.$message.error(data.msg || '查询失败')
        }
        this.dataListLoading = false
      }).catch(() => {
        this.dataList = []
        this.totalPage = 0
        this.dataListLoading = false
      })
    },

    // 重置查询条件
    resetQuery() {
      this.queryHeaderData = {
        inStockFlag: '',
        partNo: '',
        batchNo: '',
        locationId: '',
        unitId: '',
        partDesc: ''
      }
      this.pageIndex = 1
      this.getDataList()
    },

    // 重打标签
    async reprintLabel(row) {

      try {
        // 设置页面打印状态
        this.printLoading = true
        this.loadingText = `${row.unitId} 打印中...`
        // 设置行打印状态
        this.$set(row, 'printing', true)
        let printLabelType;
        if (row.partNo && row.partNo.startsWith("80")) {
          printLabelType = '库存成品标签';
        } else {
          printLabelType = 'BIL标签';
        }
        const printRequest = {
          reportId: this.reportId,
          zplCode: this.zplCode,
          paperSize: this.paperSize,
          orientation: this.orientation,
          dpi: this.dpi,
          userId: localStorage.getItem('userName'),
          username: localStorage.getItem('userName'),
          site: localStorage.getItem('site'),
          unitId: row.unitId,
          labelType:printLabelType
        }

        const { data } = await reprintLabel(printRequest)
        if (data && data.code === 0) {
          this.$message.success('打印任务已发送成功')
          // 刷新当前行数据
          this.getDataList()
        } else {
          this.$message.error(data.msg || '打印失败')
        }
      } catch (error) {
        this.$message.error('打印失败：' + error.message)
      } finally {
        // 清除页面打印状态
        this.printLoading = false
        this.loadingText = '加载中...'
        // 清除行打印状态
        this.$set(row, 'printing', false)
      }
    },

    // 删除标签
    deleteLabel(row) {
      this.$confirm(`确定要删除单元ID为 ${row.unitId} 的标签吗？此操作不可恢复！`, '删除确认', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          this.dataListLoading = true
          const { data } = await deleteLabel({
            site: localStorage.getItem('site'),
            unitId: row.unitId
          })
          if (data && data.code === 0) {
            this.$message.success('删除成功')
            // 刷新数据列表
            this.getDataList()
          } else {
            this.$message.error(data.msg || '删除失败')
          }
        } catch (error) {
          this.$message.error('删除失败：' + error.message)
        } finally {
          this.dataListLoading = false
        }
      }).catch(() => {
        // 用户取消删除
      })
    },

    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },

    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },

    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hours = String(d.getHours()).padStart(2, '0')
      const minutes = String(d.getMinutes()).padStart(2, '0')
      const seconds = String(d.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    // 导出相关方法 - rqrq
    async createExportData() {
      const queryParams = {
        site: localStorage.getItem('site'),
        ...this.queryHeaderData,
        page: 1,
        size: 999999  // 设置一个很大的数字来获取全部数据 - rqrq
      }
      const {data} = await getHandlingUnitLabelList(queryParams)
      if (data && data.code === 0) {
        return (data.page.list || []).map(item => {
          return {
            ...item,
            inStockFlag: item.inStockFlag === 'Y' ? '在库' : item.inStockFlag === 'N' ? '已出库' : item.inStockFlag === 'X' ? '未入库' : item.inStockFlag,
            reserveFlag: item.reserveFlag === 'Y' ? '是' : '否',
            lastPrintDate: this.formatDate(item.lastPrintDate),
            createdDate: this.formatDate(item.createdDate)
          }
        })
      }
      return []
    },
    startDownload() {
      // 开始导出 - rqrq
    },
    finishDownload() {
      // 导出完成 - rqrq
    },
    fields() {
      let json = "{"
      this.columnList.forEach((item, index) => {
        if (index == this.columnList.length - 1) {
          json += "\"" + item.columnLabel + "\"" + ":" + "\"" + item.columnProp + "\""
        } else {
          json += "\"" + item.columnLabel + "\"" + ":" + "\"" + item.columnProp + "\"" + ","
        }
      })
      json += "}"
      let s = eval("(" + json + ")")
      return s
    },

    // 获取表格高度
    getHeight() {
      this.$nextTick(() => {
        this.height = window.innerHeight - 280
      })
    },

    // 显示其它入库标签打印对话框
    showOtherInboundDialog() {
      this.otherInboundVisible = true
      // 重置表单
      this.otherInboundForm = {
        partNo: '',
        partDesc: '',
        batchNo: '',
        locationId: '',
        warehouseId: '',
        wdr: '*',
        qty: 1,
        umId: '个',
        packageCount: 1,
        manufactureDate: '',
        expiredDate: '',
        remark: '',
        height: '',
      }
      this.$nextTick(() => {
        if (this.$refs['otherInboundForm']) {
          this.$refs['otherInboundForm'].clearValidate()
        }
      })
    },

    // 创建其它入库HandlingUnit
    async createOtherInboundHU() {
      try {
        // 基本验证
        if (!this.otherInboundForm.partNo) {
          this.$message.error('物料编码不能为空')
          return
        }
        if (!this.otherInboundForm.partDesc) {
          this.$message.error('物料描述不能为空')
          return
        }
        if (!this.otherInboundForm.batchNo) {
          this.$message.error('批次号不能为空')
          return
        }
        if (!this.otherInboundForm.qty || parseFloat(this.otherInboundForm.qty) <= 0) {
          this.$message.error('数量必须大于0')
          return
        }
        if (!this.otherInboundForm.packageCount || parseInt(this.otherInboundForm.packageCount) <= 0) {
          this.$message.error('包装数必须大于0')
          return
        }

        this.otherInboundLoading = true

         // 准备创建HU的数据
         const createData = {
           site: localStorage.getItem('site'),
           warehouseId: this.otherInboundForm.warehouseId,
           partNo: this.otherInboundForm.partNo,
           partDesc: this.otherInboundForm.partDesc,
           batchNo: this.otherInboundForm.batchNo,
           wdr: this.otherInboundForm.wdr,
           locationId: this.otherInboundForm.locationId,
           umid: this.otherInboundForm.umId,
           perPackageQty: parseFloat(this.otherInboundForm.qty),
           packageCount: parseInt(this.otherInboundForm.packageCount),
           manufactureDate: this.otherInboundForm.manufactureDate || null,
           expiredDate: this.otherInboundForm.expiredDate || null,
           remark: this.otherInboundForm.remark,
            height: this.otherInboundForm.height || null,
         }

        // 创建HandlingUnit
        const { data } = await createOtherInboundHU(createData)
        if (data && data.code === 0) {
          this.$message.success('创建HandlingUnit成功')

          // 确定标签类型
          let printLabelType
          if (this.otherInboundForm.partNo && this.otherInboundForm.partNo.startsWith("80")) {
            printLabelType = '库存成品标签'
          } else {
            printLabelType = 'BIL标签'
          }

          // 创建成功后进行打印
          await this.printHandlingUnits(data.unitIds, printLabelType)

          this.otherInboundVisible = false
          this.getDataList() // 刷新列表
        } else {
          this.$message.error(data.msg || '创建HandlingUnit失败')
        }
      } catch (error) {
        this.$message.error('创建失败：' + error.message)
      } finally {
        this.otherInboundLoading = false
      }
    },

    // 打印HandlingUnit标签
    async printHandlingUnits(unitIds, printLabelType) {
      if (!unitIds || unitIds.length === 0) {
        return
      }

      try {
        // 逐个打印每个HandlingUnit
        for (const unitId of unitIds) {
          await this.printViaServer(unitId, printLabelType)
        }
        this.$message.success(`成功打印 ${unitIds.length} 个HandlingUnit标签`)
      } catch (error) {
        this.$message.error('打印失败: ' + error.message)
      }
    },

    // 通过服务器打印
    async printViaServer(unitId, printLabelType) {
      try {
        const printRequest = {
          reportId: this.reportId,
          zplCode: this.zplCode,
          paperSize: this.paperSize,
          orientation: this.orientation,
          dpi: this.dpi,
          userId: localStorage.getItem('userName'),
          username: localStorage.getItem('userName'),
          site: localStorage.getItem('site'),
          unitId: unitId,
          labelType: printLabelType
        }
        const { data } = await printLabel(printRequest)
        if (data.code === 200) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error(data.msg || '打印失败'))
        }
      } catch (error) {
        return Promise.reject(error)
      }
    },

    /**
     * 显示失败打印任务对话框
     */
    async showFailedPrintTasksDialog() {
      this.failedPrintTasksVisible = true
      this.failedPrintTasksLoading = true

      try {
        const { data } = await getFailedPrintTasks({
          site: localStorage.getItem('site')
        })

        if (data && data.code === 0) {
          this.failedPrintTasksList = data.rows || []
          if (this.failedPrintTasksList.length === 0) {
            this.$message.warning('没有失败的打印任务')
          }
        } else {
          this.$message.error(data.msg || '查询失败')
          this.failedPrintTasksList = []
        }
      } catch (error) {
        this.$message.error('查询失败：' + error.message)
        this.failedPrintTasksList = []
      } finally {
        this.failedPrintTasksLoading = false
      }
    },

    /**
     * 重试全部失败的打印任务
     */
    async retryAllFailedTasks() {
      if (this.failedPrintTasksList.length === 0) {
        this.$message.warning('没有需要重试的任务')
        return
      }

      this.$confirm(`确定要重试全部 ${this.failedPrintTasksList.length} 个失败的打印任务吗？`, '重试确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.retryLoading = true

        try {
          const { data } = await retryFailedPrintTasks({
            site: localStorage.getItem('site')
          })

          if (data && data.code === 0) {
            this.$message.success(`成功将 ${data.count || 0} 个任务重新加入打印队列`)
            // 关闭对话框
            this.failedPrintTasksVisible = false
            // 清空列表
            this.failedPrintTasksList = []
          } else {
            this.$message.error(data.msg || '重试失败')
          }
        } catch (error) {
          this.$message.error('重试失败：' + error.message)
        } finally {
          this.retryLoading = false
        }
      }).catch(() => {
        // 用户取消重试
      })
    }
  }
}
</script>

<style>
.mod-config .el-form-item {
  margin-bottom: 15px;
}
.sl-svg {
  font-size: 20px;
  cursor: pointer;
  color: #409EFF;
}

/* 其它入库标签打印表单样式 */
.other-inbound-form .form-item-vertical {
  margin-bottom: 20px;
}

.other-inbound-form .form-item-vertical .el-form-item__label {
  display: block;
  text-align: left;
  padding: 0 0 8px 0;
  line-height: 1.5;
  font-weight: 500;
}

.other-inbound-form .form-item-vertical .el-form-item__content {
  margin-left: 0 !important;
}

.other-inbound-form .el-row {
  margin-bottom: 0;
}
</style>
