<template>
  <div class="capacity-analysis">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
      <el-form-item label="生产令号" prop="productionOrderNo" v-hasPermi="['system:plan:productionOrderNoOptions']">
        <el-select
          v-model="queryParams.productionOrderNo"
          filterable
          remote
          reserve-keyword
          placeholder="请输入生产令号模糊查询"
          :remote-method="searchProductionOrder"
          :loading="searchingOptions"
          @change="handleOrderSelect"
          style="width: 280px"
          clearable
        >
          <el-option
            v-for="(item, index) in productionOptions"
            :key="index"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="主产品图号" prop="productCode">
        <el-input
          v-model="queryParams.productCode"
          placeholder="自动带出"
          disabled
        />
      </el-form-item>
      <el-form-item label="主产品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="自动带出"
          disabled
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" v-hasPermi="['system:material:buildCapacity']" @click="handleQuery">分析</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          :disabled="!hasSearched || !analysisData"
          v-hasPermi="['system:material:exportBuildCapacity']"
          @click="handleExport"
        >导出</el-button>
      </el-form-item>
    </el-form>

    <div v-if="loading" class="loading-wrapper">
      <el-spinner />
      <span class="loading-text">正在分析预配套数据，请稍候...</span>
    </div>

    <!-- 分析结果区域 -->
    <template v-else-if="analysisData && (analysisData.selfMadeMaterials || analysisData.purchaseMaterials)">
      <!-- 顶部卡片 -->
      <el-card class="top-card" shadow="never">
        <div class="header-info">
          <div class="info-item">
            <span class="label">产品：</span>
            <span class="value">{{ analysisData.productName }} ({{ analysisData.productCode }})</span>
          </div>
          <div class="info-item">
            <span class="label">可生产：</span>
            <span class="value highlight">{{ analysisData.maxBuildQty }} 台</span>
          </div>
        </div>
      </el-card>

      <!-- 自制件表格 -->
      <el-card class="table-card" shadow="never" header="自制件">
        <el-table
          :data="analysisData.selfMadeMaterials || []"
          border
          style="width: 100%"
          :header-cell-style="{ background: '#f0f2f5', color: '#303133', fontWeight: 'bold' }"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          
          <el-table-column prop="materialCode" label="物料编码" width="160" show-overflow-tooltip />
          <el-table-column prop="materialName" label="物料名称" min-width="160" show-overflow-tooltip />
          
          <!-- 物料基本属性组 -->
          <el-table-column label="物料属性" align="center">
            <el-table-column prop="material" label="材质" width="100" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.material || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="singleWeight" label="单重(kg)" width="80" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.singleWeight != null ? scope.row.singleWeight : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="requiredQty" label="单台用量" width="80" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.requiredQty != null ? scope.row.requiredQty : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="totalWeight" label="总重(kg)" width="80" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.totalWeight != null ? scope.row.totalWeight : '-' }}</span>
              </template>
            </el-table-column>
          </el-table-column>

          <!-- 库存信息组 -->
          <el-table-column label="库存信息" align="center">
            <el-table-column prop="stock.onHandQty" label="即时库存" width="100" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.stock ? scope.row.stock.onHandQty : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="stock.poNotInQty" label="采购未入库" width="100" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.stock ? scope.row.stock.poNotInQty : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="stock.moNotInQty" label="生产未入库" width="100" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.stock ? scope.row.stock.moNotInQty : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="stock.moNotPickQty" label="未领料(占用)" width="110" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.stock ? scope.row.stock.moNotPickQty : '-' }}</span>
              </template>
            </el-table-column>
          </el-table-column>

          <!-- 计算结果组 -->
          <el-table-column label="计算" align="center">
            <el-table-column prop="calc.finalAvailableQty" label="最终可用" width="100" align="center">
              <template slot-scope="scope">
                <span class="calc-value">{{ scope.row.calc ? scope.row.calc.finalAvailableQty : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="calc.canSupportQty" label="可生产数" width="100" align="center">
              <template slot-scope="scope">
                <span class="calc-value highlight">{{ scope.row.calc ? scope.row.calc.canSupportQty : '-' }}</span>
              </template>
            </el-table-column>
          </el-table-column>

          <!-- 状态列 -->
          <el-table-column prop="status" label="状态" width="100" align="center" fixed="right">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status" :type="getStatusTagType(scope.row.status)" effect="plain" size="small">
                {{ formatStatus(scope.row.status) }}
              </el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 采购件表格 -->
      <el-card class="table-card" shadow="never" header="采购件">
        <el-table
          :data="analysisData.purchaseMaterials || []"
          border
          style="width: 100%"
          :header-cell-style="{ background: '#f0f2f5', color: '#303133', fontWeight: 'bold' }"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          
          <el-table-column prop="materialCode" label="物料编码" width="160" show-overflow-tooltip />
          <el-table-column prop="materialName" label="物料名称" min-width="160" show-overflow-tooltip />
          
          <!-- 物料基本属性组 -->
          <el-table-column label="物料属性" align="center">
            <el-table-column prop="material" label="材质" width="100" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ scope.row.material || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="singleWeight" label="单重(kg)" width="80" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.singleWeight != null ? scope.row.singleWeight : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="requiredQty" label="单台用量" width="80" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.requiredQty != null ? scope.row.requiredQty : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="totalWeight" label="总重(kg)" width="80" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.totalWeight != null ? scope.row.totalWeight : '-' }}</span>
              </template>
            </el-table-column>
          </el-table-column>

          <!-- 库存信息组 -->
          <el-table-column label="库存信息" align="center">
            <el-table-column prop="stock.onHandQty" label="即时库存" width="100" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.stock ? scope.row.stock.onHandQty : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="stock.poNotInQty" label="采购未入库" width="100" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.stock ? scope.row.stock.poNotInQty : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="stock.moNotInQty" label="生产未入库" width="100" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.stock ? scope.row.stock.moNotInQty : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="stock.moNotPickQty" label="未领料(占用)" width="110" align="center">
              <template slot-scope="scope">
                <span>{{ scope.row.stock ? scope.row.stock.moNotPickQty : '-' }}</span>
              </template>
            </el-table-column>
          </el-table-column>

          <!-- 计算结果组 -->
          <el-table-column label="计算" align="center">
            <el-table-column prop="calc.finalAvailableQty" label="最终可用" width="100" align="center">
              <template slot-scope="scope">
                <span class="calc-value">{{ scope.row.calc ? scope.row.calc.finalAvailableQty : '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="calc.canSupportQty" label="可生产数" width="100" align="center">
              <template slot-scope="scope">
                <span class="calc-value highlight">{{ scope.row.calc ? scope.row.calc.canSupportQty : '-' }}</span>
              </template>
            </el-table-column>
          </el-table-column>

          <!-- 状态列 -->
          <el-table-column prop="status" label="状态" width="100" align="center" fixed="right">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status" :type="getStatusTagType(scope.row.status)" effect="plain" size="small">
                {{ formatStatus(scope.row.status) }}
              </el-tag>
              <span v-else>-</span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </template>
    <el-empty v-else-if="!loading && hasSearched" description="暂无产能分析数据" />

    <!-- 多产品选择弹窗 -->
    <el-dialog title="选择主产品" :visible.sync="productSelectVisible" width="800px" append-to-body>
      <el-table :data="productOptions" border style="width: 100%" v-loading="productSelectLoading">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="parentDrawingNo" label="主产品图号" min-width="150" />
        <el-table-column prop="parentPart" label="主产品名称" min-width="150" />
        <el-table-column prop="drawingNo" label="组件图号" min-width="150" />
        <el-table-column prop="quantity" label="数量" width="80" align="center" />
        <el-table-column label="操作" width="100" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="confirmProductSelect(scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import { getCapacityAnalysisApi, selectByProCode, getProductionOrderNoOptions } from "@/api/system/operationPlanningMain";

export default {
  name: 'CapacityAnalysis',
  data() {
    return {
      loading: false,
      hasSearched: false,
      queryParams: {
        productionOrderNo: '',
        productCode: '',
        productName: ''
      },
      analysisData: null,
      // 下拉框数据
      productionOptions: [],
      searchingOptions: false,
      
      // 选中令号后的关联图号列表对话框
      productSelectVisible: false,
      productSelectLoading: false,
      productOptions: []
    };
  },
  created() {
    // 初始加载生产令号下拉列表
    this.searchProductionOrder('');
  },
  methods: {
    searchProductionOrder(query) {
      this.searchingOptions = true;
      getProductionOrderNoOptions({ keyword: query, limit: 200 }).then(res => {
        this.searchingOptions = false;
        if (res.code === 200) {
          // 后端返回的是 List<String>
          this.productionOptions = res.data || [];
        } else {
          this.productionOptions = [];
        }
      }).catch(() => {
        this.searchingOptions = false;
        this.productionOptions = [];
      });
    },
    handleOrderSelect(val) {
      if (!val) {
        this.queryParams.productCode = '';
        this.queryParams.productName = '';
        return;
      }
      
      // 选中生产令号后，去后端查询对应的产品信息列表
      this.productSelectLoading = true;
      selectByProCode(val).then(res => {
        this.productSelectLoading = false;
        if (res.code === 200 && res.data && res.data.length > 0) {
          if (res.data.length === 1) {
            // 只有一个产品直接带出
            this.queryParams.productCode = res.data[0].parentDrawingNo;
            this.queryParams.productName = res.data[0].parentPart;
          } else {
            // 多个产品，弹窗让用户选
            this.productOptions = res.data;
            this.productSelectVisible = true;
          }
        } else {
          this.$message.warning('该生产令号未查到关联产品');
          this.queryParams.productCode = '';
          this.queryParams.productName = '';
        }
      }).catch(() => {
        this.productSelectLoading = false;
        this.$message.error('获取关联产品失败');
      });
    },
    confirmProductSelect(row) {
      this.queryParams.productCode = row.parentDrawingNo;
      this.queryParams.productName = row.parentPart;
      this.productSelectVisible = false;
    },
    handleQuery() {
      if (!this.queryParams.productionOrderNo) {
        this.$message.warning('请输入生产令号');
        return;
      }
      if (!this.queryParams.productCode) {
        this.$message.warning('请输入主产品图号');
        return;
      }
      
      this.loading = true;
      this.hasSearched = true;
      
      getCapacityAnalysisApi(this.queryParams).then(res => {
        if (res.code === 200) {
          this.analysisData = res.data || res;
        } else {
          this.$message.error(res.msg || '产能分析查询失败');
        }
      }).catch(() => {
        this.$message.error('产能分析请求异常');
      }).finally(() => {
        this.loading = false;
      });
    },
    handleExport() {
      this.$confirm('是否确认导出产能分析数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.download('/system/material/buildCapacity/export', {
          ...this.queryParams
        }, `capacity_${new Date().getTime()}.xlsx`);
      }).catch(() => {});
    },
    resetQuery() {
      this.queryParams = {
        productionOrderNo: '',
        productCode: '',
        productName: ''
      };
      this.analysisData = null;
      this.hasSearched = false;
    },
    buildTree(list) {
      const map = {};
      const roots = [];
      
      // 先将所有节点放入 map 中
      list.forEach(item => {
        map[item.rowId] = { ...item, children: [] };
      });
      
      // 构建树结构
      list.forEach(item => {
        const node = map[item.rowId];
        // 如果 parentRowId 为 null 或者在 map 中找不到其父节点，则视为根节点
        if (item.parentRowId === null || !map[item.parentRowId]) {
          roots.push(node);
        } else {
          map[item.parentRowId].children.push(node);
        }
      });
      
      // 清理空的 children 数组，避免展开箭头错乱
      const cleanEmptyChildren = (nodes) => {
        nodes.forEach(node => {
          if (node.children.length === 0) {
            delete node.children;
          } else {
            cleanEmptyChildren(node.children);
          }
        });
      };
      cleanEmptyChildren(roots);
      
      return roots;
    },
    // 为瓶颈行添加红色高亮 class
    tableRowClassName({ row }) {
      return row.bottleneck ? 'bottleneck-row' : '';
    },
    // 根据状态返回 Element UI 标签颜色类型
    getStatusTagType(status) {
      if (status === 'SHORTAGE') return 'danger';   // 红色
      if (status === 'WARNING') return 'warning';   // 橙色
      return 'success';                             // 绿色
    },
    // 将英文状态格式化为中文
    formatStatus(status) {
      if (status === 'SHORTAGE') return '短缺';
      if (status === 'WARNING') return '预警';
      if (status === 'OK') return '正常';
      return status;
    }
  }
}
</script>

