<template>
  <div class="customer-css">
    <el-dialog :title="titleCon" v-drag v-bind="$attrs" v-on="$listeners" width="700px" style="height: 680px;" class="customer-dialog">
      <el-form :inline="true" label-position="top" style="height: auto;">
        <!-- 时间和固定载具 -->
        <el-row style="margin-top: -10px;">
          <el-col :span="11">
            <el-form-item :label=labels.currentTime>
              <el-date-picker style="width: 110px;"
                              v-model="pageData.reportDate"
                              format="yyyy-MM-dd"
                              value-format="yyyy-MM-dd"
                              placeholder="">
              </el-date-picker>
            </el-form-item>
            <el-form-item :label="''" style="margin-top: 23px">
              <el-time-picker style="width: 100px;"
                              v-model="pageData.reportTime"
                              format="HH:mm:ss"
                              value-format="HH:mm:ss"
                              placeholder="">
              </el-time-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <span style="cursor: pointer" slot="label" @click="queryFixedCarrierList"><a>固定载具</a></span>
              <el-input v-model="pageData.fixture" readonly style="width: 120px;" placeholder="固定载具"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="排数">
              <el-input-number :controls="false" :step="0" v-model="pageData.rowCount" @change="handleRowCountChange" style="width: 60px;"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item label="分切卷数">
              <el-input-number :controls="false" :step="0" v-model="pageData.rollCount" style="width: 60px;"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 排数据表格 -->
        <div class="rq">
          <el-table
            :data="rowDataList"
            border
            style="width: 100%; margin-top: 10px;"
            max-height="350"
            :span-method="objectSpanMethod">
            <el-table-column prop="rowNumber" label="NO." width="50" align="center">
            </el-table-column>
            <el-table-column label="良品数" width="80" align="center">
              <template slot-scope="scope">
                <el-input-number
                  :controls="false" :step="0"
                  v-model="scope.row.goodQty"
                  @change="handleQtyChange(scope.row)"
                  style="width: 100%"
                  class="good-qty-input"
                  :style="{'color': '#67c23a', 'font-weight': 'bold'}">
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="面损" width="80" align="center">
              <template slot-scope="scope">
                <el-input-number
                  :controls="false" :step="0"
                  v-model="scope.row.surfaceLossQty"
                  @change="handleQtyChange(scope.row)"
                  style="width: 100%">
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="性能不良" width="80" align="center">
              <template slot-scope="scope">
                <el-input-number
                  :controls="false" :step="0"
                  v-model="scope.row.poorPerformanceQty"
                  @change="handleQtyChange(scope.row)"
                  style="width: 100%">
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="不良数" width="80" align="right">
              <template slot-scope="scope">
                <div class="defect-display" :style="{'color': '#f56c6c', 'font-weight': 'bold', 'text-align': 'right', 'padding-right': '10px'}">
                  {{ scope.row.defectQty }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="良率" width="80" align="center">
              <template slot-scope="scope">
                <div class="yield-display" :style="{'color': '#409eff', 'font-weight': 'bold'}">
                  {{ scope.row.yieldRate }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="总数" width="80" align="right">
              <template slot-scope="scope">
                <div class="total-display" :style="{'text-align': 'right', 'padding-right': '10px'}">
                  {{ scope.row.totalQty }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" class-name="remark-column">
              <template slot-scope="scope">
                <div class="remark-wrapper">
                  <el-input
                    type="textarea"
                    v-model="scope.row.remark"
                    resize="none"
                    :autosize="false"
                    class="remark-textarea">
                  </el-input>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="checkCreateSeparateRolllBun">保存</el-button>
        <el-button @click="closeDialog">{{ buttons.closeButton }}</el-button>
      </span>
    </el-dialog>

    <!-- 固定载具选择对话框 -->
    <el-dialog title="固定载具清单" :close-on-click-modal="false" v-drag :visible.sync="carrierModelFlag" width="950px">
      <div class="rq">
        <el-form :inline="true" label-position="top" :model="carrierSearchData">
          <el-form-item label="标签条码">
            <el-input v-model="carrierSearchData.carrierNo" clearable style="width: 150px"></el-input>
          </el-form-item>
          <el-form-item label="载具类型名称">
            <el-input v-model="carrierSearchData.carrierTypeName" clearable style="width: 150px"></el-input>
          </el-form-item>
          <el-form-item label="规格描述">
            <el-input v-model="carrierSearchData.specification" clearable style="width: 150px"></el-input>
          </el-form-item>
          <el-form-item label=" ">
            <el-button type="primary" @click="queryFixedCarrierList">查询</el-button>
            <el-button v-if="!editBatchVisible" @click="editBatchModel" type="success" icon="el-icon-edit">批量编辑</el-button>
            <el-button v-if="editBatchVisible" @click="batchSaveCarrier" type="primary" icon="el-icon-check" :loading="saveLoading">批量保存</el-button>
          </el-form-item>
        </el-form>
        <el-table
          :height="400"
          :data="carrierList"
          @row-dblclick="selectCarrier"
          border
          style="width: 100%;">
          <el-table-column
            prop="carrierNo"
            label="标签条码"
            header-align="center"
            align="left"
            min-width="120">
          </el-table-column>
          <el-table-column
            prop="carrierTypeName"
            label="载具类型名称"
            header-align="center"
            align="left"
            min-width="150">
          </el-table-column>
          <el-table-column
            prop="specification"
            label="规格描述"
            header-align="center"
            align="left"
            min-width="150">
          </el-table-column>
          <el-table-column
            prop="dimensions"
            label="尺寸"
            header-align="center"
            align="left"
            min-width="100">
          </el-table-column>
          <el-table-column
            label="可用数量"
            header-align="center"
            align="right"
            min-width="120">
            <template slot-scope="scope">
              <el-input-number
                v-if="editBatchVisible"
                v-model="scope.row.availableQty"
                :controls="false"
                :min="0"
                :precision="0"
                style="width: 100%">
              </el-input-number>
              <span v-else>{{ scope.row.availableQty || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            header-align="center"
            align="center"
            width="80"
            fixed="right">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-printer"
                @click="printCarrier(scope.row)"
                style="color: #409eff;">
                打印
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-footer style="height:40px;margin-top: 20px;text-align:center">
        <el-button type="primary" @click="carrierModelFlag=false">关闭</el-button>
      </el-footer>
    </el-dialog>
  </div>
</template>

<script>
  import {
    checkCreateSplitSfdcRoll,/*校验是否可以创建分卷*/
    createSplitSfdcRoll,/*执行创建分卷的操作*/
    getFixedCarrierList,/*获取固定载具列表*/
  } from '@/api/yieldReport/com_separate_roll.js';

  /*打印标签专用的js*/
  import {
    printSfdcLabel,
  } from "@/views/modules/yieldReport/print_roll_label.js";

  import {
    searchSysLanguagePackList,
    searchSysLanguageParam,
    searchFunctionButtonList,
    saveButtonList,
    searchSysLanguage,
    searchLanguageListByLanguageCode,
    saveSysLanguageOne,
    searchPageLanguageData,
    removerLanguage,
    saveSysLanguageList
  } from "@/api/sysLanguage.js";

  var functionId = 'C10000004';

export default {
  name: "com_separate_roll",
  data() {
    return {
      titleCon: '创建分卷',
      showDefault: false,
      scheduleData: {
        site: this.$store.state.user.site,
        username: this.$store.state.user.name,
        seqNo: '',
        orderNo: '',
        itemNo: 0,
        resourceId: '',
        scheduledDate: '',
        shiftNo: '',
        partNo: '',
        workCenterNo: '',
        workCenterDesc: '',
        resourceDesc: '',
        rollNo: '',
        partDesc: '',
        planStartTime: '',
        planFinishTime: '',
        qtyRequiredOriginal: 0,
        preItemDesc: '',
        nextItemDesc: '',
        nextItemNo: 0,
        operatorId: '',
        functionName: '',
        currentRollFlag: false
      },
      pageData: {
        site: this.$store.state.user.site,
        username: this.$store.state.user.name,
        orderNo: '',
        itemNo: '',
        seqNo: '',
        rollNo: '',
        reportDate: '',
        reportTime: '',
        operatorId: '',
        rollQty: 0,
        rollNums: 1,
        // 新增字段
        fixture: '',      // 固定载具
        rowCount: 0,      // 排数
        rollCount: 0,      // 卷数
        carrierNo: ''
      },
      rowDataList: [],    // 排数据列表
      operatorData: {
        site: this.$store.state.user.site,
        username: this.$store.state.user.name,
        operatorId: '',
        operatorName: '',
        status: '',
        seqNo: '',
        showFlag: false
      },
      carrierModelFlag: false,  // 固定载具对话框标记
      carrierList: [],  // 固定载具列表
      carrierSearchData: {  // 固定载具查询条件
        carrierNo: '',
        carrierTypeName: '',
        specification: ''
      },
      editBatchVisible: false,  // 批量编辑状态
      saveLoading: false,  // 保存loading状态
      buttons: {
        confirmButton: '确定',
        closeButton: '关闭',
      },
      buttonList: [
        {
          functionId: functionId,
          languageValue: '确定',
          objectId: 'confirmButton',
          objectType: 'button',
          tableId: '*'
        }, {
          functionId: functionId,
          languageValue: '关闭',
          objectId: 'closeButton',
          objectType: 'button',
          tableId: '*'
        },
      ],
      queryButton: {
        functionId: functionId,
        table_id: '*',
        languageCode: this.$i18n.locale,
        objectType: 'button'
      },
      labels: {
        componentTitle: '创建分卷',
        currentTime: '当前时间:',
        rollQty: '良品数量:',
        rollNums: '卷数:',
        approvedQtyMustBeInteger: '良品数量必须是正整数!',
        rollQtyMustBeInteger: '卷数必须是正整数!',
        pleaseSwitchOperator: '请先切换人员!',
        approvedQtyMustMoreTanZeroAndBeInteger: '良品数量必须大于零且是整数!',
        rollQtyMustMoreTanZeroAndBeInteger: '卷数必须是正整数!',
        confirmLabel: '确认',
        cancelLabel: '取消',
      },
      labelsList: [
        {
          functionId: functionId,
          languageValue: '创建分卷',
          objectId: 'componentTitle',
          objectType: 'label',
          tableId: '*'
        }, {
          functionId: functionId,
          languageValue: '当前时间:',
          objectId: 'currentTime',
          objectType: 'label',
          tableId: '*'
        }, {
          functionId: functionId,
          languageValue: '良品数量:',
          objectId: 'rollQty',
          objectType: 'label',
          tableId: '*'
        }, {
          functionId: functionId,
          languageValue: '卷数:',
          objectId: 'rollNums',
          objectType: 'label',
          tableId: '*'
        }, {
          functionId: functionId,
          languageValue: '良品数量必须是正整数!',
          objectId: 'approvedQtyMustBeInteger',
          objectType: 'label',
          tableId: '*'
        }, {
          functionId: functionId,
          languageValue: '卷数必须是正整数!',
          objectId: 'rollQtyMustBeInteger',
          objectType: 'label',
          tableId: '*'
        }, {
          functionId: functionId,
          languageValue: '良品数量必须大于零且是整数!',
          objectId: 'approvedQtyMustMoreTanZeroAndBeInteger',
          objectType: 'label',
          tableId: '*'
        }, {
          functionId: functionId,
          languageValue: '卷数必须大于零且是整数!',
          objectId: 'rollQtyMustMoreTanZeroAndBeInteger',
          objectType: 'label',
          tableId: '*'
        }, {
          functionId: functionId,
          languageValue: '请先切换人员!',
          objectId: 'pleaseSwitchOperator',
          objectType: 'label',
          tableId: '*'
        }, {
          functionId: functionId,
          languageValue: '确认',
          objectId: 'confirmLabel',
          objectType: 'label',
          tableId: '*'
        }, {
          functionId: functionId,
          languageValue: '取消',
          objectId: 'cancelLabel',
          objectType: 'label',
          tableId: '*'
        },
      ],
      queryLabel: {
        functionId: functionId,
        table_id: '*',
        languageCode: this.$i18n.locale,
        objectType: 'label'
      },
    }
  },
  methods: {
    //页面初始化是的方法
    init(scheduleData, operatorData) {
      //初始化参数
      this.scheduleData = scheduleData;
      //初始化操作员对象
      this.operatorData = JSON.parse(JSON.stringify(operatorData));
      //重置时间
      this.pageData.reportDate = this.dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss');
      this.pageData.reportTime = this.dayjs(new Date()).format('HH:mm:ss');
      //设置参数
      this.pageData.orderNo = scheduleData.orderNo;
      this.pageData.itemNo = scheduleData.itemNo;
      this.pageData.seqNo = scheduleData.seqNo;
      this.pageData.rollNo = scheduleData.rollNo;
      this.pageData.operatorId = operatorData.operatorId;
      //清空参数
      this.pageData.rollQty = 0;
      this.pageData.rollNums = 1;
      // 初始化新增字段
      this.pageData.rowCount = scheduleData.rowCount;
      this.pageData.rollCount = scheduleData.rollCount;
      this.pageData.fixture = scheduleData.carrierNo;
       //判断是否启用多语言
      // this.getMultiLanguageList();  //刷新多语言的信息
      //获取焦点
      this.$nextTick(() => {
        this.$refs.rollQty && this.$refs.rollQty.focus();
      });
      this.titleCon = this.labels.componentTitle;//重置标题
      // 初始化排数据列表
      this.initRowDataList();
    },

    // ===================== 新增分卷优化方法 =====================

    // 初始化排数据列表
    initRowDataList() {
      this.rowDataList = []
      for (let i = 0; i < this.pageData.rowCount; i++) {
        this.rowDataList.push({
          rowNumber: i,
          goodQty: 0,
          surfaceLossQty: 0,
          poorPerformanceQty: 0,
          defectQty: 0,
          yieldRate: '0.00%',
          totalQty: 0,
          remark: ''
        })
      }
    },

    // 排数变化时重新初始化
    handleRowCountChange() {
      if (this.pageData.rollCount > this.pageData.rowCount) {
        this.pageData.rollCount = this.pageData.rowCount
      }
      this.initRowDataList()
    },

    // 数量变化时自动计算不良数、良率和总数
    handleQtyChange(row) {
      // 计算不良数 = 面损 + 性能不良
      row.defectQty = (row.surfaceLossQty || 0) + (row.poorPerformanceQty || 0)

      // 计算总数 = 良品数 + 不良数
      row.totalQty = (row.goodQty || 0) + row.defectQty

      // 计算良率 = 良品数 / 总数 * 100%
      if (row.totalQty > 0) {
        const yieldValue = ((row.goodQty || 0) / row.totalQty * 100).toFixed(2)
        row.yieldRate = yieldValue + '%'
      } else {
        row.yieldRate = '0.00%'
      }
    },

    // 验证排数据
    validateRowData() {
      if (this.pageData.rowCount <= 0) {
        this.$message.warning('请输入有效的排数')
        return false
      }
      if (this.pageData.rollCount <= 0) {
        this.$message.warning('请输入有效的卷数')
        return false
      }
      if (this.pageData.rollCount > this.pageData.rowCount) {
        this.$message.warning('卷数不能大于排数')
        return false
      }

      // 检查是否有数据
      const hasData = this.rowDataList.some(row => (row.goodQty > 0 || row.defectQty > 0))
      if (!hasData) {
        this.$message.warning('请至少输入一行数据')
        return false
      }

      // 检查每一行的良品数必须大于0
      for (let i = 0; i < this.rowDataList.length; i++) {
        const row = this.rowDataList[i]
        if (row.goodQty === null || row.goodQty === undefined || row.goodQty <= 0) {
          this.$message.error(`第 ${i + 1} 排的良品数必须大于0`)
          return false
        }
      }

      return true
    },

    // 表格合并行方法（备注列根据卷数合并）
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // 只对备注列进行合并（最后一列）
      if (column.label === '备注') {
        // 计算每卷的排数
        const rowsPerRoll = Math.floor(this.pageData.rowCount / this.pageData.rollCount)
        const remainingRows = this.pageData.rowCount % this.pageData.rollCount

        // 计算当前行属于第几卷
        let currentRollIndex = 0
        let accumulatedRows = 0

        for (let i = 0; i < this.pageData.rollCount; i++) {
          const currentRollRows = rowsPerRoll + (i < remainingRows ? 1 : 0)
          if (rowIndex < accumulatedRows + currentRollRows) {
            currentRollIndex = i
            break
          }
          accumulatedRows += currentRollRows
        }

        // 计算当前卷的排数
        const currentRollRows = rowsPerRoll + (currentRollIndex < remainingRows ? 1 : 0)

        // 如果是当前卷的第一行，显示合并的单元格
        if (rowIndex === accumulatedRows) {
          return {
            rowspan: currentRollRows,
            colspan: 1
          }
        } else {
          // 其他行不显示
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },

    // 计算备注wrapper的样式（使用padding-top实现垂直居中）
    getRemarkWrapperStyle(rowIndex) {
      if (this.pageData.rowCount <= 0 || this.pageData.rollCount <= 0) {
        return {}
      }

      // 计算每卷的排数
      const rowsPerRoll = Math.floor(this.pageData.rowCount / this.pageData.rollCount)
      const remainingRows = this.pageData.rowCount % this.pageData.rollCount

      // 计算当前行属于第几卷
      let currentRollIndex = 0
      let accumulatedRows = 0

      for (let i = 0; i < this.pageData.rollCount; i++) {
        const currentRollRows = rowsPerRoll + (i < remainingRows ? 1 : 0)
        if (rowIndex < accumulatedRows + currentRollRows) {
          currentRollIndex = i
          break
        }
        accumulatedRows += currentRollRows
      }

      // 计算当前卷的排数
      const currentRollRows = rowsPerRoll + (currentRollIndex < remainingRows ? 1 : 0)

      // 每行高度约为32px
      const rowHeight = 32
      const totalHeight = currentRollRows * rowHeight

      // textarea的实际高度约为24px（单行）
      const textareaHeight = 24

      // 计算需要的padding-top来实现垂直居中
      const paddingTop = (totalHeight - textareaHeight) / 2

      // 返回样式对象
      return {
        paddingTop: paddingTop + 'px'
      }
    },

    // ===================== 分卷优化方法结束 =====================

    // 查询固定载具列表
    queryFixedCarrierList() {
      const params = {
        site: this.scheduleData.site,
        carrierNo: this.carrierSearchData.carrierNo,
        carrierTypeName: this.carrierSearchData.carrierTypeName,
        specification: this.carrierSearchData.specification
      }
      getFixedCarrierList(params).then(({data}) => {
        if (data && data.code === 0) {
          this.carrierList = data.data
          this.carrierModelFlag = true
        } else {
          this.$message.error(data.msg || '获取固定载具列表失败')
        }
      }).catch(error => {
        this.$message.error('获取固定载具列表失败: ' + error.message)
      })
    },

    // 选中固定载具
    selectCarrier(row) {
      this.pageData.fixture = row.carrierNo
      this.carrierModelFlag = false
    },

    // 批量编辑模态框
    editBatchModel() {
      if (this.editBatchVisible) {
        this.editBatchVisible = false
      } else {
        this.editBatchVisible = true
      }
    },

    // 批量保存固定载具可用数量
    batchSaveCarrier() {
      this.saveLoading = true
      // 调用API保存
      import('@/api/yieldReport/com_separate_roll.js').then(module => {
        const { updateFixedCarrierBatch } = module
        updateFixedCarrierBatch(this.carrierList).then(({data}) => {
          if (data && data.code === 0) {
            this.$message.success('批量保存成功')
            this.editBatchVisible = false
            this.queryFixedCarrierList()
          } else {
            this.$message.error(data.msg || '批量保存失败')
          }
        }).catch(error => {
          this.$message.error('批量保存失败: ' + error.message)
        }).finally(() => {
          this.saveLoading = false
        })
      })
    },

    // 打印固定载具
    printCarrier(row) {
      // 构造打印数据
      const printData = {
        carrierNo: row.carrierNo,
        carrierTypeName: row.carrierTypeName,
        specification: row.specification,
        dimensions: row.dimensions,
        availableQty: row.availableQty || 0,
        site: this.scheduleData.site
      }

      // 调用打印功能
      this.printCarrierLabel(printData)
    },

    // 打印载具标签
    printCarrierLabel(data) {
      try {
        // 生成二维码（使用 QRCode.js 或者使用在线二维码API）
        const qrCodeUrl = `https://api.qrserver.com/v1/create-qr-code/?size=120x120&data=${encodeURIComponent(data.carrierNo)}`

        // 打印HTML模板
        const printContent = `
          <div style="width: 100mm; font-family: Arial, sans-serif; padding: 10px; position: relative;">
            <!-- 左上角二维码 -->
            <div style="position: absolute; top: 10px; left: 10px;">
              <img src="${qrCodeUrl}" style="width: 80px; height: 80px; border: 1px solid #ddd;" alt="QR Code"/>
            </div>

            <!-- 标题 -->
            <div style="text-align: center; font-size: 20px; font-weight: bold; margin-bottom: 15px; padding-top: 5px;">
              固定载具标签
            </div>

            <!-- 信息表格 -->
            <table style="width: 100%; border-collapse: collapse; font-size: 14px; margin-top: 10px;">
              <tr>
                <td style="padding: 8px; border: 1px solid #333; font-weight: bold; width: 35%; background-color: #f5f5f5;">标签条码:</td>
                <td style="padding: 8px; border: 1px solid #333; font-size: 15px; font-weight: bold;">${data.carrierNo || ''}</td>
              </tr>
              <tr>
                <td style="padding: 8px; border: 1px solid #333; font-weight: bold; background-color: #f5f5f5;">载具类型:</td>
                <td style="padding: 8px; border: 1px solid #333;">${data.carrierTypeName || ''}</td>
              </tr>
              <tr>
                <td style="padding: 8px; border: 1px solid #333; font-weight: bold; background-color: #f5f5f5;">规格描述:</td>
                <td style="padding: 8px; border: 1px solid #333;">${data.specification || ''}</td>
              </tr>
              <tr>
                <td style="padding: 8px; border: 1px solid #333; font-weight: bold; background-color: #f5f5f5;">尺寸:</td>
                <td style="padding: 8px; border: 1px solid #333;">${data.dimensions || ''}</td>
              </tr>
              <tr>
                <td style="padding: 8px; border: 1px solid #333; font-weight: bold; background-color: #f5f5f5;">可用数量:</td>
                <td style="padding: 8px; border: 1px solid #333; font-size: 18px; font-weight: bold; color: #e74c3c;">${data.availableQty}</td>
              </tr>
            </table>

            <!-- 打印时间 -->
            <div style="text-align: center; margin-top: 15px; font-size: 11px; color: #999; border-top: 1px dashed #ccc; padding-top: 10px;">
              打印时间: ${this.dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')}
            </div>
          </div>
        `

        // 创建打印窗口
        const printWindow = window.open('', '_blank')
        printWindow.document.write(`
          <html>
            <head>
              <title>打印固定载具标签</title>
              <meta charset="UTF-8">
              <style>
                @page { size: auto; margin: 5mm; }
                body { margin: 0; padding: 0; }
                @media print {
                  body { -webkit-print-color-adjust: exact; print-color-adjust: exact; }
                }
              </style>
            </head>
            <body>
              ${printContent}
            </body>
          </html>
        `)
        printWindow.document.close()

        // 延迟打印，确保二维码图片加载完成
        setTimeout(() => {
          printWindow.print()
          printWindow.close()
        }, 500)

        this.$message.success('正在打印载具标签...')
      } catch (error) {
        this.$message.error('打印失败: ' + error.message)
      }
    },

    /*关闭modal*/
    closeDialog(){
      //刷新报工的页面
      this.$emit('refreshPageData');
      //关闭当前的页面
      this.$emit('update:visible', false);
    },

    /*检查材料卷号的数据*/
    checkValidQty() {
      //获取当前是的数量
      let rollQty = parseFloat(this.pageData.rollQty);
      //判断是否可以修改
      if (rollQty <= 0 || !Number.isInteger(rollQty)){
        this.$message.error(this.labels.approvedQtyMustBeInteger);
        return false;
      }
    },

    /*检查材料卷号的数据*/
    checkRollNums() {
      //获取当前是的数量
      let rollNums = parseFloat(this.pageData.rollNums);
      //判断是否是正整数
      if (rollNums <= 0 || !Number.isInteger(rollNums)){
        this.$message.error(this.labels.rollQtyMustBeInteger);
        return false;
      }
    },

    checkCreateSeparateRolllBun() {
      //人员判断
      if (this.pageData.operatorId === '' || this.pageData.operatorId == null) {
        this.$message.error(this.labels.pleaseSwitchOperator);
        return false;
      }

      // //获取当前是的数量
      // let rollQty = parseFloat(this.pageData.rollQty);
      // //判断是否可以修改
      // if (rollQty <= 0 || !Number.isInteger(rollQty)){
      //   this.$message.error(this.labels.approvedQtyMustMoreTanZeroAndBeInteger);
      //   return false;
      // }

      // //获取当前是的数量
      // let rollNums = parseFloat(this.pageData.rollNums);
      // //判断是否是正整数
      // if (rollNums <= 0 || !Number.isInteger(rollNums)){
      //   this.$message.error(this.labels.rollQtyMustMoreTanZeroAndBeInteger);
      //   return false;
      // }
      //校验是否继续
      checkCreateSplitSfdcRoll(this.pageData)
        .then(({data}) => {
        //判断是否成功
        if (data.code == 500) {
          this.$message.error(data.msg);
        } else if (data.resultMap.resultCode == '201') {
          //打开异常原因录入的界面
          this.$confirm(data.resultMap.resultMsg, '提示', {
            confirmButtonText: this.labels.confirmLabel,
            celButtonText: this.labels.cancelLabel,
            type: 'warning'
          }).then(() => {
            //执行切换卷的操作
            this.createSeparateRolllOperation();
          });
        } else { //执行切换卷的操作
          this.createSeparateRolllOperation();
        }
      });
    },

    /*执行创建分卷的操作*/
    async createSeparateRolllOperation() {
      // 验证排数据
      if (!this.validateRowData()) {
        return false
      }

      try {
        // 计算分卷
        const rowsPerRoll = Math.floor(this.pageData.rowCount / this.pageData.rollCount)
        const remainingRows = this.pageData.rowCount % this.pageData.rollCount

        let currentRowIndex = 0
        const allPrintList = []

        // 循环创建每一卷
        for (let rollIndex = 0; rollIndex < this.pageData.rollCount; rollIndex++) {
          // 计算当前卷的排数
          const currentRollRows = rowsPerRoll + (rollIndex < remainingRows ? 1 : 0)

          // 计算当前卷的良品和不良总数
          let totalGoodQty = 0
          let totalDefectQty = 0
          const rollRows = []

          // 获取当前卷的备注（第一排的备注）
          let rollRemark = ''

          for (let i = 0; i < currentRollRows; i++) {
            const row = this.rowDataList[currentRowIndex + i]
            totalGoodQty += row.goodQty || 0
            totalDefectQty += row.defectQty || 0

            // 第一排的备注作为整卷的备注
            if (i === 0) {
              rollRemark = row.remark || ''
            }

            rollRows.push({
              rowNumber: row.rowNumber,
              goodQty: row.goodQty || 0,
              surfaceLossQty: row.surfaceLossQty || 0,
              poorPerformanceQty: row.poorPerformanceQty || 0,
              defectQty: row.defectQty || 0,
              totalQty: row.totalQty || 0,
              remark: row.remark || ''
            })
          }

          // 构建请求数据（每次调用rollNums固定为1）
          const requestData = {
            ...this.pageData,
            rollQty: totalGoodQty,  // 该卷的良品总数
            rollNums: 1,            // 固定为1
            totalDefectQty: totalDefectQty,  // 该卷的不良总数
            rollRows: rollRows,     // 该卷包含的排数据
            remark: rollRemark      // 该卷的备注
          }

          // 调用后端创建单个卷
          const {data} = await createSplitSfdcRoll(requestData)

          if (data.code === 500) {
            throw new Error(data.msg)
          }

          // 收集打印数据
          if (data.printList && data.printList.length > 0) {
            allPrintList.push(...data.printList)
          }

          // 进度提示
          this.$message.success(`第${rollIndex + 1}/${this.pageData.rollCount}卷创建成功`)

          currentRowIndex += currentRollRows
        }

        // 所有卷创建完成
        this.$message.success('创建分卷完成！')

        // 处理打印的数据
        if (allPrintList.length > 0) {
          printSfdcLabel(allPrintList)
        }

        // 延时关闭弹窗
        setTimeout(() =>{
          //关闭当前的页面
          this.closeDialog()
        }, 1000)

      } catch (error) {
        this.$message.error('创建分卷失败: ' + error.message)
      }
    },

    // 保存 默认配置 列
    async saveMultiLanguage() {
      // 保存页面 button label title 属性
      let buttons = this.buttonList;
      let labels = this.labelsList;
      await saveButtonList(buttons)
      await saveButtonList(labels)
    },

    getMultiLanguageList() {
      //首先查询当前按钮的多语言
      searchFunctionButtonList(this.queryButton).then(({data}) => {
        if (data && data.code == 0 ) {
          this.buttons = data.data
        } else {
          // saveButtonList(this.buttonList).then(({data}) => {
          // })
        }
      });
      //其次查询当前标签的多语言
      searchFunctionButtonList(this.queryLabel).then(({data}) => {
        if (data && data.code == 0 ) {
          this.labels = data.data
        } else {
          // saveButtonList(this.buttonList).then(({data}) => {
          // })
        }
      });
    },

  },
  created() {
    // this.factoryList()
    // this.getLanguageList()
  }
}

</script>

<style scoped lang="scss">
/*调节页面button和input的上下间距*/
.customer-css .customer-button{
  margin-top: 25px;
}

/*调节fieldset下的样式*/
.customer-fieldset .customer-item{
  margin-top: -15px;
}

/*fieldset下table的样式*/
.customer-fieldset /deep/ .el-table__header th.is-leaf{
  line-height: 16px;
}

/deep/ .customer-tab .el-tabs__content{
  padding: 0px !important;
}

/* 良品数输入框样式 - 绿色加粗 */
.good-qty-input >>> .el-input__inner {
  font-weight: bold !important;
  color: #67c23a !important;
  font-size: 12px !important;
}

::v-deep .good-qty-input .el-input__inner {
  font-weight: bold !important;
  color: #67c23a !important;
  font-size: 12px !important;
}

/deep/ .good-qty-input .el-input__inner {
  font-weight: bold !important;
  color: #67c23a !important;
  font-size: 12px !important;
}

/* 不良数输入框样式 - 红色加粗 */
.defect-qty-input >>> .el-input__inner {
  font-weight: bold !important;
  color: #f56c6c !important;
  font-size: 12px !important;
}

::v-deep .defect-qty-input .el-input__inner {
  font-weight: bold !important;
  color: #f56c6c !important;
  font-size: 12px !important;
}

/deep/ .defect-qty-input .el-input__inner {
  font-weight: bold !important;
  color: #f56c6c !important;
  font-size: 12px !important;
}

/* 总数显示样式 */
.total-display {
  font-weight: bold;
  color: #303133;
  font-size: 12px;
}

/* 备注列单元格样式 - 使用绝对定位填满 */
.customer-dialog >>> .el-table td:last-child {
  padding: 0 !important;
  position: relative !important;
}

.customer-dialog /deep/ .el-table td:last-child {
  padding: 0 !important;
  position: relative !important;
}

/* 备注包装器 - 绝对定位填满单元格 */
.customer-dialog >>> .remark-wrapper {
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  width: 100% !important;
  height: 100% !important;
}

.customer-dialog /deep/ .remark-wrapper {
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  width: 100% !important;
  height: 100% !important;
}

/* 备注textarea */
.customer-dialog >>> .remark-textarea {
  width: 100% !important;
  height: 100% !important;
}

.customer-dialog >>> .remark-textarea .el-textarea__inner {
  border: none !important;
  padding: 8px 10px !important;
  border-radius: 0 !important;
  resize: none !important;
  width: 100% !important;
  height: 100% !important;
  box-sizing: border-box !important;
  overflow-y: auto !important;
}

.customer-dialog /deep/ .remark-textarea {
  width: 100% !important;
  height: 100% !important;
}

.customer-dialog /deep/ .remark-textarea .el-textarea__inner {
  border: none !important;
  padding: 8px 10px !important;
  border-radius: 0 !important;
  resize: none !important;
  width: 100% !important;
  height: 100% !important;
  box-sizing: border-box !important;
  overflow-y: auto !important;
}

</style>

<style lang="scss">
/* 全局样式 - 良品数和不良数输入框颜色 */
.good-qty-input .el-input__inner {
  font-weight: bold !important;
  color: #67c23a !important;
  font-size: 16px !important;
}

.defect-qty-input .el-input__inner {
  font-weight: bold !important;
  color: #f56c6c !important;
  font-size: 16px !important;
}

/* 备注列样式 - 只针对创建分卷对话框 */
.customer-css .el-table td:last-child {
  padding: 0 !important;
  position: relative !important;
}

/* 备注包装器 - 填满整个单元格 */
.customer-css .remark-wrapper {
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
  right: 0 !important;
  bottom: 0 !important;
  width: 100% !important;
  height: 100% !important;
}

/* 备注textarea容器 */
.customer-css .remark-textarea {
  width: 100% !important;
  height: 100% !important;
}

.customer-css .remark-textarea .el-textarea__inner {
  border: none !important;
  padding: 8px 10px !important;
  border-radius: 0 !important;
  resize: none !important;
  width: 100% !important;
  height: 100% !important;
  box-sizing: border-box !important;
  overflow-y: auto !important;
}

</style>
