<template>
  <!-- 模板部分保持不变 -->
  <div>
    <el-card>
      <div>
        <span class="show-text">订单号:</span>
        <el-input v-model="orderNo" placeholder="请输入订单号" clearable style="width: 100px; margin-right: 10px" />
        <!-- <span class="show-text">合同号:</span>
        <el-input v-model="contractNo" placeholder="请输入合同号" clearable style="width: 130px; margin-right: 10px" /> -->
        <span class="show-text">零件编码:</span>
        <el-input v-model="productCode" placeholder="请输入零件编码" clearable style="width: 150px; margin-right: 10px" />
        <span class="show-text">零件名称:</span>
        <el-input v-model="productName" placeholder="请输入零件名称" clearable style="width: 100px; margin-right: 10px" />
        <span class="show-text">检测人:</span>
        <el-select
          v-model="checker"
          placeholder="请选择检测人"
          clearable
          style="width: 150px; margin-right: 10px"
          filterable
        >
          <el-option
            v-for="item in checkerList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        
        <span class="show-text">质检类型:</span>
        <el-select
          v-model="QualityStatus"
          clearable
          placeholder="请选择质检类型"
          style="width: 150px; margin-right: 10px"
        >
          <el-option label="全部" value="10" />
          <el-option label="收检" value="0" />
          <el-option label="终检" value="1" />
          <el-option label="来料检验" value="2" />
          <el-option label="退库检验" value="3" />
        </el-select>
        <span class="show-text">质检日期起:</span>
        <el-date-picker 
          v-model="startDate" 
          type="date"
          placeholder="选择开始日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          style="width: 150px; margin-right: 10px" />
        <span class="show-text">质检日期止:</span>
        <el-date-picker 
          v-model="endDate" 
          type="date"
          placeholder="选择结束日期"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          style="width: 150px; margin-right: 10px" />
        <el-button :disabled="!!loading" icon="el-icon-search" plain type="primary" @click="searchTable()">查询</el-button>
        <!-- <el-button style="width: 100px;" icon="el-icon-download" type="primary"  @click="exportExcel">Excel导出</el-button> -->
      </div>
      
      <el-tabs v-model="activeTab" type="card" class="custom-tabs">
        <el-table 
          v-loading="loading" 
          :data="tableData" 
          :height="'67vh'" 
          border
          element-loading-background="rgba(0, 0, 0, 0.2)" 
          element-loading-spinner="el-icon-loading"
          highlight-current-row 
          size="mini" 
          style="width: 100%;margin-top: 20px;" 
          tooltip-effect="dark"
          :row-class-name="tableRowClassName"  
          @row-click="handleRowClick">
          
          <el-table-column align="center" label="序号" type="index" width="50" fixed />
          <el-table-column align="center" prop="质检类型" label="质检类型" width="80" fixed />
          <el-table-column align="center" prop="零件编码" label="零件编码" width="220" fixed />
          <el-table-column align="center" prop="零件名称" label="零件名称" width="190" />
          <el-table-column align="center" prop="内部合同号" label="内部合同号" width="100" />
          <el-table-column align="center" prop="计划号" label="计划号" width="80" />
          <el-table-column align="center" prop="工序名称" label="工序名称" width="100" />
          <el-table-column align="center" prop="工位名称" label="工位名称" width="100" />
          <el-table-column align="center" prop="供应商代码" label="供应商代码" width="120" />
          <el-table-column align="center" prop="检验数量" label="检验数量" width="120" />
          <el-table-column align="center" prop="合格数" label="合格数" width="120" />
          <el-table-column align="center" prop="不合格数" label="不合格数" width="120" />
          <el-table-column align="center" prop="检测人" label="检测人" width="100" />
          <el-table-column align="center" label="检测时间" width="160">
            <template slot-scope="scope">
              {{ formatDateTime(scope.row.检测时间) }}
            </template>
          </el-table-column>
          
          <el-table-column align="center" prop="检测说明" label="检测说明" width="160"/>
          <el-table-column label="操作" align="center" width="100px"  fixed="right">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="mini"
                style="margin-right: 5px; padding:0; width:auto"
                @click="print(scope.row)">打印
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <div class="block" style="margin-top: 10px;">
          <el-pagination
            :current-page="pageCurrent"
            :page-sizes="[20, 50, 100]"
            :page-size="pageSize"
            :total="total1"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChanges"
            @current-change="handleCurrentChanges" />
        </div>
      </el-tabs>
    </el-card>
    <div class="print-page2" style=" display: none; width: 20cm;height: 11.5cm;background-color: #fff; page-break-after: always;" >
      <div style="margin-bottom: 20px;">
        <div style="display: flex;">
          <div style="width: 30%;
            height: 40px;
            background: url(/static/img/logo.6454a812.png);
            background-size: contain;
            background-repeat: no-repeat;
            "></div>
          <div style="width: 40%;text-align: center;font-size: 25px;line-height: 40px;">不合格品处置单</div>
        </div>
      </div>
      <div class="field-container">
        <!-- 第一行：订单号、合同号、发生日期 -->
        <div class="field-row">
          <div class="field-group" style="width: 33%;">
            <span class="field-label">订单号</span>
            <span class="field-value">{{ printData2.计划号  }}</span>
          </div>
          <div class="field-group">
            <span class="field-label" style="width: 33%;" >合同号</span>
            <span class="field-value">{{ printData2.内部合同号 }}</span>
          </div>
          <div class="field-group">
            <span class="field-label"  >检测时间</span>
            <span class="field-value">{{ printData2.检测时间 }}</span>
          </div>
        </div>
        <!-- 第三行：物料编码、零件名称 -->
        <div class="field-row">
          <div class="field-group" style="width: 60%;">
            <span class="field-label">物料编码</span>
            <span class="field-value">{{ printData2.零件编码 }}</span>
          </div>
          <div class="field-group">
            <span class="field-label">物料名称</span>
            <span class="field-value">{{ printData2.零件名称  }}</span>
          </div>
        </div>
        <div class="field-row">
          <div class="field-group" style="width: 33%;">
            <span class="field-label">供应商编码</span>
            <span class="field-value"></span>
          </div>
          <div class="field-group" style="width: 33%;">
            <span class="field-label">批次号</span>
            <span class="field-value"></span>
          </div>
          <div class="field-group" >
            <span class="field-label">采购员</span>
            <span class="field-value"></span>
          </div>
        </div>
        <!-- 第二行：发生场所、发现人员、供应商编码、批次号 -->
        <div class="field-row">
          <div class="field-group" style="width: 33%;">
            <span class="field-label">发生日期</span>
            <span class="field-value"></span>
          </div>
          <div class="field-group" style="width: 33%;">
            <span class="field-label">发生场所</span>
            <span class="field-value"></span>
          </div>
          <div class="field-group">
            <span class="field-label">发现人员</span>
            <span class="field-value"></span>
          </div>
        
        </div>
        <!-- 第四行：加工数量、不良数量、质检员 -->
        <div class="field-row">
          <div class="field-group" style="width: 33%;">
            <span class="field-label">加工数量</span>
            <span class="field-value">{{ printData2.检验数量 }}</span>
          </div>
          <div class="field-group" style="width: 33%;">
            <span class="field-label">不良数量</span>
            <span class="field-value">{{ printData2.不合格数 }}</span>
          </div>
          <div class="field-group">
            <span class="field-label">质检员</span>
            <span class="field-value">{{ printData2.检测人}}</span>
          </div>
        </div>
        
        <!-- 第五行：不良内容描述 (占两行) -->
        <div class="field-row" style="height: 40px;">
          <div class="field-group" style="width: 100%; height: 100%;">
            <span class="field-label" style="width: 20%; height: 100%; line-height: 60px;">不良内容描述</span>
            <span class="field-value" style="width: 80%; height: 100%;">{{ printData2.检测说明 }}</span>
          </div>
        </div>
        
        <!-- 第六行：质量部处理措施 (占两行) -->
        <div class="field-row" style="height: 40px;">
          <div class="field-group" style="width: 100%; height: 100%;">
            <span class="field-label" style="width: 20%; height: 100%; line-height: 60px;">质量部处理措施</span>
            <span class="field-value" style="width: 80%; height: 100%; display: flex; align-items: center; gap: 20px;">
              <span>□让步放行</span>
              <span>□返工返修</span>
              <span>□报废</span>
              <span>□其他</span>
            </span>
          </div>
        </div>
        
        <!-- 第七行：采购处理措施 (占两行) -->
        <div class="field-row" style="height: 40px;">
          <div class="field-group" style="width: 100%; height: 100%;">
            <span class="field-label" style="width: 20%; height: 100%; line-height: 60px;">采购处理措施</span>
            <span class="field-value" style="width: 80%; height: 100%; display: flex; align-items: center; gap: 20px;">
              <span>□费用扣除</span>
              <span>□返工返修</span>
              <span>□退换货</span>
              <span>□其他</span>
            </span>
          </div>
          
        </div>
        
        <!-- 第八行：采购员、备注 -->
        <div class="field-row">
          <div class="field-group">
            <span class="field-label">备注</span>
            <span class="field-value"></span>
          </div>
        </div>
        
        <!-- 第九行：配发部门 -->
        <div class="field-row">
          <div class="field-group" style="width: 100%;">
            <span class="field-label" style="width: 10%;">配发部门</span>
            <span class="field-value" style="width: 90%; display: flex; gap: 20px; flex-wrap: wrap;">
              <span>□生产部</span>
              <span>□采购部</span>
              <span>□工艺部</span>
              <span>□技术部</span>
              <span>□机加车间</span>
              <span>□库房</span>
              <span>□质量部</span>
              <span>□其他</span>
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import $ from 'jquery'
export default {
  data() {
    return {
      // 分页
      pageCurrent: 1,
      pageSize: 20,
      total1: 0,
      
      // 搜索条件
      QualityStatus:'10',
      startDate:null,
      endDate:null,
      orderNo:'',
      contractNo:'',
      productCode:'',
      productName:'',

      
      // 表格数据
      loading: false,
      activeTab: 'first',
      tableData: [],

      // 新增相关数据
      orderList: [],
      exporting: false,
      // processList: [],
      // personnelList: [],
      printData2:[],
      checkerList: [],
      checker: "",
      checkerLabel: "",
    }
  },
  
  mounted() {
    this.searchTable()
    this.getCheckerList();
  },
  
  methods: {
    getCheckerList() {
      this.checkerList = [];
      var Data = this.CreateData("11", "人员管理_人员信息查询_质检部门_查询");
      this.ExecDatabase(Data).then((response) => {
        for (let i = 0; i < response.data.length; i++) {
          this.checkerList.push({
            label: response.data[i].Personnel_Name,
            value: response.data[i].Personnel_Number,
          });
        }
      });
    },
    // ============ 表格相关方法 ============
    tableRowClassName({ row, rowIndex }) {
      if (!row.结束时间 || row.结束时间 === '') {
        return 'row-without-endtime'
      }
      return ''
    },
    
    handleRowClick(row) {
      this.currentTask = row
    },
    
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    
    // ============ 分页方法 ============
    handleSizeChanges(val) {
      this.pageCurrent = 1
      this.pageSize = val
      this.searchTable()
    },
    
    handleCurrentChanges(val) {
      this.pageCurrent = val
      this.searchTable()
    },
    
    searchTable() {
      this.loading = true
      
      var param = []
      param.push(["质检类型", this.QualityStatus]);
      param.push(["开始日期", this.startDate]);
      param.push(["结束日期", this.endDate]);
      param.push(["订单号", this.orderNo ]);
      param.push(["合同号", this.contractNo ]);
      param.push(["零件编码", this.productCode ]);
      param.push(["零件名称", this.productName ]);
      const selectedChecker = this.checkerList.find(
        (item) => item.value === this.checker
      );
      param.push(['检测人', selectedChecker ? selectedChecker.label : 0])
      param.push(['PageCurrent', this.pageCurrent])
      param.push(['pageSize', this.pageSize])
      
      param.push(['PageCount', '1111', 'int', '1'])
      param.push(['ItemCount', '1111', 'int', '1'])
      
      console.log(selectedChecker)
      var Data = this.CreateData('11', '质量管理_不合格品处置_查询', param)
      this.ExecDatabase(Data).then(response => {
        this.tableData = response.data.result || []
        this.total1 = parseInt(response.data.output[0].ItemCount)
        this.loading = false
      }).catch(error => {
        this.$message.error('查询失败：' + error.message)
        this.loading = false
      })
    },
    //打印
    print(row){
      this.printData2 = row
      console.log(this.printData2)
      this.numname = this.$store.state.user.name
      try {
        this.$nextTick(() => {
          setTimeout(() => {
            this.executePrint2()
          }, 500)
        })
      } catch (error) {
        console.error('获取打印数据失败:', error)
        this.$message.error('获取打印数据失败')
      } finally {
        this.loading = false
      }
    },
    executePrint2() {
      return new Promise((resolve, reject) => {
        this.historyVisible = false
        try {
          const originalStyles = {}
          $('.print-page2').each(function(index) {
            originalStyles[index] = $(this).attr('style')
          })
          
          const body = $('body')
          
          // 隐藏原始内容
          body.children().hide()
          
          // 创建打印容器
          const printContainer = $('<div class="print-container"></div>')
          
          // 复制所有打印页面到打印容器
          $('.print-page2').each(function() {
            const pageClone = $(this).clone()
            pageClone.css({
              display: 'block',
              width: '20cm',
              height: '11.5cm',
              'background-color': '#fff',
              'page-break-after': 'always',
              margin: '0',
              padding: '0'
            })
            printContainer.append(pageClone)
          })
          
          // 添加到body
          body.append(printContainer)
          
          // 打印后恢复
          const restorePage = () => {
            try {
              printContainer.remove()
              body.children().show()
              
              // 恢复原始样式
              $('.print-page2').each(function(index) {
                if (originalStyles[index]) {
                  $(this).attr('style', originalStyles[index])
                } else {
                  $(this).css('display', 'none')
                }
              })
              
              if (window.matchMedia) {
                window.matchMedia('print').removeListener(handlePrintChange)
              }
              
              resolve()
            } catch (error) {
              reject(error)
            }
          }
          
          const handlePrintChange = (mql) => {
            if (!mql.matches) {
              restorePage()
            }
          }
          
          // 添加打印状态监听
          if (window.matchMedia) {
            window.matchMedia('print').addListener(handlePrintChange)
          }
          
          // 设置超时恢复（备用）
          setTimeout(restorePage, 5000)
          
          // 触发打印
          setTimeout(() => {
            window.print()
          }, 1000);
          
          
        } catch (error) {
          reject(error)
        }
      })
    },
    // ============ 工具方法 ============
    
    
    getCurrentUser() {
      return this.$store.state.user.name
    },
    formatDate(date) {
      if (!date) return ''
      return date.split(' ').length > 1 ? date.split(' ')[0] : date
    },
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      }).replace(/\//g, '-')
    },

  }
}
</script>

<style scoped>
.search-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.show-text {
  white-space: nowrap;
}

.custom-tabs {
  margin-top: 10px;
}

.dialog-footer {
  text-align: center;
}
.field-container {
      border: 1px solid #000;
      border-bottom:0px
  }
  .field-row {
      display: flex;
      width: 100%;
      border-bottom: 1px solid #000;
  }
  .field-group {
      display: flex;
      width: 25%;
      align-items: stretch;
      border-right: 1px solid #000;
  }
  .field-group:last-child {
      border-right: none;
  }
  .field-label {
      width: 40%;
      color: #000;
      text-align: right;
      padding: 8px 5px;
      border-right: 1px solid #000;
      display: flex;
      align-items: center;
      justify-content: flex-end;
  }
  .field-value {
      width: 60%;
      color: #303133;
      word-break: break-word;
      overflow-wrap: break-word;
      padding: 12px 10px;
      display: flex;
      align-items: center;
  }
/* ::v-deep .row-without-endtime {
  background-color: #f56c6c !important;
  color: #000000 !important;
} */
</style>