<style scoped>
.capacity-analysis {
  padding: 16px;
  background-color: #f5f7fa; /* 工业风浅灰背景 */
  min-height: 100%;
}

.top-card {
  margin-bottom: 16px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.header-info {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 32px;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 15px;
}

.info-item .label {
  color: #606266;
  margin-right: 8px;
  font-weight: 600;
}

.info-item .value {
  color: #303133;
  font-weight: bold;
}

.info-item .value.highlight {
  color: #409EFF;
  font-size: 22px;
}

.bottleneck-info {
  flex: 1;
}

.tags {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.bottleneck-tag {
  font-size: 14px;
  padding: 0 12px;
  height: 32px;
  line-height: 30px;
}

.no-bottleneck {
  color: #67c23a;
  font-size: 14px;
  font-weight: bold;
}

.table-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

/* 表格标题列及基础边框工业风微调 */
::v-deep .el-table {
  border: 1px solid #e4e7ed;
}

.bottleneck-icon {
  margin-right: 6px;
  font-size: 16px;
}

.text-danger {
  color: #F56C6C;
}

/* 计算字段强调 */
.calc-value {
  font-weight: bold;
  color: #303133;
}

.calc-value.highlight {
  color: #409EFF;
  font-size: 15px;
}

.loading-wrapper {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: #909399;
}

.loading-text {
  margin-top: 15px;
  font-size: 14px;
}

/* 瓶颈行整行标红的背景覆盖 */
::v-deep .el-table .bottleneck-row {
  background-color: #fef0f0 !important;
}

/* 鼠标悬停在瓶颈行时加深红色 */
::v-deep .el-table .bottleneck-row:hover > td {
  background-color: #fde2e2 !important;
}
</style>
