<template>
  <div class="app-container nd3-phased-product">
    <!-- 顶部查询 -->
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true" label-width="90px">
      <el-form-item label="查询模式">
        <el-radio-group v-model="queryMode" size="small">
          <el-radio-button label="single">单主产品</el-radio-button>
          <el-radio-button label="multi">多主产品联合试算</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="项目检索" prop="keyword">
        <el-select
          v-model="queryParams.keyword"
          filterable
          remote
          reserve-keyword
          placeholder="请输入关键字检索"
          :remote-method="querySearch"
          :loading="searchLoading"
          clearable
          style="width: 260px"
          @change="handleSelect"
        >
          <el-option
            v-for="(item, index) in searchOptions"
            :key="index"
            :label="item.productionOrderNo ? (item.productionOrderNo + ' - ' + item.productName) : item.productName"
            :value="index"
          >
            <div style="line-height: 1.4; padding: 4px 0;">
              <div>{{ item.productionOrderNo || '无令号' }}</div>
              <div style="font-size: 12px; color: #999;">
                {{ item.productName }} <span v-if="item.productCode">({{ item.productCode }})</span>
              </div>
            </div>
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="当前令号" prop="productionOrderNo">
        <el-input
          v-model="queryParams.productionOrderNo"
          placeholder="生产令号(与图号二选一)"
          clearable
          style="width: 180px"
        />
      </el-form-item>

      <el-form-item v-if="queryMode === 'single'" label="主产品图号" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="主产品图号(与令号二选一)"
          clearable
          style="width: 180px"
        />
      </el-form-item>

      <el-form-item v-if="queryMode === 'single'" label="投产量" prop="inputQty">
        <el-input-number
          v-model="queryParams.inputQty"
          :min="1"
          placeholder="试算投产量"
          controls-position="right"
          style="width: 130px"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" :loading="loading" @click="handleQuery">查询</el-button>
        <el-button
          v-if="queryMode === 'multi'"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExportCustomKit"
        >导出</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 多主产品投单量 -->
    <el-card v-if="queryMode === 'multi'" shadow="never" class="mb-20">
      <div slot="header" class="parent-header">
        <span style="font-weight: bold;">销售投单量（可添加多个相似 BOM 主产品）</span>
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="addParentRow">添加主产品</el-button>
      </div>
      <el-table :data="parentInputs" border size="small">
        <el-table-column label="物料编码" min-width="180">
          <template slot-scope="scope">
            <el-input v-model="scope.row.materialCode" placeholder="如 LTBZF.0" clearable size="small" />
          </template>
        </el-table-column>
        <el-table-column label="投单量" width="160" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.inputQty" :min="1" controls-position="right" size="small" style="width: 120px" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="mini" :disabled="parentInputs.length <= 1" @click="removeParentRow(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div v-if="reportData && queryMode === 'single'" v-loading="loading">
      <div style="margin-bottom: 15px; font-size: 14px; color: #606266;">
        <strong>可生产套数 (BOM齐套)：</strong>
        <span style="font-size: 18px; font-weight: bold; color: #E6A23C;">{{ reportData.maxBuildQty || 0 }}</span>
      </div>

      <!-- BOM 头 -->
      <el-descriptions v-if="reportData.bomHeader" title="BOM" :column="3" border class="mb-20">
        <el-descriptions-item label="版本">{{ reportData.bomHeader.bomNumber }}</el-descriptions-item>
        <el-descriptions-item label="父项">{{ reportData.bomHeader.materialCode }}</el-descriptions-item>
        <el-descriptions-item label="名称">{{ reportData.bomHeader.materialName }}</el-descriptions-item>
      </el-descriptions>

      <!-- 主产品区 -->
      <el-card v-if="reportData.mainProduct" shadow="never" class="mb-20">
        <div slot="header" style="font-weight: bold; font-size: 15px;">
          主产品：{{ reportData.mainProduct.productName || '-' }} ({{ reportData.mainProduct.productCode || '-' }})
        </div>
        <el-space class="ml-4">
          <el-tag type="info" style="cursor: pointer" @click="openDrill('库存', reportData.mainProduct.stockDrillRows, reportData.mainProduct.productCode)">
            库存 {{ reportData.mainProduct.stockQty || 0 }}
          </el-tag>
          <el-tag type="success" style="cursor: pointer; margin-left: 10px;" @click="openDrill('发货', reportData.mainProduct.deliverDrillRows, reportData.mainProduct.productCode)">
            发货 {{ reportData.mainProduct.deliverQty || 0 }}
          </el-tag>
          <el-tag type="warning" style="cursor: pointer; margin-left: 10px;" @click="openDrill('在途', reportData.mainProduct.transitMoRows, reportData.mainProduct.productCode)">
            在途 {{ reportData.mainProduct.transitQty || 0 }}
          </el-tag>
        </el-space>
      </el-card>

      <!-- 子项区 -->
      <el-tabs v-model="activeTab" type="border-card" class="mb-20">
        <el-tab-pane :label="`自制子项 (${reportData.subItems && reportData.subItems.selfMade ? reportData.subItems.selfMade.length : 0})`" name="selfMade">
          <el-table :data="reportData.subItems && reportData.subItems.selfMade ? reportData.subItems.selfMade : []" border size="small" max-height="600">
            <el-table-column prop="partCode" label="部件图号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="partName" label="部件名称" min-width="140" show-overflow-tooltip />
            <el-table-column prop="materialCode" label="子项编码" min-width="140" show-overflow-tooltip />
            <el-table-column prop="materialName" label="子项名称" min-width="160" show-overflow-tooltip />
            <el-table-column prop="materialType" label="类型" width="70" align="center">
              <template slot-scope="scope">
                <el-tag size="mini" type="primary">{{ scope.row.materialType }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="requiredQty" label="单台用量" width="80" align="right" />
            <el-table-column prop="stockQty" label="库存" width="90" align="right">
              <template slot-scope="scope">
                <el-link type="primary" :underline="false" style="color: #606266; text-decoration: underline;" @click="openDrill('库存', scope.row.stockDrillRows, scope.row.materialCode)">
                  {{ scope.row.stockQty || 0 }}
                </el-link>
              </template>
            </el-table-column>
            <el-table-column prop="noPickedQty" label="未领料" width="90" align="right" />
            <el-table-column label="在途" align="center">
              <el-table-column prop="transitMoQty" label="MO在途" width="90" align="right">
                <template slot-scope="scope">
                  <el-popover v-if="scope.row.transitMoRows && scope.row.transitMoRows.length > 0" trigger="hover" placement="top" width="250">
                    <div style="max-height: 200px; overflow-y: auto;">
                      <div style="font-weight: bold; margin-bottom: 5px;">生产在途明细：</div>
                      <div v-for="(item, idx) in scope.row.transitMoRows" :key="idx" style="margin-top: 5px; font-size: 13px; border-bottom: 1px solid #ebeef5; padding-bottom: 4px;">
                        令号：<span>{{ item.sclh || '(无令号)' }}</span><br>
                        单号：<span style="color: #409EFF">{{ item.billNo || item.orderNo || '-' }}</span><br>
                        未入库：<span style="color: #E6A23C">{{ item.notInstockQty != null ? item.notInstockQty : (item.qty || item.orderQty || 0) }}</span> |
                        交期：{{ item.planFinishDate ? item.planFinishDate.substring(0, 10) : '-' }}
                      </div>
                    </div>
                    <div slot="reference" style="cursor: pointer; color: #67c23a; text-decoration: underline;">
                      {{ scope.row.transitMoQty || 0 }}
                    </div>
                  </el-popover>
                  <span v-else>{{ scope.row.transitMoQty || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="transitPoQty" label="PO在途" width="90" align="right">
                <template slot-scope="scope">
                  <el-popover v-if="scope.row.transitPoRows && scope.row.transitPoRows.length > 0" trigger="hover" placement="top" width="250">
                    <div style="max-height: 200px; overflow-y: auto;">
                      <div style="font-weight: bold; margin-bottom: 5px;">采购在途明细：</div>
                      <div v-for="(item, idx) in scope.row.transitPoRows" :key="idx" style="margin-top: 5px; font-size: 13px; border-bottom: 1px solid #ebeef5; padding-bottom: 4px;">
                        令号：<span>{{ item.sclh || '(无令号)' }}</span><br>
                        单号：<span style="color: #409EFF">{{ item.billNo || item.orderNo || '-' }}</span><br>
                        未入库：<span style="color: #E6A23C">{{ item.notInstockQty != null ? item.notInstockQty : (item.qty || item.orderQty || 0) }}</span> |
                        交期：{{ item.planFinishDate ? item.planFinishDate.substring(0, 10) : '-' }}
                      </div>
                    </div>
                    <div slot="reference" style="cursor: pointer; color: #409eff; text-decoration: underline;">
                      {{ scope.row.transitPoQty || 0 }}
                    </div>
                  </el-popover>
                  <span v-else>{{ scope.row.transitPoQty || 0 }}</span>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column prop="expectedAvailableQty" label="预计可用" width="90" align="right">
              <template slot-scope="scope">
                <span :style="{ color: scope.row.expectedAvailableQty < 0 ? '#f56c6c' : '#67c23a', fontWeight: 'bold' }">
                  {{ scope.row.expectedAvailableQty || 0 }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane :label="`外购子项 (${reportData.subItems && reportData.subItems.purchase ? reportData.subItems.purchase.length : 0})`" name="purchase">
          <el-table :data="reportData.subItems && reportData.subItems.purchase ? reportData.subItems.purchase : []" border size="small" max-height="600">
            <el-table-column prop="partCode" label="部件图号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="partName" label="部件名称" min-width="140" show-overflow-tooltip />
            <el-table-column prop="materialCode" label="子项编码" min-width="140" show-overflow-tooltip />
            <el-table-column prop="materialName" label="子项名称" min-width="160" show-overflow-tooltip />
            <el-table-column prop="materialType" label="类型" width="70" align="center">
              <template slot-scope="scope">
                <el-tag size="mini" type="warning">{{ scope.row.materialType }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="requiredQty" label="单台用量" width="80" align="right" />
            <el-table-column prop="stockQty" label="库存" width="90" align="right">
              <template slot-scope="scope">
                <el-link type="primary" :underline="false" style="color: #606266; text-decoration: underline;" @click="openDrill('库存', scope.row.stockDrillRows, scope.row.materialCode)">
                  {{ scope.row.stockQty || 0 }}
                </el-link>
              </template>
            </el-table-column>
            <el-table-column prop="noPickedQty" label="未领料" width="90" align="right" />
            <el-table-column label="在途" align="center">
              <el-table-column prop="transitMoQty" label="MO在途" width="90" align="right">
                <template slot-scope="scope">
                  <el-popover v-if="scope.row.transitMoRows && scope.row.transitMoRows.length > 0" trigger="hover" placement="top" width="250">
                    <div style="max-height: 200px; overflow-y: auto;">
                      <div style="font-weight: bold; margin-bottom: 5px;">生产在途明细：</div>
                      <div v-for="(item, idx) in scope.row.transitMoRows" :key="idx" style="margin-top: 5px; font-size: 13px; border-bottom: 1px solid #ebeef5; padding-bottom: 4px;">
                        令号：<span>{{ item.sclh || '(无令号)' }}</span><br>
                        单号：<span style="color: #409EFF">{{ item.billNo || item.orderNo || '-' }}</span><br>
                        未入库：<span style="color: #E6A23C">{{ item.notInstockQty != null ? item.notInstockQty : (item.qty || item.orderQty || 0) }}</span> |
                        交期：{{ item.planFinishDate ? item.planFinishDate.substring(0, 10) : '-' }}
                      </div>
                    </div>
                    <div slot="reference" style="cursor: pointer; color: #67c23a; text-decoration: underline;">
                      {{ scope.row.transitMoQty || 0 }}
                    </div>
                  </el-popover>
                  <span v-else>{{ scope.row.transitMoQty || 0 }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="transitPoQty" label="PO在途" width="90" align="right">
                <template slot-scope="scope">
                  <el-popover v-if="scope.row.transitPoRows && scope.row.transitPoRows.length > 0" trigger="hover" placement="top" width="250">
                    <div style="max-height: 200px; overflow-y: auto;">
                      <div style="font-weight: bold; margin-bottom: 5px;">采购在途明细：</div>
                      <div v-for="(item, idx) in scope.row.transitPoRows" :key="idx" style="margin-top: 5px; font-size: 13px; border-bottom: 1px solid #ebeef5; padding-bottom: 4px;">
                        令号：<span>{{ item.sclh || '(无令号)' }}</span><br>
                        单号：<span style="color: #409EFF">{{ item.billNo || item.orderNo || '-' }}</span><br>
                        未入库：<span style="color: #E6A23C">{{ item.notInstockQty != null ? item.notInstockQty : (item.qty || item.orderQty || 0) }}</span> |
                        交期：{{ item.planFinishDate ? item.planFinishDate.substring(0, 10) : '-' }}
                      </div>
                    </div>
                    <div slot="reference" style="cursor: pointer; color: #409eff; text-decoration: underline;">
                      {{ scope.row.transitPoQty || 0 }}
                    </div>
                  </el-popover>
                  <span v-else>{{ scope.row.transitPoQty || 0 }}</span>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column prop="expectedAvailableQty" label="预计可用" width="90" align="right">
              <template slot-scope="scope">
                <span :style="{ color: scope.row.expectedAvailableQty < 0 ? '#f56c6c' : '#67c23a', fontWeight: 'bold' }">
                  {{ scope.row.expectedAvailableQty || 0 }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 投产量试算区 -->
      <el-card v-if="reportData.deployRows && reportData.deployRows.length > 0" shadow="never" class="mb-20">
        <div slot="header" style="font-weight: bold;">
          投产量试算 
          <el-tag size="mini" type="success" style="margin-left: 10px;">试算数量: {{ queryParams.inputQty }}</el-tag>
          <span style="font-size: 12px; color: #909399; font-weight: normal; margin-left: 15px;">
            计算说明：<span style="color: #606266">需投数量 = 试算数量 × 单台用量</span> &nbsp;&nbsp;|&nbsp;&nbsp; <span style="color: #606266">投后余量 = 可用数量 - 需投数量</span> &nbsp;&nbsp;|&nbsp;&nbsp; <span style="color: #606266">仍须补投 = 投后余量 < 0 时的缺口</span>
          </span>
        </div>
        <el-table :data="reportData.deployRows" border size="small" max-height="400">
          <el-table-column prop="materialCode" label="物料编码" min-width="140" show-overflow-tooltip />
          <el-table-column prop="materialName" label="物料名称" min-width="160" show-overflow-tooltip />
          <el-table-column prop="needQty" label="需投数量" width="100" align="right" />
          <el-table-column label="投后余量" width="100" align="right">
            <template slot="header">
              投后余量
              <el-tooltip class="item" effect="dark" content="投后余量 = 可用数量 - 需投数量" placement="top">
                <i class="el-icon-question" style="color: #909399; margin-left: 2px;"></i>
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              <span :style="{ color: getBalanceQty(scope.row) < 0 ? '#f56c6c' : '#67c23a', fontWeight: 'bold' }">
                {{ getBalanceQty(scope.row) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="remainDeployQty" label="仍须补投" width="100" align="right">
            <template slot-scope="scope">
              <span :style="{ color: scope.row.remainDeployQty > 0 ? '#f56c6c' : 'inherit', fontWeight: scope.row.remainDeployQty > 0 ? 'bold' : 'normal' }">
                {{ scope.row.remainDeployQty || 0 }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 多主产品联合试算结果 -->
    <div v-if="reportData && queryMode === 'multi'" v-loading="loading">
      <el-card v-if="reportData.parentProducts && reportData.parentProducts.length" shadow="never" class="mb-20">
        <div slot="header" style="font-weight: bold;">主产品投单汇总</div>
        <el-table :data="reportData.parentProducts" border size="small">
          <el-table-column prop="materialCode" label="物料编码" min-width="160" />
          <el-table-column prop="materialName" label="物料名称" min-width="220" show-overflow-tooltip />
          <el-table-column prop="inputQty" label="投单量" width="100" align="right" />
        </el-table>
      </el-card>

      <el-card v-if="reportData.customKitRows && reportData.customKitRows.length" shadow="never" class="mb-20">
        <div slot="header">
          <span style="font-weight: bold;">联合齐套试算</span>
          <span style="font-size: 12px; color: #909399; font-weight: normal; margin-left: 15px;">
            本批需求 = Σ(各主产品单台用量 × 投单量) &nbsp;|&nbsp; 差值 = 本批需求 − 预计可用 &nbsp;|&nbsp; 本次投单 = max(0, 差值)
          </span>
        </div>
        <el-table :data="reportData.customKitRows" border size="small" max-height="650">
          <el-table-column type="index" label="序号" width="55" align="center" />
          <el-table-column prop="materialCode" label="子项编码" min-width="130" show-overflow-tooltip />
          <el-table-column prop="materialName" label="子项名称" min-width="140" show-overflow-tooltip />
          <el-table-column prop="materialType" label="类型" width="70" align="center">
            <template slot-scope="scope">
              <el-tag size="mini" :type="scope.row.materialType === '外购' ? 'warning' : 'primary'">{{ scope.row.materialType }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            v-for="parent in reportData.parentProducts"
            :key="parent.materialCode"
            :label="parent.materialCode + ' 单台用量'"
            width="115"
            align="right"
          >
            <template slot-scope="scope">
              {{ getParentUnitQty(scope.row, parent.materialCode) }}
            </template>
          </el-table-column>
          <el-table-column prop="stockQty" label="库存" width="90" align="right">
            <template slot-scope="scope">
              <el-link type="primary" :underline="false" style="color: #606266; text-decoration: underline;" @click="openDrill('库存', scope.row.stockDrillRows, scope.row.materialCode)">
                {{ scope.row.stockQty || 0 }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="noPickedQty" label="未领料" width="90" align="right" />
          <el-table-column label="在途" align="center">
            <el-table-column prop="transitMoQty" label="MO在途" width="90" align="right">
              <template slot-scope="scope">
                <el-popover v-if="scope.row.transitMoRows && scope.row.transitMoRows.length > 0" trigger="hover" placement="top" width="250">
                  <div style="max-height: 200px; overflow-y: auto;">
                    <div style="font-weight: bold; margin-bottom: 5px;">生产在途明细：</div>
                    <div v-for="(item, idx) in scope.row.transitMoRows" :key="idx" style="margin-top: 5px; font-size: 13px; border-bottom: 1px solid #ebeef5; padding-bottom: 4px;">
                      令号：<span>{{ item.sclh || '(无令号)' }}</span><br>
                      单号：<span style="color: #409EFF">{{ item.billNo || item.orderNo || '-' }}</span><br>
                      未入库：<span style="color: #E6A23C">{{ item.notInstockQty != null ? item.notInstockQty : (item.qty || item.orderQty || 0) }}</span> |
                      交期：{{ item.planFinishDate ? item.planFinishDate.substring(0, 10) : '-' }}
                    </div>
                  </div>
                  <div slot="reference" style="cursor: pointer; color: #67c23a; text-decoration: underline;">
                    {{ scope.row.transitMoQty || 0 }}
                  </div>
                </el-popover>
                <span v-else>{{ scope.row.transitMoQty || 0 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="transitPoQty" label="PO在途" width="90" align="right">
              <template slot-scope="scope">
                <el-popover v-if="scope.row.transitPoRows && scope.row.transitPoRows.length > 0" trigger="hover" placement="top" width="250">
                  <div style="max-height: 200px; overflow-y: auto;">
                    <div style="font-weight: bold; margin-bottom: 5px;">采购在途明细：</div>
                    <div v-for="(item, idx) in scope.row.transitPoRows" :key="idx" style="margin-top: 5px; font-size: 13px; border-bottom: 1px solid #ebeef5; padding-bottom: 4px;">
                      令号：<span>{{ item.sclh || '(无令号)' }}</span><br>
                      单号：<span style="color: #409EFF">{{ item.billNo || item.orderNo || '-' }}</span><br>
                      未入库：<span style="color: #E6A23C">{{ item.notInstockQty != null ? item.notInstockQty : (item.qty || item.orderQty || 0) }}</span> |
                      交期：{{ item.planFinishDate ? item.planFinishDate.substring(0, 10) : '-' }}
                    </div>
                  </div>
                  <div slot="reference" style="cursor: pointer; color: #409eff; text-decoration: underline;">
                    {{ scope.row.transitPoQty || 0 }}
                  </div>
                </el-popover>
                <span v-else>{{ scope.row.transitPoQty || 0 }}</span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column prop="expectedAvailableQty" label="预计可用" width="90" align="right">
            <template slot-scope="scope">
              <span :style="{ color: scope.row.expectedAvailableQty < 0 ? '#f56c6c' : '#67c23a', fontWeight: 'bold' }">
                {{ scope.row.expectedAvailableQty != null ? scope.row.expectedAvailableQty : (scope.row.availableQty || 0) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="batchNeedQty" label="本批需求数量" width="110" align="right">
            <template slot-scope="scope">
              <span style="font-weight: bold;">{{ scope.row.batchNeedQty || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="diffQty" label="差值" width="90" align="right">
            <template slot-scope="scope">
              <span :style="{ color: scope.row.diffQty < 0 ? '#67c23a' : (scope.row.diffQty > 0 ? '#f56c6c' : '#606266'), fontWeight: 'bold' }">
                {{ scope.row.diffQty || 0 }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="deployQty" label="本次投单量" width="100" align="right">
            <template slot-scope="scope">
              <span :style="{ color: scope.row.deployQty > 0 ? '#f56c6c' : 'inherit', fontWeight: scope.row.deployQty > 0 ? 'bold' : 'normal' }">
                {{ scope.row.deployQty || 0 }}
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <el-empty v-else-if="!loading" description="请输入查询条件并点击查询" />

    <!-- 下钻弹窗 -->
    <el-dialog :title="drillTitle" :visible.sync="drillVisible" width="900px" append-to-body>
      <el-table :data="drillData" border size="small" max-height="500">
        <el-table-column prop="sclh" label="令号" min-width="150" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.sclh || '(无令号)' }}
          </template>
        </el-table-column>
        <el-table-column prop="billNo" label="单据号" min-width="130" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.billNo || scope.row.orderNo || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="sourceType" label="类型" width="80" align="center">
          <template slot-scope="scope">
            <el-tag size="mini" :type="getSourceTypeTag(scope.row.sourceType)">
              {{ scope.row.sourceType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="数量" width="80" align="right">
          <template slot-scope="scope">
            {{ scope.row.notInstockQty !== null && scope.row.notInstockQty !== undefined ? scope.row.notInstockQty : (scope.row.qty || scope.row.orderQty || 0) }}
          </template>
        </el-table-column>
        <el-table-column prop="instockQty" label="已入库" width="80" align="right">
          <template slot-scope="scope">
            {{ scope.row.instockQty != null ? scope.row.instockQty : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="planStartDate" label="下达时间" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.planStartDate ? scope.row.planStartDate.substring(0, 10) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="planFinishDate" label="完成/交期" width="100" align="center">
          <template slot-scope="scope">
            {{ scope.row.planFinishDate ? scope.row.planFinishDate.substring(0, 10) : '-' }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { searchNd3Project, getNd3Report, getNd3CustomKit, exportNd3CustomKit } from '@/api/system/nd3PhasedProduct'
import { blobValidate } from '@/utils/ruoyi'
import { saveAs } from 'file-saver'

export default {
  name: 'Nd3PhasedProduct',
  data() {
    return {
      loading: false,
      exportLoading: false,
      searchLoading: false,
      queryMode: 'single',
      searchOptions: [],
      parentInputs: [
        { materialCode: '', inputQty: 1 },
        { materialCode: '', inputQty: 1 },
        { materialCode: '', inputQty: 1 }
      ],
      queryParams: {
        keyword: undefined,
        productionOrderNo: undefined,
        productCode: undefined,
        inputQty: undefined
      },
      reportData: null,
      activeTab: 'selfMade',

      // 下钻弹窗
      drillVisible: false,
      drillTitle: '',
      drillData: []
    }
  },
  methods: {
    // 自动补全搜索
    querySearch(query) {
      if (query !== '') {
        this.searchLoading = true
        searchNd3Project({ keyword: query }).then(res => {
          this.searchOptions = Array.isArray(res.data) ? res.data : []
        }).catch(() => {
          this.searchOptions = []
        }).finally(() => {
          this.searchLoading = false
        })
      } else {
        this.searchOptions = []
      }
    },
    // 选择搜索结果
    handleSelect(index) {
      if (index !== undefined && index !== null && this.searchOptions[index]) {
        const item = this.searchOptions[index]
        this.queryParams.productionOrderNo = item.productionOrderNo
        this.queryParams.productCode = item.productCode
      }
    },
    // 提交查询
    handleQuery() {
      if (this.queryMode === 'multi') {
        this.handleCustomKitQuery()
        return
      }
      const { productionOrderNo, productCode, inputQty } = this.queryParams
      if (!productionOrderNo && !productCode) {
        this.$modal.msgWarning('请填写主产品图号或生产令号')
        return
      }
      this.loading = true

      const params = {}
      if (productionOrderNo) {
        params.productionOrderNo = productionOrderNo
      }
      if (productCode) {
        params.productCode = productCode
        // 兼容后端强制要求 materialCode 的情况
        params.materialCode = productCode
      }
      if (inputQty > 0) {
        params.inputQty = inputQty
      }

      getNd3Report(params).then(res => {
        this.reportData = res.data || null
      }).finally(() => {
        this.loading = false
      })
    },
    handleCustomKitQuery() {
      const payload = this.buildCustomKitPayload()
      if (!payload) {
        return
      }
      this.loading = true
      getNd3CustomKit(payload).then(res => {
        this.reportData = res.data || null
      }).finally(() => {
        this.loading = false
      })
    },
    buildCustomKitPayload() {
      const parents = this.parentInputs
        .filter(p => p.materialCode && String(p.materialCode).trim() && p.inputQty > 0)
        .map(p => ({
          materialCode: String(p.materialCode).trim(),
          inputQty: p.inputQty
        }))
      if (parents.length === 0) {
        this.$modal.msgWarning('请至少填写一个主产品编码及投单量')
        return null
      }
      const payload = { parents }
      if (this.queryParams.productionOrderNo) {
        payload.productionOrderNo = this.queryParams.productionOrderNo
      }
      return payload
    },
    handleExportCustomKit() {
      const payload = this.buildCustomKitPayload()
      if (!payload) {
        return
      }
      this.exportLoading = true
      exportNd3CustomKit(payload).then(async (data) => {
        const isBlob = blobValidate(data)
        if (isBlob) {
          saveAs(new Blob([data]), `多主产品联合齐套试算_${new Date().getTime()}.xlsx`)
        } else {
          const resText = await data.text()
          const rspObj = JSON.parse(resText)
          this.$modal.msgError(rspObj.msg || '导出失败')
        }
      }).catch(() => {
        this.$modal.msgError('导出失败，请稍后重试')
      }).finally(() => {
        this.exportLoading = false
      })
    },
    addParentRow() {
      this.parentInputs.push({ materialCode: '', inputQty: 1 })
    },
    removeParentRow(index) {
      if (this.parentInputs.length <= 1) return
      this.parentInputs.splice(index, 1)
    },
    getParentUnitQty(row, parentMaterialCode) {
      const list = row.parentUnitQtys || []
      const hit = list.find(u => u.parentMaterialCode === parentMaterialCode)
      return hit && hit.unitQty != null ? hit.unitQty : 0
    },
    // 重置
    resetQuery() {
      this.queryMode = 'single'
      this.parentInputs = [
        { materialCode: '', inputQty: 1 },
        { materialCode: '', inputQty: 1 },
        { materialCode: '', inputQty: 1 }
      ]
      this.queryParams = {
        keyword: undefined,
        productionOrderNo: undefined,
        materialCode: undefined,
        inputQty: undefined
      }
      this.searchOptions = []
      this.reportData = null
      this.activeTab = 'selfMade'
    },
    // 打开下钻弹窗
    openDrill(typeLabel, rows, code) {
      this.drillData = rows || []
      // 根据点击类型补充 sourceType (例如：MO在途、PO在途的明细里可能没有带这个字段)
      if (this.drillData.length > 0) {
        this.drillData.forEach(row => {
          if (!row.sourceType) {
            if (typeLabel.includes('MO')) {
              row.sourceType = 'MO'
            } else if (typeLabel.includes('PO')) {
              row.sourceType = 'PO'
            } else if (typeLabel.includes('发货')) {
              row.sourceType = 'DELIVER'
            } else {
              row.sourceType = 'STOCK'
            }
          }
        })
      }
      this.drillTitle = `${typeLabel}明细 - ${code || ''}`
      this.drillVisible = true
    },
    // 获取行标签颜色
    getSourceTypeTag(type) {
      const map = {
        'STOCK': 'info',
        'DELIVER': 'success',
        'WIP': 'primary',
        'MO': 'primary',
        'PO': 'warning'
      }
      return map[type] || 'default'
    },
    // 计算投后余量
    getBalanceQty(row) {
      if (row.balanceQty != null) return row.balanceQty
      if (row.remainStockQty != null) return row.remainStockQty
      return (row.availableQty || 0) - (row.needQty || 0)
    }
  }
}
</script>

<style scoped>
.nd3-phased-product .mb-20 {
  margin-bottom: 20px;
}

/* 主产品 KPI 卡片样式 */
.kpi-card {
  padding: 12px 15px;
  border-radius: 4px;
  text-align: center;
  border: 1px solid #ebeef5;
}
.kpi-card.kpi-stock {
  border-left: 4px solid #909399;
  background-color: #f4f4f5;
}
.kpi-card.kpi-deliver {
  border-left: 4px solid #67c23a;
  background-color: #f0f9eb;
}
.kpi-card.kpi-wip {
  border-left: 4px solid #409eff;
  background-color: #ecf5ff;
}

.kpi-label {
  font-size: 13px;
  color: #606266;
  margin-bottom: 6px;
}
.kpi-value {
  font-size: 20px;
  font-weight: bold;
}
.kpi-value ::v-deep .el-link {
  font-size: 20px;
  font-weight: bold;
}

.parent-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
