<template>
  <div class="aps-sch-page">
    <!-- 顶部工具栏 -->
    <div class="aps-sch-toolbar">
      <span class="aps-sch-label">生产日期：</span>
      <el-date-picker
        v-model="queryDate"
        type="date"
        placeholder="选择生产日期"
        value-format="yyyy-MM-dd"
        size="small"
        style="width:160px"
        @change="handleDateChange"
      />
      <el-button size="small" class="aps-btn-red" icon="el-icon-search" @click="handleQuery">查询</el-button>
      <el-tabs v-model="activeTab" size="small" style="margin:0 0 0 16px;" @tab-click="handleQuery">
        <el-tab-pane label="待审核" name="pending" />
        <el-tab-pane label="已排产" name="scheduled" />
      </el-tabs>
      <div v-if="summaryText" class="aps-sch-summary">
        <span>{{ summaryText }}</span>
      </div>
    </div>

    <!-- 待审核 Tab -->
    <div v-loading="loading" v-show="activeTab === 'pending'" class="detail-card aps-sch-card">
      <div class="detail-card-header">
        <span>待审核产需单明细</span>
        <span v-if="pendingScheduleList.length > 0" style="font-weight:normal;font-size:12px;opacity:0.8;">
          共 {{ pendingScheduleList.length }} 个产需单
        </span>
      </div>
      <div element-loading-text="正在加载待审核产需单..." class="detail-card-body" style="padding:0;">
        <div v-if="pendingScheduleList.length > 0" class="aps-sch-list">
          <div v-for="sch in pendingScheduleList" :key="sch.scheduleId" class="aps-sch-item">
            <!-- 产需单头部：排产单号 + 状态标签 + 操作 -->
            <div class="aps-sch-item-header">
              <div class="aps-sch-item-header-left">
                <span class="aps-sch-no">{{ sch.scheduleNo }}</span>
                <span class="aps-status-tag" :class="'status-' + (sch.scheduleStatus || 1)">{{ statusMap[sch.scheduleStatus] || '待审核' }}</span>
                <span class="aps-sch-header-extra">
                  {{ sch.customerName }} · {{ sch.businessUser }} · {{ sch.deliveryCycle }}天
                </span>
              </div>
              <div class="aps-sch-item-actions">
                <el-button type="text" size="small" style="color:#52c41a;" @click.stop="handleAccept(sch)">接收</el-button>
                <el-button type="text" size="small" style="color:#ff4d4f;" @click.stop="handleReject(sch)">驳回</el-button>
              </div>
            </div>

            <!-- 产需单完整信息表 -->
            <table class="req-info-table">
              <tbody>
                <tr>
                  <td class="req-td-label">排产单号</td>
                  <td class="req-td-value">{{ sch.scheduleNo }}</td>
                  <td class="req-td-label">生产日期</td>
                  <td class="req-td-value">{{ sch.prodDate }}</td>
                </tr>
                <tr>
                  <td class="req-td-label">排产状态</td>
                  <td class="req-td-value">
                    <span class="aps-status-tag" :class="'status-' + (sch.scheduleStatus || 1)">{{ statusMap[sch.scheduleStatus] || '未知' }}</span>
                  </td>
                  <td class="req-td-label">业务员</td>
                  <td class="req-td-value">{{ sch.businessUser }}</td>
                </tr>
                <tr>
                  <td class="req-td-label">联系电话</td>
                  <td class="req-td-value">{{ sch.businessPhone }}</td>
                  <td class="req-td-label">订货单位</td>
                  <td class="req-td-value">{{ sch.customerName }}</td>
                </tr>
                <tr>
                  <td class="req-td-label">交货期(天)</td>
                  <td class="req-td-value">{{ sch.deliveryCycle }}</td>
                  <td class="req-td-label">产品用途</td>
                  <td class="req-td-value">{{ sch.usePurpose }}</td>
                </tr>
                <tr>
                  <td class="req-td-label">品名</td>
                  <td class="req-td-value" colspan="3">{{ sch.productType }}</td>
                </tr>
                <tr>
                  <td class="req-td-label">厚度公差</td>
                  <td class="req-td-value">{{ sch.thicknessTolerance }}</td>
                  <td class="req-td-label">宽度公差</td>
                  <td class="req-td-value">{{ sch.widthTolerance }}</td>
                </tr>
                <tr>
                  <td class="req-td-label">表面质量</td>
                  <td class="req-td-value">{{ sch.surfaceQuality }}</td>
                  <td class="req-td-label">表面处理</td>
                  <td class="req-td-value">{{ sch.surfaceTreatment }}</td>
                </tr>
                <tr>
                  <td class="req-td-label">内径尺寸</td>
                  <td class="req-td-value">{{ sch.innerDiameter }}</td>
                  <td class="req-td-label">外径要求</td>
                  <td class="req-td-value">{{ sch.outerDiameter }}</td>
                </tr>
                <tr>
                  <td class="req-td-label">包装要求</td>
                  <td class="req-td-value">{{ sch.packReq }}</td>
                  <td class="req-td-label">切边要求</td>
                  <td class="req-td-value">{{ sch.cutEdgeReq }}</td>
                </tr>
                <tr>
                  <td class="req-td-label">单件重量</td>
                  <td class="req-td-value">{{ sch.singleCoilWeight }}</td>
                  <td class="req-td-label">交货重量偏差</td>
                  <td class="req-td-value">{{ sch.weightDeviation }}</td>
                </tr>
                <tr>
                  <td class="req-td-label">其他技术要求</td>
                  <td class="req-td-value" colspan="3">{{ sch.otherTechReq }}</td>
                </tr>
                <tr>
                  <td class="req-td-label">付款情况说明</td>
                  <td class="req-td-value" colspan="3">{{ sch.paymentDesc }}</td>
                </tr>
                <tr>
                  <td class="req-td-label">备注</td>
                  <td class="req-td-value" colspan="3">{{ sch.remark }}</td>
                </tr>
                <tr v-if="sch.returnReason">
                  <td class="req-td-label" style="color:#e74c3c;">驳回原因</td>
                  <td class="req-td-value" colspan="3" style="color:#e74c3c;background:#fdecea;">{{ sch.returnReason }}</td>
                </tr>
              </tbody>
            </table>

            <!-- 明细列表 -->
            <div v-if="(sch.detailList || []).length > 0" class="aps-sch-item-details">
              <div class="aps-sch-detail-header">
                <span class="aps-sch-detail-col col-spec">规格</span>
                <span class="aps-sch-detail-col col-material">材质</span>
                <span class="aps-sch-detail-col col-weight">排产吨数</span>
                <span class="aps-sch-detail-col col-type">品名</span>
                <span class="aps-sch-detail-col col-remark">备注</span>
              </div>
              <div
                v-for="(d, di) in sch.detailList"
                :key="di"
                class="aps-sch-detail-row"
                @click="handleDetailClick(sch, d)"
              >
                <span class="aps-sch-detail-col col-spec">{{ d.spec }}</span>
                <span class="aps-sch-detail-col col-material">{{ d.material }}</span>
                <span class="aps-sch-detail-col col-weight">{{ d.scheduleWeight }}</span>
                <span class="aps-sch-detail-col col-type">{{ sch.productType || d.productType || '' }}</span>
                <span class="aps-sch-detail-col col-remark">{{ d.remark }}</span>
              </div>
            </div>
            <div v-else class="aps-sch-item-empty">暂无明细</div>
          </div>
        </div>
        <div v-else-if="!loading" style="padding:40px;text-align:center;color:#909399;">
          {{ hasQueried ? '该日期暂无待审核产需单' : '请选择日期查询' }}
        </div>
      </div>
    </div>

    <!-- 已排产 Tab -->
    <div v-loading="schLoading" v-show="activeTab === 'scheduled'" class="detail-card aps-sch-card">
      <div class="detail-card-header">
        <span>已排产明细</span>
        <div style="display:flex; align-items:center; gap:8px;">
          <span v-if="scheduledItemList.length > 0" style="font-weight:normal;font-size:12px;opacity:0.8;">
            共 {{ scheduledItemList.length }} 条
          </span>
          <span v-if="selectedItems.length >= 2" style="margin-left: auto;">
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-link"
              @click.stop="handleMergePrepare"
            >
              合并选中项 ({{ selectedItems.length }})
            </el-button>
          </span>
          <span v-else style="margin-left: auto;">
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-link"
              disabled
            >
              合并选中项
            </el-button>
          </span>
        </div>
      </div>
      <div element-loading-text="正在加载已排产数据..." class="detail-card-body" style="padding:0;">
        <el-table
          v-if="scheduledItemList.length > 0"
          ref="scheduledTable"
          :data="scheduledItemList"
          border
          size="small"
          class="aps-table"
          :row-class-name="getItemRowClassName"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="45" align="center" />
          <el-table-column label="排产单号" prop="scheduleNo" min-width="140" show-overflow-tooltip />
          <el-table-column label="生产日期" prop="prodDate" width="110" align="center" show-overflow-tooltip />
          <el-table-column label="工序类型" prop="actionType" width="100" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ getActionTypeName(scope.row.actionType) }}
            </template>
          </el-table-column>
          <el-table-column label="排产状态" prop="scheduleStatus" width="90" align="center">
            <template slot-scope="scope">
              <span class="aps-status-tag" :class="'status-' + (scope.row.scheduleStatus || 1)">{{ statusMap[scope.row.scheduleStatus] || '未知' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格" prop="spec" min-width="120" show-overflow-tooltip />
          <el-table-column label="材质" prop="material" width="90" align="center" show-overflow-tooltip />
          <el-table-column label="排产吨数" prop="scheduleWeight" width="100" align="right" show-overflow-tooltip />
          <el-table-column label="品名项" prop="productItem" min-width="100" show-overflow-tooltip />
          <el-table-column label="品名" prop="productType" min-width="90" align="center" show-overflow-tooltip />
          <el-table-column label="订货单位" prop="customerName" min-width="140" show-overflow-tooltip />
          <el-table-column label="业务员" prop="businessUser" width="90" align="center" show-overflow-tooltip />
          <el-table-column label="联系电话" prop="businessPhone" width="110" align="center" show-overflow-tooltip />
          <el-table-column label="交货期(天)" prop="deliveryCycle" width="100" align="center" show-overflow-tooltip />
          <el-table-column label="产品用途" prop="usePurpose" min-width="120" show-overflow-tooltip />
          <el-table-column label="厚度公差" prop="thicknessTolerance" min-width="100" show-overflow-tooltip />
          <el-table-column label="宽度公差" prop="widthTolerance" min-width="100" show-overflow-tooltip />
          <el-table-column label="表面质量" prop="surfaceQuality" min-width="100" show-overflow-tooltip />
          <el-table-column label="表面处理" prop="surfaceTreatment" min-width="100" show-overflow-tooltip />
          <el-table-column label="内径尺寸" prop="innerDiameter" width="90" align="center" show-overflow-tooltip />
          <el-table-column label="外径要求" prop="outerDiameter" width="90" align="center" show-overflow-tooltip />
          <el-table-column label="包装要求" prop="packReq" min-width="100" show-overflow-tooltip />
          <el-table-column label="切边要求" prop="cutEdgeReq" min-width="100" show-overflow-tooltip />
          <el-table-column label="单件重量" prop="singleCoilWeight" width="90" align="center" show-overflow-tooltip />
          <el-table-column label="交货重量偏差" prop="weightDeviation" min-width="110" show-overflow-tooltip />
          <el-table-column label="其他技术要求" prop="otherTechReq" min-width="130" show-overflow-tooltip />
          <el-table-column label="付款情况说明" prop="paymentDesc" min-width="130" show-overflow-tooltip />
          <el-table-column label="单行排产备注" prop="rowRemark" min-width="100" show-overflow-tooltip />
          <el-table-column label="备注" prop="remark" min-width="100" show-overflow-tooltip />
          <el-table-column label="操作" width="150" align="center" fixed="right">
            <template slot-scope="scope">
              <div style="display:flex; justify-content:center; gap:0;">
                <el-button type="text" size="small" style="color:#409EFF;padding:0 6px;" @click="handleEditScheduled(scope.row)">编辑</el-button>
                <el-button type="text" size="small" style="color:#ff4d4f;padding:0 6px;" @click="handleDeleteScheduled(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div v-else-if="!schLoading" style="padding:40px;text-align:center;color:#909399;">
          {{ hasQueried ? '该日期暂无已排产数据' : '请选择日期查询' }}
        </div>
      </div>
    </div>

    <!-- 下钻弹窗（来源订单信息） -->
    <el-dialog title="来源订单信息" :visible.sync="drillDialogVisible" width="600px" append-to-body>
      <div v-if="drillOrder" class="detail-card" style="border:none;box-shadow:none;">
        <div class="detail-card-body">
          <div class="form-grid-2">
            <div class="form-field"><label>订单编号</label><div class="field-value">{{ drillOrder.orderCode }}</div></div>
            <div class="form-field"><label>销售员</label><div class="field-value">{{ drillOrder.salesman }}</div></div>
            <div class="form-field"><label>客户公司</label><div class="field-value">{{ drillOrder.companyName }}</div></div>
            <div class="form-field"><label>联系人</label><div class="field-value">{{ drillOrder.contactPerson }}</div></div>
            <div class="form-field"><label>联系电话</label><div class="field-value">{{ drillOrder.contactWay }}</div></div>
            <div class="form-field"><label>交货日期</label><div class="field-value">{{ drillOrder.deliveryDate }}</div></div>
            <div class="form-field"><label>合同号</label><div class="field-value">{{ drillOrder.contractCode }}</div></div>
            <div class="form-field" style="grid-column:1/3;"><label>备注</label><div class="field-value">{{ drillOrder.remark }}</div></div>
          </div>
        </div>
      </div>
      <div v-else>
        <el-empty description="未找到订单信息" />
      </div>
    </el-dialog>

    <!-- 驳回理由对话框 -->
    <el-dialog title="驳回产需单" :visible.sync="rejectDialogVisible" width="450px" append-to-body :close-on-click-modal="false">
      <el-form ref="rejectForm" :model="rejectForm" label-width="90px" size="small">
        <el-form-item label="排产单号">
          <span style="color:#2c3e50;font-weight:500;">{{ rejectForm.scheduleNo }}</span>
        </el-form-item>
        <el-form-item label="驳回理由" prop="returnReason">
          <el-input v-model="rejectForm.returnReason" type="textarea" :rows="4" placeholder="请填写驳回理由" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="rejectBtnLoading" type="danger" @click="confirmReject">确 定</el-button>
        <el-button @click="rejectDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 已排产明细编辑对话框 -->
    <el-dialog
      :title="editDialogTitle"
      :visible.sync="editDialogVisible"
      width="800px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="editForm" :model="editForm" label-width="110px" size="small">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="排产单号">
              <span style="color:#2c3e50;font-weight:500;">{{ editForm.scheduleNo }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排产状态">
              <el-select v-model="editForm.scheduleStatus" placeholder="请选择排产状态" style="width:100%">
                <el-option v-for="(label, val) in statusMap" :key="val" :label="label" :value="Number(val)" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="工序类型">
              <el-select v-model="editForm.actionType" placeholder="请选择工序类型" clearable filterable style="width:100%">
                <el-option v-for="p in processOptions" :key="p.actionType" :label="p.name" :value="p.actionType" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订货单位">
              <el-input v-model="editForm.customerName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="规格" prop="spec">
              <el-input v-model="editForm.spec" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="材质" prop="material">
              <el-input v-model="editForm.material" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="排产吨数">
              <el-input-number v-model="editForm.scheduleWeight" :min="0" :precision="3" :controls="false" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排产总计划吨数">
              <el-input-number v-model="editForm.totalPlanWeight" :min="0" :precision="3" :controls="false" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="品名">
              <el-input v-model="editForm.productType" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品名项">
              <el-input v-model="editForm.productItem" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="业务员">
              <el-input v-model="editForm.businessUser" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话">
              <el-input v-model="editForm.businessPhone" />
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-row :gutter="16">-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="关联销售合同号">-->
        <!--              <el-input v-model="editForm.relContractNo" />-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item label="订单日期">-->
        <!--              <el-date-picker v-model="editForm.orderDate" type="date" value-format="yyyy-MM-dd" style="width:100%" />-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="交货期(天)">
              <el-input-number v-model="editForm.deliveryCycle" :min="0" :controls="false" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品用途">
              <el-input v-model="editForm.usePurpose" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="厚度公差">
              <el-input v-model="editForm.thicknessTolerance" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="宽度公差">
              <el-input v-model="editForm.widthTolerance" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="表面质量">
              <el-input v-model="editForm.surfaceQuality" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表面处理">
              <el-input v-model="editForm.surfaceTreatment" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="内径尺寸">
              <el-input v-model="editForm.innerDiameter" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="外径要求">
              <el-input v-model="editForm.outerDiameter" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="包装要求">
              <el-input v-model="editForm.packReq" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="切边要求">
              <el-input v-model="editForm.cutEdgeReq" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="单件重量">
              <el-input v-model="editForm.singleCoilWeight" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货重量偏差">
              <el-input v-model="editForm.weightDeviation" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="其他技术要求">
              <el-input v-model="editForm.otherTechReq" type="textarea" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="付款情况说明">
              <el-input v-model="editForm.paymentDesc" type="textarea" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="单行排产备注">
              <el-input v-model="editForm.rowRemark" type="textarea" :rows="2" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="editForm.remark" type="textarea" :rows="2" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="editBtnLoading" type="danger" @click="submitEditForm">确 定</el-button>
        <el-button @click="editDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 合并排产明细对话框 -->
    <el-dialog
      title="合并排产明细"
      :visible.sync="mergeDialogVisible"
      width="850px"
      append-to-body
      :close-on-click-modal="false"
    >
      <div style="margin-bottom:12px;font-size:13px;color:#e67e22;">
        选中 {{ mergeForm.itemCount }} 条明细，请选择一个作为合并模板，下方字段将自动填充，您可修改后确认合并。
      </div>

      <!-- 选择模板 -->
      <el-table :data="mergeSourceRows" border size="small" style="margin-bottom:12px;" @row-click="pickMergeTemplate">
        <el-table-column width="50" align="center">
          <template slot-scope="scope">
            <el-radio v-model="mergeTemplateIndex" :label="scope.$index" @click.native.stop />
          </template>
        </el-table-column>
        <el-table-column label="排产单号" prop="scheduleNo" min-width="130" show-overflow-tooltip />
        <el-table-column label="规格" prop="spec" min-width="100" show-overflow-tooltip />
        <el-table-column label="材质" prop="material" width="80" show-overflow-tooltip />
        <el-table-column label="排产吨数" prop="scheduleWeight" width="90" align="right" />
        <el-table-column label="品名" prop="productType" min-width="80" show-overflow-tooltip />
        <el-table-column label="订货单位" prop="customerName" min-width="120" show-overflow-tooltip />
      </el-table>

      <!-- 合并表单 -->
      <el-form ref="mergeFormRef" :model="mergeForm" label-width="110px" size="small">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="排产单号"><el-input v-model="mergeForm.scheduleNo" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工序类型">
              <el-select v-model="mergeForm.actionType" placeholder="请选择工序类型" clearable filterable style="width:100%">
                <el-option v-for="p in processOptions" :key="p.actionType" :label="p.name" :value="p.actionType" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="订货单位"><el-input v-model="mergeForm.customerName" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格"><el-input v-model="mergeForm.spec" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="材质"><el-input v-model="mergeForm.material" /></el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="排产吨数(累加)">
              <el-input-number v-model="mergeForm.scheduleWeight" :min="0" :precision="3" :controls="false" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品名"><el-input v-model="mergeForm.productType" /></el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="品名项"><el-input v-model="mergeForm.productItem" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务员"><el-input v-model="mergeForm.businessUser" /></el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="联系电话"><el-input v-model="mergeForm.businessPhone" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货期(天)">
              <el-input-number v-model="mergeForm.deliveryCycle" :min="0" :controls="false" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="产品用途"><el-input v-model="mergeForm.usePurpose" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="厚度公差"><el-input v-model="mergeForm.thicknessTolerance" /></el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="宽度公差"><el-input v-model="mergeForm.widthTolerance" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表面质量"><el-input v-model="mergeForm.surfaceQuality" /></el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="表面处理"><el-input v-model="mergeForm.surfaceTreatment" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="内径尺寸"><el-input v-model="mergeForm.innerDiameter" /></el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="外径要求"><el-input v-model="mergeForm.outerDiameter" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="包装要求"><el-input v-model="mergeForm.packReq" /></el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="切边要求"><el-input v-model="mergeForm.cutEdgeReq" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单件重量"><el-input v-model="mergeForm.singleCoilWeight" /></el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="交货重量偏差"><el-input v-model="mergeForm.weightDeviation" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="其他技术要求"><el-input v-model="mergeForm.otherTechReq" /></el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="付款情况说明"><el-input v-model="mergeForm.paymentDesc" /></el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注"><el-input v-model="mergeForm.remark" /></el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="margin-top:8px;font-size:12px;color:#909399;">
        合并后 schedule_detail_ids：{{ mergeForm.scheduleDetailIds }}
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="mergeBtnLoading" type="warning" @click="confirmMerge">确 定 合 并</el-button>
        <el-button @click="mergeDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRequirement,
  updateRequirement
} from '@/api/aps/requirement'
import {
  getCrmOrderInfo,
  listScheduleItem,
  updateScheduleItem,
  delScheduleItem,
  receiveScheduleItem,
  mergeScheduleItem
} from '@/api/aps/schedule'
import { PROCESSES } from '@/utils/meta'

export default {
  name: 'ApsSchedule',
  data() {
    const today = new Date()
    const y = today.getFullYear()
    const m = String(today.getMonth() + 1).padStart(2, '0')
    const d = String(today.getDate()).padStart(2, '0')
    return {
      queryDate: `${y}-${m}-${d}`,
      activeTab: 'pending',
      loading: false,
      schLoading: false,
      hasQueried: false,

      // 待审核
      pendingScheduleList: [],
      summaryText: '',
      statusMap: { 1: '待审核', 2: '已接收', 3: '已驳回' },
      processOptions: PROCESSES,

      // 已排产
      scheduledItemList: [],
      selectedItems: [],
      sourceColorMap: {},

      // 合并对话框
      mergeDialogVisible: false,
      mergeBtnLoading: false,
      mergeTemplateIndex: 0,
      mergeSourceRows: [],
      mergeForm: {
        itemCount: 0, scheduleNo: '', actionType: '', customerName: '', spec: '', material: '',
        scheduleWeight: 0, productType: '', productItem: '', businessUser: '',
        businessPhone: '', deliveryCycle: undefined, usePurpose: '',
        thicknessTolerance: '', widthTolerance: '', surfaceQuality: '',
        surfaceTreatment: '', innerDiameter: '', outerDiameter: '',
        packReq: '', cutEdgeReq: '', singleCoilWeight: '',
        weightDeviation: '', otherTechReq: '', paymentDesc: '',
        remark: '', scheduleDetailIds: ''
      },

      // 驳回
      rejectDialogVisible: false,
      rejectBtnLoading: false,
      rejectForm: {
        scheduleId: null,
        scheduleNo: '',
        returnReason: ''
      },

      // 已排产编辑
      editDialogVisible: false,
      editDialogTitle: '编辑排产明细',
      editBtnLoading: false,
      editForm: this.getEmptyEditForm(),

      // 下钻
      drillDialogVisible: false,
      drillOrder: null
    }
  },
  watch: {
    activeTab() {
      this.selectedItems = []
    }
  },
  created() {
    this.handleQuery()
  },
  methods: {
    getEmptyEditForm() {
      return {
        scheduleId: undefined,
        scheduleNo: '',
        actionType: '',
        prodDate: '',
        scheduleStatus: undefined,
        totalPlanWeight: undefined,
        relContractNo: '',
        businessUser: '',
        businessPhone: '',
        orderDate: '',
        customerName: '',
        deliveryCycle: undefined,
        usePurpose: '',
        productType: '',
        thicknessTolerance: '',
        widthTolerance: '',
        surfaceQuality: '',
        surfaceTreatment: '',
        innerDiameter: '',
        outerDiameter: '',
        packReq: '',
        cutEdgeReq: '',
        singleCoilWeight: '',
        weightDeviation: '',
        otherTechReq: '',
        paymentDesc: '',
        spec: '',
        material: '',
        scheduleWeight: 0,
        productItem: '',
        rowRemark: '',
        remark: ''
      }
    },

    handleDateChange() {
      this.handleQuery()
    },

    handleQuery() {
      if (!this.queryDate) {
        this.$message.warning('请选择生产日期')
        return
      }
      this.hasQueried = true
      if (this.activeTab === 'pending') {
        this.queryPending()
      } else {
        this.queryScheduled()
      }
    },

    // ====== 待审核 ======
    queryPending() {
      this.loading = true
      this.pendingScheduleList = []

      listRequirement({
        prodDate: this.queryDate,
        scheduleStatus: 1,
        pageNum: 1,
        pageSize: 999
      }).then(res => {
        const list = res.rows || []
        this.pendingScheduleList = list

        const totalWeight = list.reduce((sum, sch) => {
          const details = sch.detailList || []
          return sum + details.reduce((s, d) => s + (parseFloat(d.scheduleWeight) || 0), 0)
        }, 0)
        const totalCount = list.reduce((sum, sch) => sum + (sch.detailList || []).length, 0)
        this.summaryText = `共 ${list.length} 个产需单，${totalCount} 条明细，排产总吨数 ${totalWeight.toFixed(3)} 吨`
      }).catch(() => {
        this.pendingScheduleList = []
        this.summaryText = ''
      }).finally(() => {
        this.loading = false
      })
    },

    handleAccept(sch) {
      const details = sch.detailList || []
      if (details.length === 0) {
        this.$message.warning('该产需单无可排产的明细')
        return
      }
      this.$confirm(
        `确认接收产需单「${sch.scheduleNo}」的全部排产明细吗？共 ${details.length} 条明细`,
        '提示',
        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
      ).then(() => {
        this.$message.info('正在处理接收...')
        receiveScheduleItem(sch.scheduleId).then(() => {
          this.$modal.msgSuccess('接收成功，排产明细已写入')
          this.queryPending()
        }).catch(() => {
          this.$modal.msgError('接收失败')
        })
      }).catch(() => {})
    },

    handleReject(sch) {
      this.rejectForm.scheduleId = sch.scheduleId
      this.rejectForm.scheduleNo = sch.scheduleNo
      this.rejectForm.returnReason = ''
      this.rejectDialogVisible = true
      this.$nextTick(() => {
        this.$refs.rejectForm && this.$refs.rejectForm.clearValidate()
      })
    },

    confirmReject() {
      if (!this.rejectForm.returnReason || !this.rejectForm.returnReason.trim()) {
        this.$message.warning('请填写驳回理由')
        return
      }
      this.rejectBtnLoading = true
      updateRequirement({
        scheduleId: this.rejectForm.scheduleId,
        scheduleStatus: 3,
        returnReason: this.rejectForm.returnReason.trim()
      }).then(() => {
        this.$modal.msgSuccess('已驳回')
        this.rejectDialogVisible = false
        this.queryPending()
      }).catch(() => {
        this.$modal.msgError('驳回失败')
      }).finally(() => {
        this.rejectBtnLoading = false
      })
    },

    // ====== 已排产 ======
    queryScheduled() {
      this.schLoading = true
      this.scheduledItemList = []
      this.sourceColorMap = {}
      this.selectedItems = []

      listScheduleItem({ prodDate: this.queryDate, pageNum: 1, pageSize: 999 }).then(res => {
        this.scheduledItemList = (res.rows || []).sort((a, b) => (a.scheduleNo || '').localeCompare(b.scheduleNo || ''))
        try {
          this.sourceColorMap = this.buildGroupColorMap(this.scheduledItemList)
        } catch (e) {
          console.error('buildGroupColorMap error:', e)
          this.sourceColorMap = {}
        }
        const totalWeight = this.scheduledItemList.reduce((sum, d) => {
          const w = parseFloat(d.scheduleWeight)
          return sum + (isNaN(w) ? 0 : w)
        }, 0)
        this.summaryText = `共 ${this.scheduledItemList.length} 条明细，排产总吨数 ${totalWeight.toFixed(3)} 吨`
      }).catch((e) => {
        console.error('queryScheduled error:', e)
        this.scheduledItemList = []
        this.summaryText = ''
      }).finally(() => {
        this.schLoading = false
      })
    },

    handleEditScheduled(row) {
      this.editForm = { ...this.getEmptyEditForm(), ...row }
      // 确保 actionType 为数字类型以匹配下拉选项
      if (this.editForm.actionType != null && typeof this.editForm.actionType !== 'number') {
        this.editForm.actionType = Number(this.editForm.actionType)
      }
      // 确保 scheduleStatus 为数字类型以匹配下拉选项
      if (this.editForm.scheduleStatus != null && typeof this.editForm.scheduleStatus !== 'number') {
        this.editForm.scheduleStatus = Number(this.editForm.scheduleStatus)
      }
      this.editDialogTitle = '编辑排产明细'
      this.editDialogVisible = true
      this.$nextTick(() => {
        this.$refs.editForm && this.$refs.editForm.clearValidate()
      })
    },

    submitEditForm() {
      this.editBtnLoading = true
      updateScheduleItem(this.editForm).then(() => {
        this.$modal.msgSuccess('修改成功')
        this.editDialogVisible = false
        this.queryScheduled()
      }).catch(() => {
        this.$modal.msgError('修改失败')
      }).finally(() => {
        this.editBtnLoading = false
      })
    },

    handleDeleteScheduled(row) {
      this.$confirm(`确认删除排产明细「${row.spec} / ${row.material}」吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delScheduleItem(row.scheduleId).then(() => {
          this.$modal.msgSuccess('删除成功')
          this.queryScheduled()
        }).catch(() => {
          this.$modal.msgError('删除失败')
        })
      }).catch(() => {})
    },

    // ====== 合并 ======
    handleSelectionChange(rows) {
      this.selectedItems = rows
    },

    getItemRowClassName({ row }) {
      const key = row.scheduleNo
      if (!key) return ''
      const colorIndex = this.sourceColorMap[key]
      return colorIndex !== undefined ? `merge-source-${colorIndex}` : ''
    },

    buildGroupColorMap(list) {
      const map = {}
      let colorIdx = 0
      list.forEach(item => {
        const key = item.scheduleNo
        if (!key) return
        if (!(key in map)) {
          map[key] = colorIdx % 5
          colorIdx++
        }
      })
      return map
    },

    handleMergePrepare() {
      if (this.selectedItems.length < 2) {
        this.$message.warning('请至少选择2条排产明细进行合并')
        return
      }
      this.mergeSourceRows = [...this.selectedItems]
      this.mergeTemplateIndex = 0
      this.pickMergeTemplate(this.mergeSourceRows[0])
      this.mergeDialogVisible = true
    },

    pickMergeTemplate(row) {
      const idx = this.mergeSourceRows.indexOf(row)
      if (idx >= 0) this.mergeTemplateIndex = idx
      this.mergeForm = {
        itemCount: this.mergeSourceRows.length,
        scheduleNo: row.scheduleNo || '',
        actionType: row.actionType != null ? Number(row.actionType) : '',
        customerName: row.customerName || '',
        spec: row.spec || '',
        material: row.material || '',
        scheduleWeight: this.mergeSourceRows.reduce((sum, r) => sum + (parseFloat(r.scheduleWeight) || 0), 0),
        productType: row.productType || '',
        productItem: row.productItem || '',
        businessUser: row.businessUser || '',
        businessPhone: row.businessPhone || '',
        deliveryCycle: row.deliveryCycle,
        usePurpose: row.usePurpose || '',
        thicknessTolerance: row.thicknessTolerance || '',
        widthTolerance: row.widthTolerance || '',
        surfaceQuality: row.surfaceQuality || '',
        surfaceTreatment: row.surfaceTreatment || '',
        innerDiameter: row.innerDiameter || '',
        outerDiameter: row.outerDiameter || '',
        packReq: row.packReq || '',
        cutEdgeReq: row.cutEdgeReq || '',
        singleCoilWeight: row.singleCoilWeight || '',
        weightDeviation: row.weightDeviation || '',
        otherTechReq: row.otherTechReq || '',
        paymentDesc: row.paymentDesc || '',
        remark: row.remark || '',
        scheduleDetailIds: this.mergeSourceRows.map(r => r.scheduleDetailIds || '').filter(Boolean).join(',')
      }
    },

    confirmMerge() {
      this.mergeBtnLoading = true
      const ids = this.mergeSourceRows.map(r => r.scheduleId)
      const mergedBo = {
        ...this.mergeForm,
        prodDate: this.queryDate,
        scheduleStatus: 2
      }
      delete mergedBo.itemCount
      mergeScheduleItem({ ids, mergedBo }).then(() => {
        this.$modal.msgSuccess(`合并成功：${ids.length} 条明细合并为 1 条`)
        this.mergeDialogVisible = false
        this.selectedItems = []
        this.queryScheduled()
      }).catch(() => {
        this.$modal.msgError('合并失败')
      }).finally(() => {
        this.mergeBtnLoading = false
      })
    },

    // ====== 下钻 & 辅助方法 ======
    scheduleTotalWeight(sch) {
      const details = sch.detailList || []
      const total = details.reduce((sum, d) => sum + (parseFloat(d.scheduleWeight) || 0), 0)
      return total.toFixed(3)
    },

    getActionTypeName(actionType) {
      const p = this.processOptions.find(item => String(item.actionType) === String(actionType))
      return p ? p.name : (actionType || '')
    },

    handleDetailClick(sch, detail) {
      // 点击明细行查看来源订单
      if (!sch || !sch.orderList || sch.orderList.length === 0) {
        this.$message.warning('未找到关联订单')
        return
      }
      const order = sch.orderList[0]
      getCrmOrderInfo(order.orderId).then(res => {
        this.drillOrder = res.data
        this.drillDialogVisible = true
      }).catch(() => {
        this.$message.warning('未找到来源订单')
      })
    }
  }
}
</script>

<style scoped lang="scss">
@import './scss/aps-theme.scss';

.aps-sch-page {
  height: 100%;
  padding: 8px;
  box-sizing: border-box;
  background: $aps-bg;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

// 工具栏
.aps-sch-toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 16px;
  background: $aps-white;
  border: 1px solid $aps-border;
  border-radius: $aps-radius;
  box-shadow: $aps-shadow-sm;
  flex-shrink: 0;
  flex-wrap: wrap;
}

.aps-sch-label {
  font-size: 13px;
  font-weight: 600;
  color: $aps-text;
  white-space: nowrap;
}

.aps-sch-summary {
  margin-left: auto;
  font-size: 12px;
  color: $aps-text-muted;
  background: $aps-silver-1;
  padding: 4px 12px;
  border-radius: $aps-radius;
  border: 1px solid $aps-border;
}

// 排产卡片
.aps-sch-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
  overflow: hidden;

  .detail-card-body {
    flex: 1;
    overflow: auto;
    min-height: 0;
    overflow-x: auto;
  }
}

// 表格
.aps-table {
  width: 100%;

  ::v-deep th {
    background: $aps-silver-1 !important;
    color: $aps-text !important;
    font-weight: 600 !important;
  }

  ::v-deep .el-table__body tr:hover > td {
    background-color: $aps-red-1 !important;
    cursor: pointer;
  }

  ::v-deep td {
    padding: 6px 8px;
  }
}

// 复用卡片/网格变量
.aps-btn-red {
  @include aps-btn-red;
}

.detail-card {
  background: $aps-white;
  border: 1px solid $aps-border;
  border-radius: $aps-radius;
  box-shadow: $aps-shadow-sm;
  overflow: hidden;
}

.detail-card-header {
  background: linear-gradient(to right, $aps-red-2, $aps-red-3);
  color: white;
  padding: 8px 14px;
  font-size: 13px;
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-shrink: 0;
}

.detail-card-body {
  padding: 14px;
}

.form-grid-2 {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 10px 16px;
}

.form-field {
  display: flex;
  flex-direction: column;
  gap: 3px;
}

.form-field label {
  font-size: 11px;
  color: $aps-text-muted;
  font-weight: 500;
}

.form-field .field-value {
  font-size: 13px;
  color: $aps-text;
  padding: 4px 0;
  border-bottom: 1px solid $aps-silver-mid;
}

// Tabs 覆盖
::v-deep .el-tabs__item {
  font-size: 13px;
  padding: 0 14px;
}

::v-deep .el-tabs__header {
  margin: 0;
}

::v-deep .el-tabs__active-bar {
  background-color: $aps-red-2 !important;
}

::v-deep .el-tabs__item.is-active {
  color: $aps-red-2 !important;
}

// ====== 待审核自定义列表 ======
.aps-sch-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding: 8px;
}

.aps-sch-item {
  background: $aps-white;
  border: 1px solid $aps-border;
  border-radius: $aps-radius;
  box-shadow: $aps-shadow-sm;
  overflow: hidden;
}

.aps-sch-item-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 14px;
  background: linear-gradient(135deg, $aps-silver-1 0%, #f8f9fb 100%);
  border-bottom: 1px solid $aps-border;
}

.aps-sch-item-header-left {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
  min-width: 0;
}

.aps-sch-header-extra {
  font-size: 12px;
  color: $aps-text-muted;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

// 状态标签
.aps-status-tag {
  display: inline-block;
  font-size: 11px;
  padding: 2px 8px;
  border-radius: 3px;
  font-weight: 500;
  white-space: nowrap;

  &.status-1 { background: #fff3e0; color: #e67e22; }
  &.status-2 { background: #e8f5e9; color: #388e3c; }
  &.status-3 { background: #fdecea; color: #e74c3c; }
}

// 产需单信息表
.req-info-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;

  td {
    padding: 5px 10px;
    border: 1px solid $aps-silver-mid;
    vertical-align: middle;
  }

  .req-td-label {
    width: 100px;
    background: $aps-silver-1;
    color: $aps-text-muted;
    font-weight: 500;
    text-align: right;
    white-space: nowrap;
  }

  .req-td-value {
    color: $aps-text;
  }
}

.aps-sch-no {
  color: $aps-red-2;
  font-weight: 600;
  font-size: 13px;
}

.aps-sch-item-actions {
  display: flex;
  gap: 6px;
  flex-shrink: 0;
  margin-left: 12px;
}

// 明细表
.aps-sch-item-details {
  padding: 0;
}

.aps-sch-detail-header {
  display: flex;
  padding: 7px 14px;
  background: $aps-silver-1;
  border-bottom: 1px solid $aps-border;
  font-size: 12px;
  font-weight: 600;
  color: $aps-text;
}

.aps-sch-detail-row {
  display: flex;
  padding: 7px 14px;
  border-bottom: 1px solid $aps-silver-mid;
  font-size: 12px;
  color: $aps-text;
  cursor: pointer;
  transition: background 0.15s;

  &:last-child {
    border-bottom: none;
  }

  &:hover {
    background: $aps-red-1;
  }
}

.aps-sch-detail-col {
  &.col-spec { flex: 1.2; min-width: 100px; }
  &.col-material { flex: 0 0 80px; text-align: center; }
  &.col-weight { flex: 0 0 90px; text-align: right; font-weight: 500; }
  &.col-type { flex: 1; min-width: 80px; padding: 0 8px; }
  &.col-remark { flex: 1; min-width: 80px; }
}

.aps-sch-item-empty {
  padding: 20px;
  text-align: center;
  color: $aps-text-muted;
  font-size: 12px;
}

// ====== 合并候选行颜色高亮（同一源排产单 → 同色） ======
::v-deep .el-table__body tr.merge-source-0 > td {
  background-color: #f0f5ff !important;
}
::v-deep .el-table__body tr.merge-source-1 > td {
  background-color: #f6ffed !important;
}
::v-deep .el-table__body tr.merge-source-2 > td {
  background-color: #fff7e6 !important;
}
::v-deep .el-table__body tr.merge-source-3 > td {
  background-color: #f9f0ff !important;
}
::v-deep .el-table__body tr.merge-source-4 > td {
  background-color: #fff0f6 !important;
}
</style>
