<template>
  <div class="alert-console" :class="{ 'fill-viewport': activeTab === 'jjSubcontractDelayRemind' }">
    <!-- 顶栏：全局刷新 -->
    <header class="console-header">
      <div class="header-actions">
        <span class="sync-time" v-if="lastSyncTime">
          <i class="el-icon-time" /> {{ lastSyncTime }}
        </span>
        <el-button
          class="refresh-btn"
          type="primary"
          size="small"
          icon="el-icon-refresh"
          :loading="currentLoading"
          @click="loadActiveTab(true)"
        >
          刷新当前页
        </el-button>
      </div>
    </header>

    <!-- KPI 概览条 -->
    <section class="kpi-strip">
      <button
        v-for="cat in categories"
        :key="cat.key"
        type="button"
        class="kpi-chip"
        :class="{ active: activeTab === cat.key, [`tone-${cat.tone}`]: true }"
        @click="switchTab(cat.key)"
      >
        <span class="kpi-label">{{ cat.shortLabel }}</span>
        <span class="kpi-value">{{ tabCounts[cat.key] }}</span>
        <span class="kpi-unit">条</span>
      </button>
    </section>

    <!-- 主内容区 -->
    <div class="console-body">
      <!-- 右侧数据面板 -->
      <main class="data-panel">
        <div class="panel-head">
          <div>
            <h2 class="panel-title">{{ activeCategory.label }}</h2>
            <p class="panel-desc">{{ activeCategory.desc }}</p>
          </div>
          <div class="panel-toolbar">
            <el-select
              v-if="activeCategory.hasWorkCenterFilter"
              v-model="workCenterFilter[activeTab]"
              placeholder="全部工段"
              clearable
              size="small"
              class="wc-select"
              @change="handleWorkCenterChange"
            >
              <el-option v-for="item in currentWorkCenterOptions" :key="item" :label="item" :value="item" />
            </el-select>
            <el-select
              v-if="activeTab === 'subcontractTransfer'"
              v-model="subcontractReturnStatusFilter"
              placeholder="回厂状态"
              clearable
              size="small"
              class="wc-select"
              @change="handleSubcontractReturnStatusChange"
            >
              <el-option
                v-for="item in subcontractReturnStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-select
              v-if="activeTab === 'purchaseOrderApproval'"
              v-model="purchaseOrderApprovalFilter"
              placeholder="审批分类"
              clearable
              size="small"
              class="wc-select"
              @change="handlePurchaseOrderApprovalFilterChange"
            >
              <el-option
                v-for="item in purchaseOrderApprovalFilterOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-button
              v-if="activeTab === 'subcontractTransfer'"
              type="warning"
              plain
              size="small"
              icon="el-icon-download"
              :loading="exportingSubcontract"
              :disabled="currentDisplayCount === 0"
              v-hasPermi="['system:workCenterData:export']"
              @click="handleExportSubcontractTransfer"
            >
              导出
            </el-button>
            <span class="record-count" v-if="activeTab !== 'jjSubcontractDelayRemind'">
              共 <strong>{{ currentDisplayCount }}</strong> 条记录
              <span
                v-if="activeTab === 'subcontractTransfer' && subcontractNotBackCount > 0 && !subcontractReturnStatusFilter"
                class="not-back-hint"
              >（未回来 {{ subcontractNotBackCount }}）</span>
            </span>
            <span class="record-count" v-else>
              延期工序 <strong>{{ jjRemindMeta.delayRowCount }}</strong>
              · 订单 <strong>{{ jjRemindMeta.delayMoCount }}</strong>
              · 转移 <strong>{{ jjRemindMeta.transferCount }}</strong> 条
            </span>
          </div>
        </div>

        <div class="panel-table-wrap" :class="{ 'jj-remind-wrap': activeTab === 'jjSubcontractDelayRemind' }">
          <div v-if="activeTab === 'jjSubcontractDelayRemind'" class="jj-remind-host">
            <production-remind
              ref="jjRemind"
              embedded
              @loaded="onJjRemindLoaded"
            />
          </div>

          <!-- 工段类表格（延期 / 已转入未转出 / 开工未转入） -->
          <el-table
            v-show="isWorkCenterTab"
            v-loading="loading[activeTab]"
            :data="paginateList(currentWorkCenterList, activeTab)"
            class="alert-table"
            border
            stripe
          >
            <el-table-column type="index" label="#" width="48" align="center" :index="tableIndex" />
            <el-table-column prop="workCenter" label="工段" width="100" show-overflow-tooltip />
            <el-table-column prop="moOrderNo" label="生产令号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="moBillNo" label="生产订单号" min-width="130" show-overflow-tooltip>
              <template slot-scope="{ row }">
                <a
                  v-if="activeTab === 'delayData' && row.moBillNo"
                  href="javascript:;"
                  class="mo-link"
                  @click="openSubcontractDrawer(row)"
                >{{ row.moBillNo }}</a>
                <span v-else>{{ row.moBillNo || '—' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="materialNumber" label="产品编码" min-width="120" show-overflow-tooltip />
            <el-table-column prop="materialName" label="产品名称" min-width="140" show-overflow-tooltip />
            <el-table-column prop="operNumber" label="工序号" width="76" align="center" />
            <el-table-column prop="processName" label="工序名称" min-width="120" show-overflow-tooltip />
            <el-table-column prop="operQty" label="本批数量" width="90" align="right" :formatter="formatQty" />
            <el-table-column prop="transInQty" label="转入" width="80" align="right" :formatter="formatQty" />
            <el-table-column prop="transOutQty" label="转出" width="80" align="right" :formatter="formatQty" />
            <el-table-column prop="materialStatus" label="状态" width="88" align="center">
              <template slot-scope="{ row }">
                <span class="status-tag" :class="statusClass(row.materialStatus)">{{ row.materialStatus || '—' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="operPlanStartTime" label="计划开始" min-width="100" />
            <el-table-column prop="operPlanFinishTime" label="计划完成" min-width="100" />
            <el-table-column v-if="activeTab === 'delayData'" prop="delayDays" label="延期天" width="80" align="center">
              <template slot-scope="{ row }">
                <span class="delay-badge" v-if="row.delayDays">{{ row.delayDays }}</span>
                <span v-else>—</span>
              </template>
            </el-table-column>
            <template v-if="activeTab === 'startedNotTransIn'">
              <el-table-column prop="prevOperNumber" label="上一序工序号" width="100" align="center" />
              <el-table-column prop="prevProcessName" label="上一序名称" min-width="120" show-overflow-tooltip />
              <el-table-column prop="prevWorkCenter" label="上一序工段" width="100" show-overflow-tooltip />
              <el-table-column prop="prevOperStatus" label="上一序状态" width="110" align="center">
                <template slot-scope="{ row }">
                  <span class="status-tag" :class="prevOperStatusClass(row.prevOperStatus)">{{ row.prevOperStatus || '—' }}</span>
                </template>
              </el-table-column>
            </template>
            <template v-if="activeTab === 'subcontractTransfer'">
              <el-table-column prop="returnStatus" label="回厂状态" width="92" align="center" fixed="right">
                <template slot-scope="{ row }">
                  <span class="status-tag" :class="subcontractReturnStatusClass(row.returnStatus)">
                    {{ row.returnStatus || '—' }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="sendBillDate" label="发出日期" min-width="100" />
              <el-table-column prop="receiveBillDate" label="接收日期" min-width="100" />
              <el-table-column prop="sendTransferQty" label="发出数量" width="90" align="right" :formatter="formatQty" />
              <el-table-column prop="receiveTransferQty" label="接收数量" width="90" align="right" :formatter="formatQty" />
              <el-table-column prop="sendQualifiedQty" label="发出合格" width="90" align="right" :formatter="formatQty" />
              <el-table-column prop="sendProFailQty" label="发出工废" width="90" align="right" :formatter="formatQty" />
              <el-table-column prop="sendMatFailQty" label="发出料废" width="90" align="right" :formatter="formatQty" />
              <el-table-column prop="receiveQualifiedQty" label="接收合格" width="90" align="right" :formatter="formatQty" />
              <el-table-column prop="receiveProFailQty" label="接收工废" width="90" align="right" :formatter="formatQty" />
              <el-table-column prop="receiveMatFailQty" label="接收料废" width="90" align="right" :formatter="formatQty" />
            </template>
          </el-table>

          <!-- 采购订单临期 -->
          <el-table
            v-show="activeTab === 'purchaseOrder'"
            v-loading="loading.purchaseOrder"
            :data="paginateList(purchaseOrderList, 'purchaseOrder')"
            class="alert-table"
            border
            stripe
          >
            <el-table-column type="index" label="#" width="48" align="center" :index="tableIndex" />
            <el-table-column prop="FBillNo" label="单据编号" min-width="130" show-overflow-tooltip />
            <el-table-column prop="FUCHNText2" label="生产令号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="FMaterialIdFNumber" label="物料编码" min-width="120" show-overflow-tooltip />
            <el-table-column prop="FMaterialName" label="物料名称" min-width="140" show-overflow-tooltip />
            <el-table-column prop="FSupplierIdFName" label="供应商" min-width="140" show-overflow-tooltip />
            <el-table-column prop="FQty" label="数量" width="90" align="right" :formatter="formatQty" />
            <el-table-column prop="FDate" label="采购日期" min-width="110" />
            <el-table-column prop="FDeliveryDate" label="交货日期" min-width="110" />
            <el-table-column prop="FCreateDate" label="创建日期" min-width="110" />
          </el-table>

          <!-- 采购订单审批中 / 重新审核 -->
          <el-table
            v-show="activeTab === 'purchaseOrderApproval'"
            v-loading="loading.purchaseOrderApproval"
            :data="paginateList(filteredPurchaseOrderApprovalList, 'purchaseOrderApproval')"
            class="alert-table"
            border
            stripe
          >
            <el-table-column type="index" label="#" width="48" align="center" :index="tableIndex" />
            <el-table-column prop="approvalCategoryLabel" label="审批分类" width="96" align="center" fixed="right">
              <template slot-scope="{ row }">
                <span class="status-tag" :class="purchaseOrderApprovalClass(row.approvalCategory)">
                  {{ row.approvalCategoryLabel || '—' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="documentStatusLabel" label="单据状态" width="96" align="center" />
            <el-table-column prop="currentApproverNames" label="当前审批人" min-width="120" show-overflow-tooltip />
            <el-table-column prop="wfAssignArriveTime" label="到达时间" min-width="110" show-overflow-tooltip />
            <el-table-column prop="billNo" label="单据编号" min-width="130" show-overflow-tooltip />
            <el-table-column prop="productionOrderNo" label="生产令号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="materialCode" label="物料编码" min-width="120" show-overflow-tooltip />
            <el-table-column prop="materialName" label="物料名称" min-width="140" show-overflow-tooltip />
            <el-table-column prop="supplierName" label="供应商" min-width="140" show-overflow-tooltip />
            <el-table-column prop="qty" label="数量" width="90" align="right" :formatter="formatQty" />
            <el-table-column prop="orderDate" label="采购日期" min-width="110" />
            <el-table-column prop="deliveryDate" label="交货日期" min-width="110" />
            <el-table-column prop="createDate" label="创建日期" min-width="110" />
          </el-table>

          <!-- 采购申请临期 -->
          <el-table
            v-show="activeTab === 'purchaseRequest'"
            v-loading="loading.purchaseRequest"
            :data="paginateList(purchaseRequestList, 'purchaseRequest')"
            class="alert-table"
            border
            stripe
          >
            <el-table-column type="index" label="#" width="48" align="center" :index="tableIndex" />
            <el-table-column prop="FBillNo" label="单据编号" min-width="130" show-overflow-tooltip />
            <el-table-column prop="FUCHNText" label="生产令号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="FMaterialIdFNumber" label="物料编码" min-width="120" show-overflow-tooltip />
            <el-table-column prop="FMaterialName" label="物料名称" min-width="140" show-overflow-tooltip />
            <el-table-column prop="FReqQty" label="申请数量" width="90" align="right" :formatter="formatQty" />
            <el-table-column prop="FDocumentStatus" label="审核状态" width="90" align="center" />
            <el-table-column prop="FCloseStatus" label="关闭状态" width="90" align="center" />
            <el-table-column prop="FApplicationDate" label="申请日期" min-width="110" />
            <el-table-column prop="FArrivalDate" label="到货日期" min-width="110" />
            <el-table-column prop="FCreatorIdFName" label="创建人" width="100" show-overflow-tooltip />
          </el-table>

          <!-- 采购申请临期且未下推采购订单 -->
          <el-table
            v-show="activeTab === 'purchaseRequestWithoutPo'"
            v-loading="loading.purchaseRequestWithoutPo"
            :data="paginateList(purchaseRequestWithoutPoList, 'purchaseRequestWithoutPo')"
            class="alert-table"
            border
            stripe
          >
            <el-table-column type="index" label="#" width="48" align="center" :index="tableIndex" />
            <el-table-column prop="FBillNo" label="单据编号" min-width="130" show-overflow-tooltip />
            <el-table-column prop="FUCHNText" label="生产令号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="FMaterialIdFNumber" label="物料编码" min-width="120" show-overflow-tooltip />
            <el-table-column prop="FMaterialName" label="物料名称" min-width="140" show-overflow-tooltip />
            <el-table-column prop="FReqQty" label="申请数量" width="90" align="right" :formatter="formatQty" />
            <el-table-column prop="FDocumentStatus" label="审核状态" width="90" align="center" />
            <el-table-column prop="FCloseStatus" label="关闭状态" width="90" align="center" />
            <el-table-column prop="FApplicationDate" label="申请日期" min-width="110" />
            <el-table-column prop="FArrivalDate" label="到货日期" min-width="110" />
            <el-table-column prop="FCreatorIdFName" label="创建人" width="100" show-overflow-tooltip />
          </el-table>

          <!-- 汇报未质检 -->
          <el-table
            v-show="activeTab === 'processReportNotInspected'"
            v-loading="loading.processReportNotInspected"
            :data="paginateList(processReportNotInspectedList, 'processReportNotInspected')"
            class="alert-table"
            border
            stripe
          >
            <el-table-column type="index" label="#" width="48" align="center" :index="tableIndex" />
            <el-table-column prop="FSCLH" label="生产令号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="FMaterialIdNumber" label="物料编码" min-width="120" show-overflow-tooltip />
            <el-table-column prop="FMaterialName" label="物料名称" min-width="140" show-overflow-tooltip />
            <el-table-column prop="FBillNo" label="汇报单号" min-width="130" show-overflow-tooltip />
            <el-table-column prop="FMoNumber" label="生产订单号" min-width="130" show-overflow-tooltip />
            <el-table-column prop="FWorkShopID" label="加工车间" min-width="110" show-overflow-tooltip />
            <el-table-column prop="FOperNumber" label="工序号" width="76" align="center" />
            <el-table-column prop="FOperDescription" label="工序说明" min-width="120" show-overflow-tooltip />
            <el-table-column prop="FQuaQty" label="合格" width="72" align="right" :formatter="formatQty" />
            <el-table-column prop="FProcessFailQty" label="工废" width="72" align="right" :formatter="formatQty" />
            <el-table-column prop="FMaterialFailQty" label="料废" width="72" align="right" :formatter="formatQty" />
            <el-table-column prop="FReworkQty" label="待返修" width="72" align="right" :formatter="formatQty" />
            <el-table-column prop="FFinishQty" label="完工" width="72" align="right" :formatter="formatQty" />
            <el-table-column prop="FDate" label="单据日期" min-width="110" />
          </el-table>

          <!-- 质检未入库 -->
          <el-table
            v-show="activeTab === 'processReport'"
            v-loading="loading.processReport"
            :data="paginateList(processReportList, 'processReport')"
            class="alert-table"
            border
            stripe
          >
            <el-table-column type="index" label="#" width="48" align="center" :index="tableIndex" />
            <el-table-column prop="FSCLH" label="生产令号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="FMaterialIdNumber" label="物料编码" min-width="120" show-overflow-tooltip />
            <el-table-column prop="FMaterialName" label="物料名称" min-width="140" show-overflow-tooltip />
            <el-table-column prop="FBillNo" label="汇报单号" min-width="130" show-overflow-tooltip />
            <el-table-column prop="FMoNumber" label="生产订单号" min-width="130" show-overflow-tooltip />
            <el-table-column prop="FOperNumber" label="工序" width="72" align="center" />
            <el-table-column prop="FQuaQty" label="合格" width="72" align="right" :formatter="formatQty" />
            <el-table-column prop="FProcessFailQty" label="工废" width="72" align="right" :formatter="formatQty" />
            <el-table-column prop="FMaterialFailQty" label="料废" width="72" align="right" :formatter="formatQty" />
            <el-table-column prop="FReworkQty" label="待返修" width="72" align="right" :formatter="formatQty" />
            <el-table-column prop="instockBillNo" label="入库单号" min-width="130" show-overflow-tooltip />
            <el-table-column prop="instockDocumentStatus" label="入库审核" width="100" align="center" />
            <el-table-column prop="instockMustQty" label="应收" width="72" align="right" :formatter="formatQty" />
            <el-table-column prop="instockRealQty" label="实收" width="72" align="right" :formatter="formatQty" />
            <el-table-column prop="instockAlertReason" label="未入库原因" min-width="140" show-overflow-tooltip>
              <template slot-scope="{ row }">
                <span class="reason-tag">{{ row.instockAlertReason || '—' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="FDate" label="汇报日期" min-width="110" />
          </el-table>

          <!-- 工序转移未及时 -->
          <el-table
            v-show="activeTab === 'processTransfer'"
            v-loading="loading.processTransfer"
            :data="paginateList(processTransferList, 'processTransfer')"
            class="alert-table"
            border
            stripe
          >
            <el-table-column type="index" label="#" width="48" align="center" :index="tableIndex" />
            <el-table-column prop="FSCLH" label="生产令号" min-width="120" show-overflow-tooltip />
            <el-table-column prop="FBillNo" label="单据编号" min-width="130" show-overflow-tooltip />
            <el-table-column prop="FMOBillNo" label="生产订单号" min-width="130" show-overflow-tooltip />
            <el-table-column prop="FProductIdNumber" label="产品编码" min-width="120" show-overflow-tooltip />
            <el-table-column prop="FProductName" label="产品名称" min-width="140" show-overflow-tooltip />
            <el-table-column prop="FOutDeptIdFName" label="转出车间" min-width="110" show-overflow-tooltip />
            <el-table-column prop="FOutOperNumber" label="转出工序" width="88" align="center" />
            <el-table-column prop="FInDeptIdFName" label="转入车间" min-width="110" show-overflow-tooltip />
            <el-table-column prop="FInOperNumber" label="转入工序" width="88" align="center" />
            <el-table-column prop="FOperTransferQty" label="转移数量" width="90" align="right" :formatter="formatQty" />
            <el-table-column prop="FCreateDate" label="创建日期" min-width="110" />
          </el-table>

          <div v-if="activeTab !== 'jjSubcontractDelayRemind' && !currentLoading && currentDisplayCount === 0" class="empty-state">
            <i class="el-icon-circle-check" />
            <p>当前分类暂无预警数据</p>
          </div>

          <div v-if="activeTab !== 'jjSubcontractDelayRemind' && currentDisplayCount > 0" class="panel-pagination">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :current-page="tabPagination[activeTab].page"
              :page-size="tabPagination[activeTab].pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="currentDisplayCount"
              @size-change="handlePageSizeChange"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </main>
    </div>

    <!-- 生产延期：按生产订单号查看委外发出 / 接收明细 -->
    <el-drawer
      :visible.sync="subcontractDrawerVisible"
      direction="rtl"
      size="720px"
      custom-class="subcontract-drawer"
      :append-to-body="true"
      destroy-on-close
    >
      <template slot="title">
        <div class="subcontract-drawer__title">
          <span class="subcontract-drawer__title-main">委外发出 / 接收明细</span>
          <span class="subcontract-drawer__title-mo">{{ subcontractDrawerMoBillNo || '—' }}</span>
        </div>
      </template>
      <div class="subcontract-drawer__meta" v-if="subcontractDrawerContext">
        <span>令号 {{ subcontractDrawerContext.moOrderNo || '—' }}</span>
        <span>产品 {{ subcontractDrawerContext.materialNumber || '—' }}</span>
        <span>{{ subcontractDrawerContext.materialName || '—' }}</span>
      </div>
      <div class="subcontract-drawer__summary">
        <div class="subcontract-drawer__summary-item">
          <span class="label">已发出</span>
          <strong class="val send">{{ formatSummaryQty(subcontractSendQty) }}</strong>
          <em>{{ subcontractSendCount }} 笔</em>
        </div>
        <div class="subcontract-drawer__summary-item">
          <span class="label">已接收</span>
          <strong class="val recv">{{ formatSummaryQty(subcontractRecvQty) }}</strong>
          <em>{{ subcontractRecvCount }} 笔</em>
        </div>
        <div class="subcontract-drawer__summary-item" :class="{ warn: subcontractDiffQty > 0 }">
          <span class="label">差额（未回）</span>
          <strong class="val diff">{{ formatSummaryQty(subcontractDiffQty) }}</strong>
          <em>发出 − 接收</em>
        </div>
        <div class="subcontract-drawer__summary-item muted">
          <span class="label">明细</span>
          <strong class="val">{{ subcontractTransferDetailList.length }}</strong>
          <em>条</em>
        </div>
      </div>
      <el-table
        v-loading="subcontractDrawerLoading"
        :data="subcontractTransferDetailList"
        class="subcontract-drawer__table"
        border
        stripe
        size="small"
        height="calc(100vh - 260px)"
        empty-text="该生产订单暂无委外发出/接收记录"
      >
        <el-table-column type="index" label="#" width="48" align="center" />
        <el-table-column prop="transferBillNo" label="转移单号" min-width="130" show-overflow-tooltip />
        <el-table-column label="类型" width="80" align="center">
          <template slot-scope="{ row }">
            <span class="status-tag" :class="row.transferType === 'C' ? 'st-warn' : 'st-ok'">
              {{ row.transferType === 'C' ? '发出' : row.transferType === 'G' ? '接收' : (row.transferType || '—') }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="operTransferQty" label="转移数量" width="90" align="right" :formatter="formatQty" />
        <el-table-column prop="operQualifiedQty" label="合格" width="80" align="right" :formatter="formatQty" />
        <el-table-column prop="operProFailQty" label="工废" width="72" align="right" :formatter="formatQty" />
        <el-table-column prop="operMatFailQty" label="料废" width="72" align="right" :formatter="formatQty" />
        <el-table-column label="单据日期" min-width="110">
          <template slot-scope="{ row }">{{ formatReportDate(row.billDate) || '—' }}</template>
        </el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>

<script>
import {
  getAlertDelayData,
  getAlertTransInPendingOut,
  getAlertStartedNotTransIn,
  getAlertPurchaseOrder,
  getAlertPurchaseOrderApproval,
  getAlertPurchaseRequest,
  getAlertPurchaseRequestWithoutPo,
  getAlertProcessReportNotInspected,
  getAlertProcessReport,
  getAlertProcessTransfer,
  getAlertSubcontractTransfer,
  getSubcontractTransfersByMo
} from '@/api/system/workCenterData'
import ProductionRemind from '@/views/system/productionRemind/index.vue'

const WORK_CENTER_OPTIONS = [
  '机一工段', '机二工段', '焊接工段', '装一工段', '装二工段', '机加委外', '电钳工段', '下料工段'
]

const SUBCONTRACT_WORK_CENTER_OPTIONS = ['机加委外', '装配委外', '铆焊委外']

const SUBCONTRACT_RETURN_STATUS_OPTIONS = [
  { label: '未回来', value: '未回来' },
  { label: '已回来', value: '已回来' },
  { label: '未发出', value: '未发出' }
]

const PURCHASE_ORDER_APPROVAL_FILTER_OPTIONS = [
  { label: '审批中', value: 'inApproval' },
  { label: '重新审批', value: 'reApproval' }
]

const CATEGORIES = [
  { key: 'delayData', label: '生产延期', shortLabel: '生产延期', icon: 'el-icon-timer', tone: 'amber', desc: '延期天数 > 0 且转出小于转入的工序', hasWorkCenterFilter: true },
  { key: 'jjSubcontractDelayRemind', label: '委外延期提醒', shortLabel: '委外延期', icon: 'el-icon-bell', tone: 'teal', desc: '' },
  { key: 'transInPendingOut', label: '已转入未转出', shortLabel: '转入未转出', icon: 'el-icon-sort', tone: 'copper', desc: '已转入但未转出或部分转出的工序（不要求延期）', hasWorkCenterFilter: true },
  { key: 'subcontractTransfer', label: '委外实际发出接收', shortLabel: '委外发出接收', icon: 'el-icon-truck', tone: 'teal', desc: '委外工段工序计划 + 工序委外转移单汇总', hasWorkCenterFilter: true, workCenterOptions: SUBCONTRACT_WORK_CENTER_OPTIONS },
  { key: 'startedNotTransIn', label: '开工未转入', shortLabel: '开工未转入', icon: 'el-icon-video-play', tone: 'rust', desc: '当天计划开工且转入不足的本批工序', hasWorkCenterFilter: true },
  { key: 'purchaseOrder', label: '采购订单临期', shortLabel: '采购订单', icon: 'el-icon-shopping-cart-2', tone: 'slate', desc: '临近交货期的采购订单' },
  { key: 'purchaseOrderApproval', label: '采购订单待审', shortLabel: '订单待审', icon: 'el-icon-s-check', tone: 'amber', desc: '审批中或重新审核的采购订单' },
  { key: 'purchaseRequest', label: '采购申请临期', shortLabel: '采购申请', icon: 'el-icon-document', tone: 'slate', desc: '临近到货期的采购申请单' },
  { key: 'purchaseRequestWithoutPo', label: '申请未下推订单', shortLabel: '未下推', icon: 'el-icon-warning-outline', tone: 'red', desc: '临期采购申请尚未关联采购订单' },
  { key: 'processReportNotInspected', label: '汇报未质检', shortLabel: '未质检', icon: 'el-icon-view', tone: 'violet', desc: '合格/工废/料废/待返修数量均为 0 的工序汇报' },
  { key: 'processReport', label: '质检未入库', shortLabel: '未入库', icon: 'el-icon-download', tone: 'red', desc: '已质检但未完成生产入库的入库点汇报' },
  { key: 'processTransfer', label: '工序转移未及时', shortLabel: '转移延迟', icon: 'el-icon-connection', tone: 'blue', desc: '计划时间内未及时完成的工序转移' }
]

function emptyPagination() {
  return CATEGORIES.reduce((acc, c) => {
    acc[c.key] = { page: 1, pageSize: 20 }
    return acc
  }, {})
}

function emptyLoading() {
  return {
    delayData: false,
    jjSubcontractDelayRemind: false,
    transInPendingOut: false,
    subcontractTransfer: false,
    startedNotTransIn: false,
    purchaseOrder: false,
    purchaseOrderApproval: false,
    purchaseRequest: false,
    purchaseRequestWithoutPo: false,
    processReportNotInspected: false,
    processReport: false,
    processTransfer: false
  }
}

export default {
  name: 'WorkCenterAlert',
  components: { ProductionRemind },
  data() {
    return {
      activeTab: 'delayData',
      categories: CATEGORIES,
      workCenterOptions: WORK_CENTER_OPTIONS,
      workCenterFilter: {
        delayData: undefined,
        transInPendingOut: undefined,
        subcontractTransfer: undefined,
        startedNotTransIn: undefined
      },
      delayDataList: [],
      transInPendingOutList: [],
      subcontractTransferList: [],
      startedNotTransInList: [],
      purchaseOrderList: [],
      purchaseOrderApprovalList: [],
      purchaseRequestList: [],
      purchaseRequestWithoutPoList: [],
      processReportNotInspectedList: [],
      processReportList: [],
      processTransferList: [],
      jjRemindMeta: {
        delayRowCount: 0,
        delayMoCount: 0,
        transferCount: 0
      },
      loadedTabs: {},
      tabPagination: emptyPagination(),
      loading: emptyLoading(),
      loadingAll: false,
      lastSyncTime: '',
      subcontractReturnStatusFilter: undefined,
      subcontractReturnStatusOptions: SUBCONTRACT_RETURN_STATUS_OPTIONS,
      purchaseOrderApprovalFilter: undefined,
      purchaseOrderApprovalFilterOptions: PURCHASE_ORDER_APPROVAL_FILTER_OPTIONS,
      exportingSubcontract: false,
      subcontractDrawerVisible: false,
      subcontractDrawerLoading: false,
      subcontractDrawerMoBillNo: '',
      subcontractDrawerContext: null,
      subcontractTransferDetailList: []
    }
  },
  computed: {
    activeCategory() {
      return this.categories.find(c => c.key === this.activeTab) || this.categories[0]
    },
    currentLoading() {
      return this.loading[this.activeTab]
    },
    isWorkCenterTab() {
      return ['delayData', 'transInPendingOut', 'subcontractTransfer', 'startedNotTransIn'].includes(this.activeTab)
    },
    currentWorkCenterOptions() {
      const cat = this.activeCategory
      return (cat && cat.workCenterOptions) || this.workCenterOptions
    },
    currentWorkCenterList() {
      const map = {
        delayData: this.delayDataList,
        transInPendingOut: this.transInPendingOutList,
        subcontractTransfer: this.filteredSubcontractTransferList,
        startedNotTransIn: this.startedNotTransInList
      }
      return map[this.activeTab] || []
    },
    filteredSubcontractTransferList() {
      let list = this.subcontractTransferList
      if (this.subcontractReturnStatusFilter) {
        list = list.filter(row => row.returnStatus === this.subcontractReturnStatusFilter)
      }
      return list
    },
    filteredPurchaseOrderApprovalList() {
      let list = this.purchaseOrderApprovalList
      if (this.purchaseOrderApprovalFilter) {
        list = list.filter(row => row.approvalCategory === this.purchaseOrderApprovalFilter)
      }
      return list
    },
    subcontractNotBackCount() {
      return this.subcontractTransferList.filter(row => row.returnStatus === '未回来').length
    },
    subcontractSendCount() {
      return this.subcontractTransferDetailList.filter(row => row.transferType === 'C').length
    },
    subcontractRecvCount() {
      return this.subcontractTransferDetailList.filter(row => row.transferType === 'G').length
    },
    subcontractSendQty() {
      return this.sumTransferQty('C')
    },
    subcontractRecvQty() {
      return this.sumTransferQty('G')
    },
    subcontractDiffQty() {
      const diff = this.subcontractSendQty - this.subcontractRecvQty
      return Math.round(diff * 100) / 100
    },
    currentDisplayCount() {
      if (this.activeTab === 'subcontractTransfer') {
        return this.filteredSubcontractTransferList.length
      }
      if (this.activeTab === 'purchaseOrderApproval') {
        return this.filteredPurchaseOrderApprovalList.length
      }
      if (this.activeTab === 'jjSubcontractDelayRemind') {
        return this.jjRemindMeta.transferCount || 0
      }
      return this.tabCounts[this.activeTab] || 0
    },
    tabCounts() {
      return {
        delayData: this.delayDataList.length,
        jjSubcontractDelayRemind: this.jjRemindMeta.transferCount || 0,
        transInPendingOut: this.transInPendingOutList.length,
        subcontractTransfer: this.subcontractNotBackCount,
        startedNotTransIn: this.startedNotTransInList.length,
        purchaseOrder: this.purchaseOrderList.length,
        purchaseOrderApproval: this.purchaseOrderApprovalList.length,
        purchaseRequest: this.purchaseRequestList.length,
        purchaseRequestWithoutPo: this.purchaseRequestWithoutPoList.length,
        processReportNotInspected: this.processReportNotInspectedList.length,
        processReport: this.processReportList.length,
        processTransfer: this.processTransferList.length
      }
    }
  },
  created() {
    this.loadActiveTab()
  },
  methods: {
    switchTab(key) {
      if (this.activeTab === key) return
      this.activeTab = key
      this.loadActiveTab()
    },
    formatSyncTime() {
      const d = new Date()
      const pad = n => String(n).padStart(2, '0')
      this.lastSyncTime = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())} 已同步`
    },
    statusClass(status) {
      if (!status) return ''
      if (status.includes('未转出')) return 'st-warn'
      if (status.includes('未转入')) return 'st-danger'
      return 'st-ok'
    },
    prevOperStatusClass(status) {
      if (!status) return ''
      if (status.includes('未质检') || status.includes('未汇报') || status.includes('未转出') || status.includes('未转入')) return 'st-danger'
      if (status.includes('质检未入库') || status.includes('未找到')) return 'st-warn'
      if (status === '正常') return 'st-ok'
      return ''
    },
    subcontractReturnStatusClass(status) {
      if (status === '未回来') return 'st-danger'
      if (status === '已回来') return 'st-ok'
      if (status === '未发出') return 'st-warn'
      return ''
    },
    purchaseOrderApprovalClass(category) {
      if (category === 'reApproval') return 'st-warn'
      if (category === 'inApproval') return 'st-danger'
      return ''
    },
    handleWorkCenterChange() {
      this.resetTabPage(this.activeTab)
      this.loadedTabs[this.activeTab] = false
      this.loadActiveTab(true)
    },
    handleSubcontractReturnStatusChange() {
      this.resetTabPage('subcontractTransfer')
    },
    handlePurchaseOrderApprovalFilterChange() {
      this.resetTabPage('purchaseOrderApproval')
    },
    handleExportSubcontractTransfer() {
      if (this.currentDisplayCount === 0) {
        this.$modal.msgWarning('当前没有可导出的数据')
        return
      }
      this.exportingSubcontract = true
      const suffix = this.subcontractReturnStatusFilter
        ? `_${this.subcontractReturnStatusFilter}`
        : ''
      this.download(
        'system/workCenterData/exportSubcontractTransfer',
        {
          workCenter: this.workCenterFilter.subcontractTransfer,
          returnStatus: this.subcontractReturnStatusFilter
        },
        `委外发出接收${suffix}_${new Date().getTime()}.xlsx`
      ).finally(() => {
        this.exportingSubcontract = false
      })
    },
    sumTransferQty(transferType) {
      return this.subcontractTransferDetailList.reduce((sum, row) => {
        if (!row || row.transferType !== transferType) return sum
        const n = Number(row.operTransferQty)
        return sum + (Number.isFinite(n) ? n : 0)
      }, 0)
    },
    formatSummaryQty(val) {
      if (val == null || val === '') return '0'
      const num = Number(val)
      if (!Number.isFinite(num)) return '0'
      return parseFloat(num.toFixed(2))
    },
    openSubcontractDrawer(row) {
      const moBillNo = row && row.moBillNo ? String(row.moBillNo).trim() : ''
      if (!moBillNo) {
        this.$modal.msgWarning('生产订单号为空')
        return
      }
      this.subcontractDrawerMoBillNo = moBillNo
      this.subcontractDrawerContext = {
        moOrderNo: row.moOrderNo,
        materialNumber: row.materialNumber,
        materialName: row.materialName
      }
      this.subcontractTransferDetailList = []
      this.subcontractDrawerVisible = true
      this.subcontractDrawerLoading = true
      getSubcontractTransfersByMo(moBillNo)
        .then(res => {
          this.subcontractTransferDetailList = (res && res.data) ? res.data : []
        })
        .catch(() => {
          this.subcontractTransferDetailList = []
        })
        .finally(() => {
          this.subcontractDrawerLoading = false
        })
    },
    resetTabPage(tabKey) {
      if (this.tabPagination[tabKey]) {
        this.tabPagination[tabKey].page = 1
      }
    },
    paginateList(list, tabKey) {
      if (!list || !list.length) {
        return []
      }
      const p = this.tabPagination[tabKey]
      if (!p) {
        return list
      }
      const start = (p.page - 1) * p.pageSize
      return list.slice(start, start + p.pageSize)
    },
    tableIndex(index) {
      const p = this.tabPagination[this.activeTab]
      if (!p) {
        return index + 1
      }
      return (p.page - 1) * p.pageSize + index + 1
    },
    handlePageSizeChange(size) {
      const p = this.tabPagination[this.activeTab]
      if (p) {
        p.pageSize = size
        p.page = 1
      }
    },
    handlePageChange(page) {
      const p = this.tabPagination[this.activeTab]
      if (p) {
        p.page = page
      }
    },
    loadActiveTab(force) {
      const loaders = {
        delayData: this.loadDelayData,
        jjSubcontractDelayRemind: this.loadJjSubcontractDelayRemind,
        transInPendingOut: this.loadTransInPendingOut,
        subcontractTransfer: this.loadSubcontractTransfer,
        startedNotTransIn: this.loadStartedNotTransIn,
        purchaseOrder: this.loadPurchaseOrder,
        purchaseOrderApproval: this.loadPurchaseOrderApproval,
        purchaseRequest: this.loadPurchaseRequest,
        purchaseRequestWithoutPo: this.loadPurchaseRequestWithoutPo,
        processReportNotInspected: this.loadProcessReportNotInspected,
        processReport: this.loadProcessReport,
        processTransfer: this.loadProcessTransfer
      }
      const loader = loaders[this.activeTab]
      if (loader) {
        return loader(force).then(() => this.formatSyncTime())
      }
      return Promise.resolve()
    },
    refreshAllTabs() {
      this.loadingAll = true
      this.loadedTabs = {}
      const current = this.activeTab
      return Promise.all([
        this.loadDelayData(true),
        this.loadJjSubcontractDelayRemind(true),
        this.loadTransInPendingOut(true),
        this.loadSubcontractTransfer(true),
        this.loadStartedNotTransIn(true),
        this.loadPurchaseOrder(true),
        this.loadPurchaseOrderApproval(true),
        this.loadPurchaseRequest(true),
        this.loadPurchaseRequestWithoutPo(true),
        this.loadProcessReportNotInspected(true),
        this.loadProcessReport(true),
        this.loadProcessTransfer(true)
      ]).finally(() => {
        this.loadingAll = false
        this.activeTab = current
        this.formatSyncTime()
      })
    },
    fetchTabData(tabKey, requestFn, assignFn, force) {
      if (!force && this.loadedTabs[tabKey]) {
        return Promise.resolve()
      }
      this.loading[tabKey] = true
      return requestFn()
        .then(res => {
          assignFn(res.data || [])
          this.resetTabPage(tabKey)
          this.loadedTabs[tabKey] = true
        })
        .catch(() => assignFn([]))
        .finally(() => {
          this.loading[tabKey] = false
        })
    },
    loadDelayData(force) {
      return this.fetchTabData(
        'delayData',
        () => getAlertDelayData(this.workCenterFilter.delayData),
        d => { this.delayDataList = d },
        force
      )
    },
    loadJjSubcontractDelayRemind(force) {
      // 该页签用 v-if 挂载，每次进入都需拉数（force 仅兼容统一调用签名）
      void force
      this.loading.jjSubcontractDelayRemind = true
      return this.$nextTick()
        .then(() => {
          const panel = this.$refs.jjRemind
          if (panel && typeof panel.loadData === 'function') {
            return panel.loadData()
          }
          return Promise.resolve()
        })
        .finally(() => {
          this.loading.jjSubcontractDelayRemind = false
          this.loadedTabs.jjSubcontractDelayRemind = true
          this.$nextTick(() => {
            const panel = this.$refs.jjRemind
            if (panel && typeof panel.updateTableHeight === 'function') {
              panel.updateTableHeight()
            }
          })
        })
    },
    onJjRemindLoaded(meta) {
      this.jjRemindMeta = {
        delayRowCount: (meta && meta.delayRowCount) || 0,
        delayMoCount: (meta && meta.delayMoCount) || 0,
        transferCount: (meta && meta.transferCount) || 0
      }
    },
    loadTransInPendingOut(force) {
      return this.fetchTabData(
        'transInPendingOut',
        () => getAlertTransInPendingOut(this.workCenterFilter.transInPendingOut),
        d => { this.transInPendingOutList = d },
        force
      )
    },
    loadSubcontractTransfer(force) {
      return this.fetchTabData(
        'subcontractTransfer',
        () => getAlertSubcontractTransfer(this.workCenterFilter.subcontractTransfer),
        d => { this.subcontractTransferList = d },
        force
      )
    },
    loadStartedNotTransIn(force) {
      return this.fetchTabData(
        'startedNotTransIn',
        () => getAlertStartedNotTransIn(this.workCenterFilter.startedNotTransIn),
        d => { this.startedNotTransInList = d },
        force
      )
    },
    loadPurchaseOrder(force) {
      return this.fetchTabData(
        'purchaseOrder',
        getAlertPurchaseOrder,
        d => { this.purchaseOrderList = this.normalizePurchaseOrderList(d) },
        force
      )
    },
    loadPurchaseOrderApproval(force) {
      return this.fetchTabData(
        'purchaseOrderApproval',
        getAlertPurchaseOrderApproval,
        d => { this.purchaseOrderApprovalList = this.normalizePurchaseOrderApprovalList(d) },
        force
      )
    },
    loadPurchaseRequest(force) {
      return this.fetchTabData(
        'purchaseRequest',
        getAlertPurchaseRequest,
        d => { this.purchaseRequestList = this.normalizePurchaseRequestList(d) },
        force
      )
    },
    loadPurchaseRequestWithoutPo(force) {
      return this.fetchTabData(
        'purchaseRequestWithoutPo',
        getAlertPurchaseRequestWithoutPo,
        d => { this.purchaseRequestWithoutPoList = this.normalizePurchaseRequestList(d) },
        force
      )
    },
    loadProcessReportNotInspected(force) {
      return this.fetchTabData(
        'processReportNotInspected',
        getAlertProcessReportNotInspected,
        d => { this.processReportNotInspectedList = this.normalizeProcessReportList(d) },
        force
      )
    },
    loadProcessReport(force) {
      return this.fetchTabData(
        'processReport',
        getAlertProcessReport,
        d => { this.processReportList = this.normalizeProcessReportList(d) },
        force
      )
    },
    loadProcessTransfer(force) {
      return this.fetchTabData(
        'processTransfer',
        getAlertProcessTransfer,
        d => { this.processTransferList = this.normalizeProcessTransferList(d) },
        force
      )
    },
    /**
     * 后端 ProcessReportDTO 使用金蝶 @JsonProperty 名序列化（如 F_HBYT_SCLH），
     * 与表格 prop 不一致；带点号的键也不能被 el-table 当作扁平字段读取。
     */
    normalizeProcessReportList(list) {
      if (!Array.isArray(list)) {
        return []
      }
      return list.map(row => this.normalizeProcessReportRow(row))
    },
    normalizeProcessReportRow(row) {
      if (!row || typeof row !== 'object') {
        return row
      }
      return {
        ...row,
        FSCLH: row.FSCLH || row.F_HBYT_SCLH || '',
        FMaterialIdNumber: row.FMaterialIdNumber || row['FMaterialId.FNumber'] || '',
        FMaterialName: row.FMaterialName || '',
        FWorkShopID: row.FWorkShopID || row['FWorkShopID.FName'] || '',
        FRKD: this.formatReportRkd(row.FRKD != null ? row.FRKD : row.F_HBYT_RKD),
        FDate: this.formatReportDate(row.FDate)
      }
    },
    normalizePurchaseOrderList(list) {
      if (!Array.isArray(list)) {
        return []
      }
      return list.map(row => this.normalizePurchaseOrderRow(row))
    },
    normalizePurchaseOrderRow(row) {
      if (!row || typeof row !== 'object') {
        return row
      }
      return {
        ...row,
        FUCHNText2: row.FUCHNText2 || row.F_UCHN_Text2 || '',
        FMaterialIdFNumber: row.FMaterialIdFNumber || row['FMaterialId.FNumber'] || '',
        FMaterialName: row.FMaterialName || '',
        FSupplierIdFName: row.FSupplierIdFName || row['FSupplierId.FName'] || '',
        FDate: this.formatReportDate(row.FDate),
        FDeliveryDate: this.formatReportDate(row.FDeliveryDate),
        FCreateDate: this.formatReportDate(row.FCreateDate)
      }
    },
    normalizePurchaseOrderApprovalList(list) {
      if (!Array.isArray(list)) {
        return []
      }
      return list.map(row => this.normalizePurchaseOrderApprovalRow(row))
    },
    normalizePurchaseOrderApprovalRow(row) {
      if (!row || typeof row !== 'object') {
        return row
      }
      return {
        ...row,
        billNo: row.billNo || row.FBillNo || '',
        productionOrderNo: row.productionOrderNo || row.F_UCHN_Text2 || '',
        materialCode: row.materialCode || row['FMaterialId.FNumber'] || '',
        materialName: row.materialName || row.FMaterialName || '',
        supplierName: row.supplierName || row['FSupplierId.FName'] || '',
        qty: row.qty != null ? row.qty : row.FQty,
        orderDate: this.formatReportDate(row.orderDate || row.FDate),
        deliveryDate: this.formatReportDate(row.deliveryDate || row.FDeliveryDate),
        createDate: this.formatReportDate(row.createDate || row.FCreateDate),
        documentStatus: row.documentStatus || row.FDocumentStatus || '',
        documentStatusLabel: row.documentStatusLabel || '',
        currentApproverNames: row.currentApproverNames || '',
        wfAssignArriveTime: row.wfAssignArriveTime || '',
        approvalCategory: row.approvalCategory || '',
        approvalCategoryLabel: row.approvalCategoryLabel || ''
      }
    },
    normalizePurchaseRequestList(list) {
      if (!Array.isArray(list)) {
        return []
      }
      return list.map(row => this.normalizePurchaseRequestRow(row))
    },
    normalizePurchaseRequestRow(row) {
      if (!row || typeof row !== 'object') {
        return row
      }
      return {
        ...row,
        FUCHNText: row.FUCHNText || row.F_UCHN_Text || '',
        FMaterialIdFNumber: row.FMaterialIdFNumber || row['FMaterialId.FNumber'] || '',
        FMaterialName: row.FMaterialName || '',
        FCreatorIdFName: row.FCreatorIdFName || row['FCreatorId.FName'] || '',
        FApplicationDate: this.formatReportDate(row.FApplicationDate),
        FArrivalDate: this.formatReportDate(row.FArrivalDate),
        FCreateDate: this.formatReportDate(row.FCreateDate)
      }
    },
    normalizeProcessTransferList(list) {
      if (!Array.isArray(list)) {
        return []
      }
      return list.map(row => this.normalizeProcessTransferRow(row))
    },
    normalizeProcessTransferRow(row) {
      if (!row || typeof row !== 'object') {
        return row
      }
      return {
        ...row,
        FSCLH: row.FSCLH || row.F_HBYT_SCLH || '',
        FProductIdNumber: row.FProductIdNumber || row['FProductId.FNumber'] || '',
        FOutDeptIdFName: row.FOutDeptIdFName || row['FOutDeptId.FName'] || '',
        FInDeptIdFName: row.FInDeptIdFName || row['FInDeptId.FName'] || '',
        FOutProcessIdName: row.FOutProcessIdName || row['FOutProcessId.FName'] || '',
        FInProcessIdFName: row.FInProcessIdFName || row['FInProcessId.FName'] || '',
        FCreateDate: this.formatReportDate(row.FCreateDate)
      }
    },
    formatReportRkd(val) {
      if (val === true || val === 'true' || val === '1') {
        return '是'
      }
      if (val === false || val === 'false' || val === '0') {
        return '否'
      }
      return val != null ? String(val) : ''
    },
    formatReportDate(val) {
      if (val == null || val === '') {
        return ''
      }
      const s = String(val)
      if (s.includes('T')) {
        const [d, t] = s.split('T')
        const time = (t || '').replace(/\.\d+.*$/, '').substring(0, 8)
        return time ? `${d} ${time}` : d
      }
      return s.length >= 10 ? s.substring(0, 10) : s
    },
    formatQty(row, column, cellValue) {
      if (cellValue == null || cellValue === '') return ''
      const num = Number(cellValue)
      if (isNaN(num)) return cellValue
      return parseFloat(num.toFixed(2))
    }
  }
}
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Barlow:wght@400;500;600;700&family=Barlow+Condensed:wght@600;700&display=swap');

.alert-console {
  --bg-base: #eceae4;
  --bg-panel: #faf9f6;
  --bg-dark: #1a2332;
  --bg-dark-soft: #243044;
  --border: #c8c4ba;
  --text: #1a2332;
  --text-muted: #5c6573;
  --accent-amber: #d4820a;
  --accent-copper: #b85c38;
  --accent-teal: #1a7a6d;
  --accent-red: #c0392b;
  --accent-blue: #2c5282;
  --shadow: 0 4px 24px rgba(26, 35, 50, 0.08);

  min-height: calc(100vh - 84px);
  padding: 0 4px 20px;
  font-family: 'Barlow', 'Microsoft YaHei', sans-serif;
  color: var(--text);
  background:
    linear-gradient(135deg, rgba(26, 35, 50, 0.03) 25%, transparent 25%) -20px 0 / 40px 40px,
    linear-gradient(225deg, rgba(26, 35, 50, 0.03) 25%, transparent 25%) -20px 0 / 40px 40px,
    var(--bg-base);
}

/* 机加委外页签：整页吃满视口，表格自适应高度 + 冻结表头 */
.alert-console.fill-viewport {
  height: calc(100vh - 84px);
  min-height: calc(100vh - 84px);
  padding-bottom: 8px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.alert-console.fill-viewport .console-body {
  flex: 1;
  min-height: 0;
  overflow: hidden;
}

.alert-console.fill-viewport .data-panel {
  flex: 1;
  min-height: 0;
}

.alert-console.fill-viewport .panel-table-wrap {
  min-height: 0;
  overflow: hidden;
}

/* ── Header ── */
.console-header {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 16px;
  padding: 12px 24px;
  margin-bottom: 12px;
  background: var(--bg-dark);
  border-radius: 4px;
  box-shadow: var(--shadow);
  position: relative;
  overflow: hidden;
}

.console-header::after {
  content: '';
  position: absolute;
  inset: 0;
  background: repeating-linear-gradient(
    0deg,
    transparent,
    transparent 2px,
    rgba(255, 255, 255, 0.015) 2px,
    rgba(255, 255, 255, 0.015) 4px
  );
  pointer-events: none;
}

.header-brand {
  display: flex;
  align-items: center;
  gap: 16px;
  position: relative;
  z-index: 1;
}

.brand-mark {
  position: relative;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--accent-amber);
  border-radius: 4px;
  color: var(--bg-dark);
  font-size: 22px;
}

.mark-pulse {
  position: absolute;
  inset: -4px;
  border: 2px solid var(--accent-amber);
  border-radius: 6px;
  animation: pulse-ring 2s ease-out infinite;
  opacity: 0;
}

@keyframes pulse-ring {
  0% { transform: scale(0.95); opacity: 0.6; }
  100% { transform: scale(1.15); opacity: 0; }
}

.brand-title {
  margin: 0 0 4px;
  font-family: 'Barlow Condensed', sans-serif;
  font-size: 26px;
  font-weight: 700;
  letter-spacing: 0.04em;
  color: #f0ebe3;
  text-transform: uppercase;
}

.brand-sub {
  margin: 0;
  font-size: 12px;
  color: rgba(240, 235, 227, 0.55);
  letter-spacing: 0.02em;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
  position: relative;
  z-index: 1;
}

.sync-time {
  font-size: 12px;
  color: rgba(240, 235, 227, 0.5);
  font-variant-numeric: tabular-nums;
}

.refresh-btn {
  background: var(--accent-amber) !important;
  border-color: var(--accent-amber) !important;
  color: var(--bg-dark) !important;
  font-weight: 600;
}

.refresh-all-btn {
  color: #f0ebe3 !important;
  border-color: rgba(240, 235, 227, 0.3) !important;
  background: transparent !important;
}

/* ── KPI strip ── */
.kpi-strip {
  display: flex;
  gap: 8px;
  overflow-x: auto;
  padding: 4px 2px 12px;
  scrollbar-width: thin;
}

.kpi-chip {
  flex: 0 0 auto;
  display: flex;
  align-items: baseline;
  gap: 6px;
  padding: 8px 14px;
  border: 1px solid var(--border);
  border-radius: 3px;
  background: var(--bg-panel);
  cursor: pointer;
  transition: all 0.18s ease;
  font-family: inherit;
}

.kpi-chip:hover {
  border-color: var(--bg-dark-soft);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(26, 35, 50, 0.1);
}

.kpi-chip.active {
  background: var(--bg-dark);
  border-color: var(--bg-dark);
  color: #f0ebe3;
}

.kpi-label {
  font-size: 11px;
  font-weight: 600;
  letter-spacing: 0.06em;
  text-transform: uppercase;
  opacity: 0.75;
}

.kpi-value {
  font-family: 'Barlow Condensed', sans-serif;
  font-size: 22px;
  font-weight: 700;
  line-height: 1;
  font-variant-numeric: tabular-nums;
}

.kpi-unit {
  font-size: 11px;
  opacity: 0.6;
}

.tone-amber .kpi-value { color: var(--accent-amber); }
.tone-copper .kpi-value { color: var(--accent-copper); }
.tone-teal .kpi-value { color: var(--accent-teal); }
.tone-red .kpi-value { color: var(--accent-red); }
.tone-blue .kpi-value { color: var(--accent-blue); }
.tone-violet .kpi-value { color: #6b4c9a; }
.tone-rust .kpi-value { color: #a0522d; }
.tone-slate .kpi-value { color: var(--text-muted); }

.kpi-chip.active .kpi-value,
.kpi-chip.active .kpi-label,
.kpi-chip.active .kpi-unit {
  color: #f0ebe3;
  opacity: 1;
}

/* ── Body layout ── */
.console-body {
  display: flex;
  flex-direction: column;
  gap: 12px;
  min-height: 520px;
}

@media (max-width: 960px) {
  .console-body {
    grid-template-columns: 1fr;
  }
  .side-nav {
    flex-direction: row !important;
    overflow-x: auto;
    padding-bottom: 4px;
  }
  .nav-item {
    flex: 0 0 auto;
    min-width: 120px;
  }
}

.side-nav {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 12px;
  border: 1px solid transparent;
  border-radius: 3px;
  background: transparent;
  cursor: pointer;
  text-align: left;
  font-family: inherit;
  font-size: 13px;
  color: var(--text-muted);
  transition: all 0.15s ease;
  animation: slide-in 0.35s ease both;
}

@keyframes slide-in {
  from { opacity: 0; transform: translateX(-8px); }
  to { opacity: 1; transform: translateX(0); }
}

.nav-item i {
  font-size: 16px;
  width: 20px;
  text-align: center;
}

.nav-item:hover {
  background: rgba(26, 35, 50, 0.05);
  color: var(--text);
}

.nav-item.active {
  background: var(--bg-panel);
  border-color: var(--border);
  color: var(--text);
  font-weight: 600;
  box-shadow: var(--shadow);
}

.nav-text {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.nav-badge {
  min-width: 22px;
  padding: 1px 6px;
  border-radius: 10px;
  font-family: 'Barlow Condensed', sans-serif;
  font-size: 13px;
  font-weight: 700;
  text-align: center;
  background: rgba(26, 35, 50, 0.08);
  color: var(--text-muted);
  font-variant-numeric: tabular-nums;
}

.nav-badge.has-alert {
  background: var(--accent-amber);
  color: var(--bg-dark);
}

.nav-item.active .nav-badge:not(.has-alert) {
  background: rgba(26, 35, 50, 0.1);
}

/* ── Data panel ── */
.data-panel {
  background: var(--bg-panel);
  border: 1px solid var(--border);
  border-radius: 4px;
  box-shadow: var(--shadow);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  animation: panel-in 0.3s ease;
}

@keyframes panel-in {
  from { opacity: 0; transform: translateY(6px); }
  to { opacity: 1; transform: translateY(0); }
}

.panel-head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 16px;
  padding: 16px 20px;
  border-bottom: 1px solid var(--border);
  background: linear-gradient(180deg, #fff 0%, var(--bg-panel) 100%);
}

.panel-title {
  margin: 0 0 4px;
  font-family: 'Barlow Condensed', sans-serif;
  font-size: 20px;
  font-weight: 700;
  letter-spacing: 0.03em;
  text-transform: uppercase;
}

.panel-desc {
  margin: 0;
  font-size: 12px;
  color: var(--text-muted);
}

.panel-toolbar {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-shrink: 0;
}

.wc-select {
  width: 148px;
}

.record-count {
  font-size: 13px;
  color: var(--text-muted);
  white-space: nowrap;
}

.record-count strong {
  font-family: 'Barlow Condensed', sans-serif;
  font-size: 18px;
  color: var(--accent-copper);
}

.not-back-hint {
  margin-left: 6px;
  color: var(--accent-red);
  font-size: 12px;
}

.panel-table-wrap {
  padding: 12px 16px 16px;
  flex: 1;
  min-height: 0;
  position: relative;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.panel-table-wrap.jj-remind-wrap {
  padding: 8px 12px 12px;
  min-height: 0;
}

.jj-remind-host {
  flex: 1;
  min-height: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.jj-remind-host >>> .remind-page {
  flex: 1;
  min-height: 0;
  height: 100%;
}

.panel-pagination {
  display: flex;
  justify-content: flex-end;
  padding-top: 12px;
  margin-top: auto;
  border-top: 1px solid var(--border);
}

.panel-pagination >>> .el-pagination.is-background .el-pager li:not(.disabled).active {
  background-color: var(--bg-dark);
}

/* ── Table overrides ── */
.alert-table {
  width: 100%;
  font-size: 13px;
}

.alert-table >>> .el-table__header th {
  background: var(--bg-dark) !important;
  color: #e8e4dc !important;
  font-family: 'Barlow Condensed', sans-serif;
  font-size: 12px;
  font-weight: 600;
  letter-spacing: 0.05em;
  text-transform: uppercase;
  border-color: var(--bg-dark-soft) !important;
}

.alert-table >>> .el-table__body td {
  border-color: #ddd9d0 !important;
}

.alert-table >>> .el-table--striped .el-table__body tr.el-table__row--striped td {
  background: rgba(26, 35, 50, 0.025) !important;
}

.alert-table >>> .el-table__body tr:hover > td {
  background: rgba(212, 130, 10, 0.06) !important;
}

/* ── Cell tags ── */
.status-tag {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 2px;
  font-size: 11px;
  font-weight: 600;
  letter-spacing: 0.03em;
}

.st-warn { background: rgba(212, 130, 10, 0.15); color: #9a6208; }
.st-danger { background: rgba(192, 57, 43, 0.12); color: var(--accent-red); }
.st-ok { background: rgba(26, 122, 109, 0.12); color: var(--accent-teal); }

.delay-badge {
  display: inline-block;
  min-width: 24px;
  padding: 2px 6px;
  background: var(--accent-red);
  color: #fff;
  border-radius: 2px;
  font-family: 'Barlow Condensed', sans-serif;
  font-weight: 700;
  font-size: 13px;
}

.reason-tag {
  color: var(--accent-copper);
  font-weight: 500;
  font-size: 12px;
}

/* ── Empty ── */
.empty-state {
  position: absolute;
  inset: 12px 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  background: rgba(250, 249, 246, 0.85);
  pointer-events: none;
  color: var(--text-muted);
}

.empty-state i {
  font-size: 40px;
  color: var(--accent-teal);
  opacity: 0.6;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}

/* ── 生产订单号链接 ── */
.mo-link {
  color: #2c5282;
  font-weight: 600;
  text-decoration: none;
  border-bottom: 1px dashed rgba(44, 82, 130, 0.35);
}

.mo-link:hover {
  color: #d4820a;
  border-bottom-color: #d4820a;
}

/* ── 委外明细抽屉（append-to-body，避免依赖父级 CSS 变量）── */
.subcontract-drawer__title {
  display: flex;
  flex-direction: column;
  gap: 2px;
  line-height: 1.3;
}

.subcontract-drawer__title-main {
  font-family: 'Barlow Condensed', sans-serif;
  font-size: 18px;
  font-weight: 700;
  letter-spacing: 0.04em;
  color: #1a2332;
}

.subcontract-drawer__title-mo {
  font-size: 12px;
  color: #5c6573;
  font-variant-numeric: tabular-nums;
}

.subcontract-drawer__meta {
  display: flex;
  flex-wrap: wrap;
  gap: 10px 16px;
  margin-bottom: 12px;
  font-size: 12px;
  color: #5c6573;
}

.subcontract-drawer__summary {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  gap: 8px;
  margin-bottom: 14px;
}

.subcontract-drawer__summary-item {
  display: flex;
  flex-direction: column;
  gap: 2px;
  padding: 10px 12px;
  background: #f3f1eb;
  border: 1px solid #d5d1c7;
  border-radius: 3px;
}

.subcontract-drawer__summary-item .label {
  font-size: 11px;
  font-weight: 600;
  letter-spacing: 0.04em;
  color: #5c6573;
}

.subcontract-drawer__summary-item .val {
  font-family: 'Barlow Condensed', sans-serif;
  font-size: 22px;
  font-weight: 700;
  line-height: 1.1;
  color: #1a2332;
  font-variant-numeric: tabular-nums;
}

.subcontract-drawer__summary-item .val.send { color: #d4820a; }
.subcontract-drawer__summary-item .val.recv { color: #1a7a6d; }
.subcontract-drawer__summary-item .val.diff { color: #1a2332; }

.subcontract-drawer__summary-item.warn {
  background: rgba(192, 57, 43, 0.08);
  border-color: rgba(192, 57, 43, 0.28);
}

.subcontract-drawer__summary-item.warn .val.diff {
  color: #c0392b;
}

.subcontract-drawer__summary-item em {
  font-style: normal;
  font-size: 11px;
  color: #8a919c;
}

.subcontract-drawer__summary-item.muted .val {
  font-size: 18px;
}

.subcontract-drawer__table {
  width: 100%;
}

@media (max-width: 720px) {
  .subcontract-drawer__summary {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}
</style>

<style>
.subcontract-drawer .el-drawer__header {
  margin-bottom: 12px;
  padding: 16px 20px 0;
}

.subcontract-drawer .el-drawer__body {
  padding: 0 20px 20px;
}

/* 抽屉挂到 body，表头样式需写在非 scoped 中 */
.subcontract-drawer .el-table__header th {
  background: #1a2332 !important;
  color: #e8e4dc !important;
  font-family: 'Barlow Condensed', 'Microsoft YaHei', sans-serif;
  font-size: 12px;
  font-weight: 600;
  letter-spacing: 0.05em;
  border-color: #243044 !important;
}

.subcontract-drawer .el-table__header th .cell {
  color: #e8e4dc !important;
}

.subcontract-drawer .el-table__body td {
  border-color: #ddd9d0 !important;
}

.subcontract-drawer .el-table--striped .el-table__body tr.el-table__row--striped td {
  background: rgba(26, 35, 50, 0.025) !important;
}

.subcontract-drawer .el-table__body tr:hover > td {
  background: rgba(212, 130, 10, 0.06) !important;
}
</style>
