<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="生产令号" prop="productionOrderNo">
        <el-input
            v-model="queryParams.productionOrderNo"
            placeholder="请输入生产令号"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="productionName">
        <el-input
            v-model="queryParams.productionName"
            placeholder="请输入项目名称"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="图号" prop="drawingNo">
        <el-input
            v-model="queryParams.drawingNo"
            placeholder="请输入图号"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="名称" prop="drawingName">
        <el-input
            v-model="queryParams.drawingName"
            placeholder="请输入名称"
            clearable
            @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="创建人" prop="createdBy">
        <el-input
          v-model="queryParams.createdBy"
          placeholder="请输入创建人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="修改人" prop="updatedBy">
        <el-input
          v-model="queryParams.updatedBy"
          placeholder="请输入修改人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="计划结束时间" prop="planEndTime">
        <el-date-picker clearable
                        v-model="queryParams.planEndTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择计划结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="计划开始时间" prop="planStartTime">
        <el-date-picker clearable
                        v-model="queryParams.planStartTime"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择计划开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:orderPro:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:orderPro:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:orderPro:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:orderPro:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderProList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <!-- <el-table-column label="序号" align="center" prop="id" v-if="true"/> -->
      <el-table-column label="生产令号" align="center" prop="productionOrderNo">
        <template slot-scope="scope">
          <el-link @click="productionCodeHandle(scope.row)" type="primary">
            {{ scope.row.productionOrderNo }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="项目名称" align="center" prop="productionName"/>
      <el-table-column label="执行单图" align="center" min-width="100">
        <template slot-scope="scope">
          <el-image
              v-if="scope.row.drawingPath"
              :src="getFullImageUrl(scope.row.drawingPath)"
              style="width:80px; height:80px; object-fit:cover; border-radius:4px;"
              :preview-src-list="[getFullImageUrl(scope.row.drawingPath)]"
              fit="cover"
          />
          <span v-else style="color: #909399; font-size: 12px;">暂无执行单图</span>
        </template>
      </el-table-column>
      <el-table-column label="图纸类型" align="center" prop="drawingType">
        <template slot-scope="scope">
          <span v-if="scope.row.drawingType">
            {{ getDrawingTypeLabel(scope.row.drawingType) }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="计量单位" align="center" prop="unit"/>
      <!-- <el-table-column label="产品数量" align="center" prop="quantity"/>-->
      <el-table-column label="是否企标" align="center" prop="isEnterpriseStandard">
        <template slot-scope="scope">
          <span>{{ scope.row.isEnterpriseStandard === 1 ? '是' : '否' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目完成时间" align="center" prop="projectEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.projectEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
     
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
      <el-table-column label="生产开始时间" align="center" prop="planStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planStartTime, '{y}年{m}月{d}日') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产结束时间" align="center" prop="planEndTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planEndTime, '{y}年{m}月{d}日') }}</span>
        </template>
      </el-table-column>
              
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-dropdown :split-button="true" size="small" type="primary" @click="handleBOM(scope.row.productionOrderNo)"
                       @command="(command)=>handleCommand(command, scope.row)">
            查看BOM
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="工艺" v-hasPermi="['system:orderPro:remove']">查看工艺</el-dropdown-item>
              <el-dropdown-item :divided="true" command="修改" v-hasPermi="['system:orderPro:edit']">修改
              </el-dropdown-item>
              <el-dropdown-item :divided="true" command="删除" v-hasPermi="['system:orderPro:remove']">删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>



        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
    />
    <el-drawer
        :title="getDrawerTitle()"
        :visible.sync="drawer"
        :direction="direction"
        :before-close="handleClose"
        :size="1500"
    >
      <el-divider content-position="center">
          <span style="color: #67C23A; font-weight: 600; font-size: 14px;">
            <i class="el-icon-picture" style="margin-right: 6px;"></i>
            选择产品
          </span>
      </el-divider>
      <div style="padding: 20px;">
        <!-- 第一部分：销齿链型号表格管理 -->
        <el-button type="primary" @click="openAddChainDialog" size="mini" style="margin-bottom:10px;">新增</el-button>
        <el-table
            :data="chainTable"
            border
            stripe
            size="small"
            style="width: 100%; margin-bottom: 10px;"
            highlight-current-row
            :header-cell-style="{ fontWeight: 'bold', background: '#f5f7fa' }"
        >

          <el-table-column prop="figureNumber" label="产品型号" min-width="100"/>
          <el-table-column prop="figureName" label="产品名称" min-width="140"/>
          <el-table-column prop="jdInventory" label="行程" min-width="80"/>
          <el-table-column prop="figureNum" label="数量" min-width="60"/>
          <el-table-column prop="drawPath" label="文件路径" min-width="120" :show-overflow-tooltip="true"/>
          <el-table-column prop="productType" label="产品类型" min-width="100"/>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <div style="display: flex; align-items: center; gap: 8px;">
                <el-upload
                    :action="dwgUploadUrl"
                    :headers="uploadHeaders"
                    :data="{ id: scope.row.id }"
                    :show-file-list="false"
                    :before-upload="(file) => beforeDwgUpload(file, scope.row)"
                    :on-success="(response, file) => handleDwgUploadSuccess(response, file, scope.row)"
                    :on-error="(error, file) => handleDwgUploadError(error, file, scope.row)"
                    accept=".dwg"
                    :disabled="form.isEnterpriseStandard === 1"
                >
                  <el-button size="mini" type="primary" :disabled="form.isEnterpriseStandard === 1">
                    <i class="el-icon-upload2"></i> 上传
                  </el-button>
                </el-upload>
                
                <el-button type="text" size="mini" @click="editChain(scope.$index, scope.row)">
                  <i class="el-icon-edit"></i> 修改
                </el-button>
                
                <el-button type="text" size="mini" @click="removeChain(scope.$index)">
                  <i class="el-icon-delete"></i> 删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-divider content-position="center">
          <span style="color: #67C23A; font-weight: 600; font-size: 14px;">
            <i class="el-icon-picture" style="margin-right: 6px;"></i>
            执行出图
          </span>
        </el-divider>
        <!-- 第二部分：执行出图命令及日志展示 -->
        <div style="margin-bottom: 20px;">
          <el-button type="success" :loading="drawLoading" @click="executeDrawCommand" style="margin-bottom: 10px;">
            执行出图
          </el-button>
          <el-button type="primary" @click="downloadPDF" style="margin-bottom: 10px; margin-left: 10px;">
            下载PDF
          </el-button>
          <el-button type="warning" @click="downloadRoute" style="margin-bottom: 10px; margin-left: 10px;" v-hasPermi="['system:route:exportRoute']">
            下载生产工艺计划表
          </el-button>
          <el-progress :text-inside="true" :stroke-width="26" :percentage="percentage"></el-progress>
          <el-card shadow="never" style="background: #f9f9f9; min-height: 120px; max-height: 220px; overflow-y: auto;">
            <div style="font-size: 13px; color: #333; white-space: pre-line;">
              <template v-if="drawLog">{{ drawLog }}</template>
              <template v-else>暂无日志</template>
            </div>
          </el-card>
        </div>
        <el-divider content-position="center">
          <span style="color: #409EFF; font-weight: 600; font-size: 14px;">
            <i class="el-icon-more" style="margin-right: 6px;"></i>
            MRP运算结果复查
          </span>
        </el-divider>
        <!-- 第三部分：预留 -->
        <div style="color: #aaa; font-size: 13px;"></div>
        <!-- 第三部分：MRP运算结果复查表格 -->
        <el-card class="box-card mrp-result-card" style="margin-bottom: 20px;">
          <div slot="header" class="clearfix">
            <span style="font-weight: 600; color: #303133;">
              <i class="el-icon-data-analysis" style="margin-right: 8px; color: #409EFF;"></i>
              MRP运算结果复查
            </span>
            <div style="float: right; display: flex; align-items: center; gap: 12px;">
              <!-- 运算状态显示 -->
              <div v-if="loadingMRP" class="mrp-status-indicator">
                <i class="el-icon-loading" style="margin-right: 6px;"></i>
                <span>{{ mrpOperationStatus || 'MRP运算进行中...' }}</span>
              </div>

              <!-- 运算结果按钮 -->
              <el-button
                  type="primary"
                  size="medium"
                  :loading="loadingMRP"
                  :disabled="loadingMRP"
                  @click="getMRPResults()"
                  class="mrp-calculate-btn"
              >
                {{ loadingMRP ? '核算中...' : '开始核算' }}
              </el-button>

              <!-- 搜索输入框 -->
              <el-input
                  v-model="mrpSearchKeyword"
                  placeholder="搜索物料名称或编码"
                  style="width: 220px;"
                  size="small"
                  clearable
                  @input="handleMrpSearch"
                  @clear="clearMrpSearch"
                  class="mrp-search-input"
              >
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>

              <!-- 导出按钮 -->
              <el-button
                  type="success"
                  size="small"
                  icon="el-icon-download"
                  @click="handleExportMrp"
                  :loading="exportLoading"
                  :disabled="!productionObj || !productionObj.id"
                  class="mrp-export-btn"
                  :title="productionObj && productionObj.id ? `导出${productionObj.productionOrderNo}的MRP数据` : '请先选择生产令号'"
              >
                导出Excel
              </el-button>

              <el-button type="text" @click="handleRefreshMrpData">
                <i class="el-icon-refresh"></i> 刷新
              </el-button>
            </div>
          </div>
          <!-- 统计信息 -->
          <div
              style="margin-bottom: 15px; padding: 15px; background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%); border-radius: 8px; border-left: 4px solid #409EFF;">
            <el-row :gutter="20">
              <el-col :span="6">
                <div style="text-align: center;">
                  <div style="font-size: 24px; font-weight: bold; color: #409EFF;">{{ mrpStats.totalMaterials }}</div>
                  <div style="font-size: 12px; color: #606266;">总物料数</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div style="text-align: center;">
                  <div style="font-size: 24px; font-weight: bold; color: #67c23a;">{{ mrpStats.positiveStock }}</div>
                  <div style="font-size: 12px; color: #606266;">正库存</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div style="text-align: center;">
                  <div style="font-size: 24px; font-weight: bold; color: #f56c6c;">{{ mrpStats.negativeStock }}</div>
                  <div style="font-size: 12px; color: #606266;">负库存</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div style="text-align: center;">
                  <div style="font-size: 24px; font-weight: bold; color: #e6a23c;">{{ mrpStats.zeroStock }}</div>
                  <div style="font-size: 12px; color: #606266;">零库存</div>
                </div>
              </el-col>
            </el-row>
          </div>
          <el-table
              :data="mrpResultData"
              style="width: 100%"
              :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
              :row-class-name="getMrpRowClass"
              border
              stripe
              size="small"
              v-loading="mrpLoading"
          >
            <el-table-column prop="materialCode" label="物料编码" min-width="120" show-overflow-tooltip/>
            <el-table-column prop="materialName" label="物料名称" min-width="100" show-overflow-tooltip/>
            <el-table-column label="项目本批数" width="130" align="right">
          <template slot-scope="scope">
            <span style="color: #e6a23c">
              {{ formatFraction(scope.row.purchaseNotInStock) }}
            </span>
          </template>
          </el-table-column>

            <el-table-column prop="availableStock" label="本项目可用库存" width="120" align="right">
              <template slot-scope="scope">
                <span :style="{ color: scope.row.availableStock < 0 ? '#f56c6c' : '#67c23a' }">
                  {{ scope.row.availableStock.toFixed(3) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="realTimeStock" label="当前可用库存" width="100" align="right">
              <template slot-scope="scope">
                <span :style="{ color: scope.row.realTimeStock < 0 ? '#f56c6c' : '#67c23a' }">
                  {{ scope.row.realTimeStock.toFixed(3) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="prodNotInStock" label="本次生产未入库" width="130" align="right">
              <template slot-scope="scope">
                <span style="color: #e6a23c">{{ scope.row.prodNotInStock.toFixed(3) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="purchaseRequestQty" label="本项目采购申请" width="130" align="right">
              <template slot-scope="scope">
                <span style="color: #409eff">{{ scope.row.purchaseRequestQty.toFixed(3) }}</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="childNotPickedQty" label="子项未领料数量" width="130" align="right">
              <template slot-scope="scope">
                <span style="color: #f56c6c">{{ scope.row.childNotPickedQty.toFixed(3) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="160" align="center">
              <template slot-scope="scope">
                {{ formatDateTime(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="160" align="center">
              <template slot-scope="scope">
                {{ formatDateTime(scope.row.updateTime) }}
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <el-pagination
              @size-change="handleMrpSizeChange"
              @current-change="handleMrpCurrentChange"
              :current-page="mrpQueryParams.pageNum"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="mrpQueryParams.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="mrpTotal"
              style="margin-top: 20px; text-align: right;"
          />
        </el-card>
        <!-- 新增/编辑弹窗 -->
        <el-dialog
            :title="isEditChain ? '编辑销齿链型号' : '新增销齿链型号'"
            :visible.sync="chainDialogVisible"
            width="420px"
            append-to-body
        >
          <el-form :model="chainForm" label-width="100px">
            <div
                style="margin-bottom: 16px; padding: 12px; background-color: #f0f9ff; border: 1px solid #b3d8ff; border-radius: 4px; color: #409eff; font-size: 13px;">
              <i class="el-icon-info" style="margin-right: 6px;"></i>
              <strong>操作说明：</strong>可以先搜索选择已有型号自动填充，或直接手动填写所有必填字段（带*号）
            </div>
            <el-form-item label="销齿链型号">
              <div style="margin-bottom: 8px; color: #909399; font-size: 12px;">
                可选择已有型号或手动填写所有信息
              </div>
              <el-select
                  v-model="chainForm.id"
                  filterable
                  remote
                  reserve-keyword
                  placeholder="请输入行程/类型/名称/产品名（可选）"
                  :remote-method="searchRigidChain"
                  :loading="chainLoading"
                  @change="onRigidChainSelect"
                  popper-class="chain-autocomplete-dropdown"
                  :default-first-option="false"
                  clearable
              >
                <el-option
                    v-for="item in rigidChainOptions"
                    :key="item.id"
                    :label="item.productName"
                    :value="item.id"
                >
                  <div class="chain-suggestion-item">
                    <div class="chain-name">{{ item.figureNumber }}</div>
                    <div class="chain-info">
                      <span>编码: {{ item.typeName }}</span>
                      <span>产品名: {{ item.productName }}</span>
                      <span>类型: {{ item.type }}</span>
                      <span>行程: {{ item.journey }}</span>
                    </div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="产品名称" required>
              <el-input v-model="chainForm.figureName" placeholder="请输入产品名称"/>
            </el-form-item>
            <el-form-item label="生产令号">
              <el-input v-model="chainForm.productionCode" placeholder="请输入生产令号"/>
            </el-form-item>
            <el-form-item label="产品型号" required>
              <el-input v-model="chainForm.figureNumber" placeholder="请输入产品型号"/>
            </el-form-item>
            <el-form-item label="数量" required>
              <el-input v-model="chainForm.figureNum" placeholder="请输入数量" type="number" min="1"/>
            </el-form-item>
            <el-form-item label="行程" required>
              <el-input v-model="chainForm.jdInventory" placeholder="请输入行程"/>
            </el-form-item>
            <!-- 文件路径和DWG上传，企标可编辑，非企标只读+可上传 -->
            <el-form-item label="文件路径">
              <div>
                <el-select
                    v-model="chainForm.selectedFileType"
                    placeholder="请选择文件类型"
                    @change="onConfigIniSelect"
                    filterable
                    clearable
                >
                  <el-option
                      v-for="item in configIniOptions"
                      :key="item.fileType"
                      :label="item.fileType"
                      :value="item.fileType"
                  />
                </el-select>
              </div>
              <div>
                <el-input v-model="chainForm.drawPath" placeholder="请输入文件路径"/>
              </div>
            </el-form-item>
            <el-form-item label="产品类型" required>
              <el-input v-model="chainForm.productType" placeholder="请输入产品类型"/>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer" style="text-align: right;">
            <el-button @click="chainDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveChainForm">确 定</el-button>
          </div>
        </el-dialog>
      </div>
    </el-drawer>


    <el-drawer
        title="BOM明细 " :visible.sync="bomDrawer" direction="rtl" :size="1500">
      <div style="padding: 20px;">
        <bomInfo v-if="bomDrawer" :params="bomParams"/>
      </div>
    </el-drawer>

    <el-drawer
        title="工艺路线 " :visible.sync="processDrawer" direction="rtl" :size="1500">
      <div style="padding: 20px;">
        <processInfo v-if="processDrawer" :params="processParams"/>
      </div>
    </el-drawer>

    <!-- 添加或修改项目令号对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="生产令号" prop="productionOrderNo">
          <el-input v-model="form.productionOrderNo" placeholder="请输入生产令号"/>
        </el-form-item>
        <el-form-item label="项目名称" prop="productionName">
          <el-input v-model="form.productionName" placeholder="请输入项目名称"/>
        </el-form-item>
        <!-- 新增：产品图片上传功能 -->
        <el-form-item label="产品图片">
          <image-upload v-model="form.drawingPath" :limit="1" :file-size="5"/>
        </el-form-item>
        <el-form-item label="完成时间" prop="projectEndTime">
          <el-date-picker clearable
                          v-model="form.projectEndTime"
                          type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择项目完成时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计量单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入计量单位"/>
        </el-form-item>
        <el-form-item label="是否企标" prop="isEnterpriseStandard">
          <el-select v-model="form.isEnterpriseStandard" placeholder="请选择是否企标" clearable>
            <el-option label="否" :value="0"/>
            <el-option label="是" :value="1"/>
          </el-select>
        </el-form-item>
<!--        &lt;!&ndash; 文件路径输入框，非企标时只读 &ndash;&gt;
        <el-form-item label="文件路径" prop="drawingPath">
          <el-input v-model="form.drawingPath" :readonly="form.isEnterpriseStandard !== 1"
                    placeholder="企标可填写，非企标请在子表单上传DWG文件"/>
        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.el-dropdown {
  vertical-align: top;
}

.el-dropdown + .el-dropdown {
  margin-left: 15px;
}

.el-icon-arrow-down {
  font-size: 12px;
}
</style>

<script>
import {
  listOrderPro,
  getOrderPro,
  delOrderPro,
  addOrderPro,
  updateOrderPro,
  getDrawingTypeDict,
  listSave,
  executDrawing,
  delSave,
  uploadPDF,
  exportRoute,
  getMRPResults
} from "@/api/system/orderPro";
import {processList} from "../../../api/system/orderPro";
import {listRigidChain} from '@/api/system/pcRigidChain';
import {addProduct} from '@/api/system/orderPro';
import {getstate} from '@/utils/external-api';
import {listConfigIni} from '@/api/system/configIni';
import ImageUpload from '@/components/ImageUpload';
import {getToken} from '@/utils/auth';
import bomInfo from '@/views/system/details/index.vue'; //bom明细
import processInfo from '@/views/system/route/index.vue'; //工艺信息
import {listMrp, exportMrp} from '@/api/system/mrp';
import dayjs from "dayjs";

export default {
  name: "OrderPro",
  components: {
    ImageUpload,
    bomInfo,
    processInfo,
  },
  data() {
    return {
      // 定时器
      time: null,
      // 进度
      percentage: 0,
      drawer: false,
      direction: 'rtl',
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目令号表格数据
      orderProList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productionOrderNo: undefined,
        productionName: undefined,
        drawingNo: undefined,
        drawingName: undefined,
        bomStatus: undefined,
        routeStatus: undefined,
        planEndTime: undefined,
        planStartTime: undefined,
        drawingType: undefined,
        projectEndTime: undefined,
        unit: undefined,
        quantity: undefined,
        isEnterpriseStandard: undefined,
        drawingPath: undefined
      },
      // 表单参数
      form: {},
      //bom明细
      bomDrawer: false,
      bomParams: {},
      //工艺信息
      processDrawer: false,
      processParams: {},

      // 图纸类型选项
      drawingTypeOptions: [],
      // MRP运算结果复查相关数据
      mrpResultData: [],
      mrpLoading: false,
      mrpTotal: 0,
      mrpSearchKeyword: '',
      mrpQueryParams: {
        pageNum: 1,
        pageSize: 10,
        materialName: '',
        materialCode: '',
        orderProId: null
      },
      loadingMRP: false,
      mrpOperationStatus: '', // MRP运算状态
      exportLoading: false, // 导出加载状态
      mrpStats: {
        totalMaterials: 0,
        positiveStock: 0,
        negativeStock: 0,
        zeroStock: 0
      },
      // 表单校验
      rules: {

        productionOrderNo: [
          {required: true, message: "生产令号不能为空", trigger: "blur"}
        ],
        productionName: [
          {required: true, message: "项目名称不能为空", trigger: "blur"}
        ],
        drawingNo: [
          {required: true, message: "图号不能为空", trigger: "blur"}
        ],
        drawingName: [
          {required: true, message: "名称不能为空", trigger: "blur"}
        ],

        drawingType: [
          {
            validator: (rule, value, callback) => {
              if (this.form.isEnterpriseStandard === 1 && !value) {
                callback(new Error('图纸类型不能为空'));
              } else {
                callback();
              }
            },
            trigger: "change"
          }
        ],
        projectEndTime: [
          {required: true, message: "项目完成时间不能为空", trigger: "blur"}
        ],
        unit: [
          {required: true, message: "计量单位不能为空", trigger: "blur"}
        ],
        quantity: [
          {required: true, message: "数量不能为空", trigger: "blur"}
        ],
        isEnterpriseStandard: [
          {required: true, message: "是否企标 (0-否, 1-是)不能为空", trigger: "blur"}
        ],
      /*  drawingPath: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback(new Error('图纸路径不能为空'));
              }
              // 你可以加更多条件
              callback();
            },
            trigger: "blur"
          }
        ]*/
      },
      productionObj: null,
      id: '',
      // 销齿链型号表单
      chainTable: [], // 销齿链型号表格数据
      chainForm: {
        pid: '',
        jdInventory: '',
        figureNumber: '',
        productType: '',
        figureNum: '',
        productName: '',
        productionCode: '',
        selectedFileType: '', // 新增
      },
      chainDialogVisible: false, // 控制新增/编辑弹窗
      isEditChain: false, // 区分新增/编辑
      editChainIndex: null, // 编辑时的索引
      rigidChainOptions: [],
      chainLoading: false,
      drawLog: '', // 出图日志内容
      drawLoading: false, // 出图按钮 loading
      currentPid: null, // 当前项目id
      configIniOptions: [], // 文件类型下拉选项
      dwgUploadUrl: process.env.VUE_APP_BASE_API + '/system/orderPro/uploadDwg',
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      }
    };
  },
  created() {
    this.getList();
    this.getDrawingTypeOptions();
    this.getConfigIniOptions(); // 新增

    this.$api = {addProduct};
  },
  watch: {
    'form.isEnterpriseStandard': function (newVal) {
      if (newVal !== 1) {
        this.form.drawingType = undefined;
        this.form.drawingPath = undefined;
      }
    },
    'form.drawingType': function (newVal) {
      if (this.form.isEnterpriseStandard === 1) {
        if (newVal) {
          const option = this.drawingTypeOptions.find(item => item.fileType === newVal);
          this.form.drawingPath = option ? option.fileUrl : '';
        } else {
          this.form.drawingPath = '';
        }
      }
      // 不是企标时，drawingPath 保持手填内容
    }
  },
  methods: {
        formatFraction(value) {
      // 如果本身就是分数字符串，直接返回
      if (typeof value === 'string' && value.includes('/')) {
        return value;
      }
      // 如果是数字或数字字符串，直接原样返回（或保留三位小数）
      if (!isNaN(value)) {
        return parseFloat(value).toFixed(3); 
      }
      return value; // 兜底
    },
    
    // 处理分数值，用于数据处理阶段
    formatFractionValue(value) {
      // 如果本身就是分数字符串，直接返回
      if (typeof value === 'string' && value.includes('/')) {
        return value;
      }
      // 如果是数字，转换为数字
      if (!isNaN(value) && value !== null && value !== undefined) {
        return Number(value);
      }
      return 0; // 兜底
    },
    handleCommand(command, row) {
      if ("工艺" === command) {
        this.handleDetail(row.productionOrderNo)
      }
      if ("修改" === command) {
        this.handleUpdate(row)
      }
      if ("删除" === command) {
        this.handleDelete(row)
      }
    },
    handleClose(done) {
      done();
    },
    /** 获取图纸类型选项 */
    getDrawingTypeOptions() {
      getDrawingTypeDict().then(response => {
        this.drawingTypeOptions = response.rows.map(item => ({
          fileType: item.fileType,
          fileUrl: item.fileUrl
        }));
      }).catch(() => {
        this.drawingTypeOptions = [
          {fileType: '机械图纸', fileUrl: 'mechanical'},
          {fileType: '电气图纸', fileUrl: 'electrical'},
          {fileType: '工艺图纸', fileUrl: 'process'},
          {fileType: '装配图纸', fileUrl: 'assembly'}
        ];
      });
    },
    productionCodeHandle(row) {
      this.productionObj = row;
      this.drawer = true;
      // 打开抽屉后加载表格数据
      this.loadChainTableData();
    },
    /** 获取图纸类型标签 */
    getDrawingTypeLabel(value) {
      const option = this.drawingTypeOptions.find(item => item.fileType === value);
      if (option) {
        return option.fileType;
      }
      // 如果没有找到匹配的选项，尝试从路径中提取文件名
      if (value && typeof value === 'string') {
        const fileName = value.split('/').pop() || value.split('\\').pop();
        return fileName || value;
      }
      return value;
    },
    /** 查询项目令号列表 */
    getList() {
      this.loading = true;
      listOrderPro(this.queryParams).then(response => {

        this.orderProList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        productionOrderNo: undefined,
        productionName: undefined,
        drawingNo: undefined,
        drawingName: undefined,
        createTime: undefined,
        updateTime: undefined,
        createBy: undefined,
        updateBy: undefined,
        bomStatus: undefined,
        routeStatus: undefined,
        planEndTime: undefined,
        planStartTime: undefined,
        drawingType: undefined,
        projectEndTime: undefined,
        unit: undefined,
        quantity: undefined,
        isEnterpriseStandard: 0, // 默认为否
        drawingPath: undefined
      };
      this.resetForm("form");
    },
    handleDetail(productionOrderNo) {
      this.processParams = {productionOrderNo: productionOrderNo};
      this.processDrawer = true
    },
    handleBOM(productionOrderNo) {
      this.bomParams = {productionOrderNo: productionOrderNo};
      this.bomDrawer = true
    },
    /** MRP运算结果复查相关方法 */
    // 获取MRP运算结果
    async getMRPResults() {
      if (!this.productionObj || !this.productionObj.id) {
        this.$message.error('请先选择生产令号');
        return;
      }

      // 只显示一次开始提示，不重复弹窗
      this.$message({
        message: 'MRP运算已开始，由于数据量较大，可能需要较长时间，请耐心等待...',
        type: 'info',
        duration: 6000, // 减少到6秒
        showClose: true
      });

      this.loadingMRP = true;
      this.mrpOperationStatus = 'MRP运算已开始，正在处理数据...';

      // 只更新状态，不弹窗提醒
      const progressTimer = setInterval(() => {
        this.mrpOperationStatus = 'MRP运算仍在进行中，请继续等待...';
        // 移除弹窗提示，只更新状态显示
      }, 30000);

      try {
        const response = await getMRPResults(this.productionObj.id);

        // 清除定时器
        clearInterval(progressTimer);

        if (response && response.code === 200) {
          this.$message.success('MRP运算完成！');
          // 运算完成后刷新MRP数据
          await this.getMrpData();
        } else {
          this.$message.error(response?.msg || 'MRP运算失败');
        }
      } catch (error) {
        // 清除定时器
        clearInterval(progressTimer);

        // 简化错误提示，避免重复弹窗
        if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
          this.$message.error('MRP运算超时，请稍后重试');
        } else {
          this.$message.error('MRP运算失败，请重试');
        }
      } finally {
        this.loadingMRP = false;
        this.mrpOperationStatus = ''; // 清空状态
      }
    },

    // 获取MRP数据
    async getMrpData() {
        this.mrpLoading = true;
        try {
          this.mrpQueryParams.orderProId = this.productionObj.id;
          const response = await listMrp(this.mrpQueryParams);

          if (response && response.rows) {
            // 统一转Number，避免 toFixed 报错
            const processedRows = response.rows.map(item => ({
              ...item,
              availableStock: Number(item.availableStock) || 0,
              realTimeStock: Number(item.realTimeStock) || 0,
              prodNotInStock: Number(item.prodNotInStock) || 0,
              purchaseRequestQty: Number(item.purchaseRequestQty) || 0,
              purchaseNotInStock: this.formatFractionValue(item.purchaseNotInStock),
              childNotPickedQty: Number(item.childNotPickedQty) || 0,
              createTime: item.createTime ? dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss') : '',
              updateTime: item.updateTime ? dayjs(item.updateTime).format('YYYY-MM-DD HH:mm:ss') : ''
            }));
            this.mrpResultData = processedRows;
            this.mrpTotal = response.total || processedRows.length;
            // 统计计算也用处理过的数字数据
            this.calculateMrpStats(processedRows);
          }
        } catch (error) {
          console.error('获取MRP数据失败:', error);
          this.$message.error('获取MRP数据失败');
        } finally {
          this.mrpLoading = false;
        }
      },


    // MRP分页大小改变
    handleMrpSizeChange(size) {
      this.mrpQueryParams.pageSize = size;
      this.mrpQueryParams.pageNum = 1;
      this.getMrpData();
    },

    // MRP当前页改变
    handleMrpCurrentChange(page) {
      this.mrpQueryParams.pageNum = page;
      this.getMrpData();
    },

    // 格式化日期时间
    formatDateTime(date) {
      if (!date) return '-';
      if (typeof date === 'string') {
        date = new Date(date);
      }
      if (isNaN(date.getTime())) return '-';

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    // MRP搜索处理
    handleMrpSearch() {
      this.mrpQueryParams.pageNum = 1;
      this.mrpQueryParams.materialCode = this.mrpSearchKeyword;
      console.log('MRP搜索参数:', this.mrpQueryParams);
      this.getMrpData();
    },

    // 清空MRP搜索
    clearMrpSearch() {
      this.mrpSearchKeyword = '';
      this.mrpQueryParams.materialCode = '';
      this.mrpQueryParams.pageNum = 1;
      this.getMrpData();
    },

    // 过滤MRP数据（前端过滤，作为备用方案）
    filterMrpData(data) {
      if (!this.mrpSearchKeyword) {
        return data;
      }

      const keyword = this.mrpSearchKeyword.toLowerCase();
      return data.filter(item =>
          item.materialName.toLowerCase().includes(keyword) ||
          item.materialCode.toLowerCase().includes(keyword)
      );
    },

    // 计算MRP统计信息
    calculateMrpStats(data) {
      const total = data.length;
      const positive = data.filter(item => item.availableStock > 0).length;
      const negative = data.filter(item => item.availableStock < 0).length;
      const zero = data.filter(item => item.availableStock === 0).length;

      this.mrpStats = {
        totalMaterials: total,
        positiveStock: positive,
        negativeStock: negative,
        zeroStock: zero
      };
    },

        // 获取抽屉标题
    getDrawerTitle() {
      if (!this.productionObj) {
        return '项目详情';
      }
      
      const orderNo = this.productionObj.productionOrderNo || '';
      const projectName = this.productionObj.productionName || '';
      
      if (orderNo && projectName) {
        return `项目详情 - ${orderNo} | ${projectName}`;
      } else if (orderNo) {
        return `项目详情 - ${orderNo}`;
      } else if (projectName) {
        return `项目详情 - ${projectName}`;
      } else {
        return '项目详情';
      }
    },
    
    // 刷新MRP数据
    handleRefreshMrpData() {
        this.mrpQueryParams.pageNum = 1;
        this.getMrpData();
    },

    // 导出MRP数据
    async handleExportMrp() {
      // 增强参数验证
      if (!this.productionObj) {
        this.$message.error('请先选择生产令号');
        return;
      }

      if (!this.productionObj.id) {
        this.$message.error('生产令号ID无效，请重新选择');
        return;
      }

      if (!this.productionObj.productionOrderNo) {
        this.$message.error('生产令号信息不完整，请重新选择');
        return;
      }

      // 调试信息
      console.log('productionObj:', this.productionObj);
      console.log('productionObj.id:', this.productionObj.id);
      console.log('mrpResultData.length:', this.mrpResultData?.length || 0);

      // 显示导出确认信息
      const exportInfo = `即将导出生产令号"${this.productionObj.productionOrderNo}"的MRP数据`;
      const searchInfo = this.mrpSearchKeyword ? `，包含搜索关键词"${this.mrpSearchKeyword}"` : '';
      const dataInfo = this.mrpResultData && this.mrpResultData.length > 0
        ? `，当前显示${this.mrpResultData.length}条记录`
        : '（后台将查询所有相关数据）';

      try {
        await this.$confirm(
          `${exportInfo}${searchInfo}${dataInfo}。\n\n确定要导出吗？`,
          '确认导出',
          {
            confirmButtonText: '确定导出',
            cancelButtonText: '取消',
            type: 'info'
          }
        );
      } catch (error) {
        // 用户取消导出
        return;
      }

      this.exportLoading = true;

      try {
        // 准备导出参数，主要传递orderProId给后台
        const exportParams = {
          orderProId: this.productionObj.id, // 核心参数：生产令号ID
          materialCode: this.mrpSearchKeyword || '', // 可选的物料编码搜索
          materialName: '', // 清空名称搜索，避免冲突
          pageSize: 9999, // 后台查询时获取所有数据
          pageNum: 1
        };

        // 详细调试信息
        console.log('导出参数:', exportParams);
        console.log('orderProId类型:', typeof exportParams.orderProId);
        console.log('orderProId值:', exportParams.orderProId);
        console.log('materialCode:', exportParams.materialCode);

        const response = await exportMrp(exportParams);

        // 创建下载链接
        const blob = new Blob([response], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `MRP运算结果_${this.productionObj.productionOrderNo}_${new Date().getTime()}.xlsx`;
        link.click();
        window.URL.revokeObjectURL(url);

        this.$message.success(`导出成功！文件已下载：MRP运算结果_${this.productionObj.productionOrderNo}_${new Date().getTime()}.xlsx`);
      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败: ' + (error.message || error));
      } finally {
        this.exportLoading = false;
      }
    },


    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.currentPid = null; // 新增时，不依赖当前行
      this.chainForm.productionCode = '';
      this.reset();
      this.open = true;
      this.title = "添加项目令号";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getOrderPro(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改项目令号";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateOrderPro(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addOrderPro(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除项目令号编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delOrderPro(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/orderPro/export', {
        ...this.queryParams
      }, `orderPro_${new Date().getTime()}.xlsx`)
    },
    openAddChainDialog() {
      this.isEditChain = false;
      this.chainForm = {
        productName: '',
        pid: this.id,
        productionCode: this.productionObj.productionOrderNo,
        figureName: '',
        figureNumber: '',
        figureNum: '',
        jdInventory: '',
        productType: '',
        selectedFileType: '', // 新增
        id: undefined, // 确保新增时没有id
      };
      this.chainDialogVisible = true;
    },
    editChain(index, row) {
      this.isEditChain = true;
      this.editChainIndex = index;
      this.chainForm = {...row};
      this.chainDialogVisible = true;
    },
    removeChain(index) {
      const row = this.chainTable[index];
      this.$modal.confirm('是否确认删除该销齿链型号？').then(() => {
        return delSave(row.id);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        // 删除成功后刷新表格数据
        this.loadChainTableData();
      }).catch(() => {
        // 删除失败时不显示错误信息，因为用户可能取消了操作
      });
    },
    async saveChainForm() {
      // 验证必填字段
      if (!this.chainForm.figureName) {
        this.$message.warning('产品名称不能为空');
        return;
      }
      if (!this.chainForm.figureNumber) {
        this.$message.warning('产品型号不能为空');
        return;
      }
      if (!this.chainForm.figureNum || Number(this.chainForm.figureNum) < 1) {
        this.$message.warning('数量不能为空且必须大于0');
        return;
      }
      if (!this.chainForm.productType) {
        this.$message.warning('产品类型不能为空');
        return;
      }
      // 组装数据，字段名与实体类完全一致
      const payload = {
        figureName: this.chainForm.figureName,
        productionCode: this.chainForm.productionCode,
        figureNumber: this.chainForm.figureNumber,
        figureNum: this.chainForm.figureNum,
        jdInventory: this.chainForm.jdInventory,
        drawPath: this.chainForm.drawPath || '',
        productType: this.chainForm.productType,
        pid: this.productionObj.id,
      };

      // 只有在编辑模式下才添加id字段
      if (this.isEditChain && this.chainForm.id) {
        payload.id = this.chainForm.id;
      }
      console.log('saveChainForm........', payload);
      try {
        await this.$api.addProduct(payload);
        this.$message.success('添加成功');
        this.chainDialogVisible = false;
        // 添加成功后刷新表格数据
        this.loadChainTableData();
      } catch (e) {
        this.$message.error('添加失败');
      }
    },
    searchRigidChain(query) {
      if (!query) {
        this.rigidChainOptions = [];
        return;
      }
      this.chainLoading = true;
      listRigidChain({typeName: query}).then(res => {
        this.rigidChainOptions = (res.rows || []).slice(0, 10); // 最多10条
        this.chainLoading = false;
      }).catch(() => {
        this.chainLoading = false;
      });
    },
    onRigidChainSelect(id) {
      if (!id) {
        // 用户清空了选择，重置相关字段，允许手动填写
        this.chainForm.figureName = '';
        this.chainForm.figureNumber = '';
        this.chainForm.jdInventory = '';
        this.chainForm.drawPath = '';
        this.chainForm.productType = '';
        this.chainForm.productName = '';
        return;
      }

      const selected = this.rigidChainOptions.find(item => item.id === id);

      if (selected) {
        this.chainForm.figureName = selected.productName || '';
        this.chainForm.figureNumber = selected.typeName || '';
        this.chainForm.jdInventory = selected.journey || '';
        this.chainForm.drawPath = selected.drawPath || '';
        this.chainForm.productType = selected.type || '';
        this.chainForm.productName = selected.productName || '';
        // 如果数量未填写，自动赋值为1
        if (!this.chainForm.figureNum) {
          this.chainForm.figureNum = 1;
        }
        // 在新增模式下，清除id字段，避免误传
        if (!this.isEditChain) {
          this.chainForm.id = undefined;
        }
      }
    },
    async executeDrawCommand() {
      this.drawLoading = true;
      this.drawLog = '';
      try {
        // 调用后端出图接口，传递当前pid和chainTable
        // const orderPro = null;
        const res = await executDrawing(this.productionObj);
        if (res.code === 200) {
          this.time = setInterval(async () => {
            const data = await getstate();

            if (data.processstate === 3) {
              // 分割消息
              const msg = data.msg.split(',');
              // 分割进度
              const percentage = msg[1].split('/');
              // 计算进度保留两位小数
              this.percentage = (percentage[0] / percentage[1] * 100).toFixed(2);
            }

            this.drawLog = data.msg;

            // 出图完成
            if (data.processstate === 4) {
              this.percentage = 100;
              clearInterval(this.time);
              this.time = null;
            }
          }, 1000);
        }


      } catch (e) {
        this.drawLog = '出图失败：' + (e.msg || e.message || e);
      } finally {
        this.drawLoading = false;
      }
    },
    // 加载销齿链型号表格数据
    async loadChainTableData() {
      if (!this.productionObj || !this.productionObj.id) {
        this.chainTable = [];
        return;
      }
      try {
        this.getMrpData(this.productionObj.id); // 获取MRP数据
        const response = await listSave({pid: this.productionObj.id});
        this.chainTable = response.rows || [];
      } catch (error) {
        console.error('加载表格数据失败:', error);
        this.chainTable = [];
      }
    },
    getConfigIniOptions() {
      listConfigIni().then(res => {
        this.configIniOptions = (res.rows || []).map(item => ({
          fileType: item.fileType,
          fileUrl: item.fileUrl
        }));
      });
    },
    onConfigIniSelect(fileType) {
      const selected = this.configIniOptions.find(item => item.fileType === fileType);
      if (selected) {
        this.chainForm.drawPath = selected.fileUrl;
      }
    },
    getFullImageUrl(path) {
      if (!path) return '';

      return path;
    },
    beforeDwgUpload(file, row) {
      // 验证文件格式
      const ext = file.name.split('.').pop().toLowerCase();
      if (ext !== 'dwg') {
        this.$message.error('仅支持dwg格式文件上传');
        return false;
      }
      
      // 验证行数据
      if (!row || !row.id) {
        this.$message.error('行数据无效，无法上传');
        return false;
      }
      
      // 验证文件大小（可选，限制为50MB）
      const maxSize = 50 * 1024 * 1024; // 50MB
      if (file.size > maxSize) {
        this.$message.error('文件大小不能超过50MB');
        return false;
      }
      
      return true;
    },
    handleDwgUploadSuccess(response, file, row) {
      if (response && response.code === 200) {
        // 刷新列表
        this.loadChainTableData();
        this.$message.success(`图纸上传成功：${file.name}`);
        
        // 可以在这里更新行的drawPath字段
        if (response.data && response.data.filePath) {
          row.drawPath = response.data.filePath;
        }
      } else {
        this.$message.error((response && response.msg) || '上传失败');
      }
    },
    handleDwgUploadError(error, file, row) {
      console.error('图纸上传失败:', error);
      this.$message.error(`图纸上传失败：${file.name}`);
    },
    downloadPDF() {
      if (!this.productionObj || !this.productionObj.id) {
        this.$message.error('请先选择生产令号');
        return;
      }

      this.$message.success('开始下载PDF文件');
      console.log('开始下载，生产令号ID:', this.productionObj.id);

      // 调用API获取文件流
      uploadPDF(this.productionObj.id)
          .then(response => {
            console.log('API响应:', response);
            console.log('响应类型:', typeof response);
            console.log('是否为Blob:', response instanceof Blob);

            // 检查响应是否为blob类型
            if (!(response instanceof Blob)) {
              console.error('响应不是文件流:', response);
              this.$message.error('服务器返回的不是文件流');
              return;
            }

            // 检查文件大小
            console.log('文件大小:', response.size);
            if (response.size === 0) {
              this.$message.error('文件为空或下载失败');
              return;
            }

            // 创建blob对象并下载
            let blob = new Blob([response], {type: 'application/zip'});
            let url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `${this.productionObj.productionOrderNo}_PDF.zip`;
            link.click();
            window.URL.revokeObjectURL(url);

            this.$message.success('PDF文件下载成功');
          })
          .catch(error => {
         
            this.$message.error('PDF文件下载失败: ' + (error.message || error));
          });
    },
    downloadRoute() {
      if (!this.productionObj || !this.productionObj.id) {
        this.$message.error('请先选择生产令号');
        return;
      }

      this.$message.success('开始下载生产工艺计划表');
      console.log('开始下载，生产令号ID:', this.productionObj.id);

      // 调用API获取文件流
      exportRoute(this.productionObj.id)
          .then(response => {
            // 检查文件大小
            if (response.size === 0) {
              this.$message.error('文件为空或下载失败');
              return;
            }

            // 创建blob对象并下载
            let blob = new Blob([response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
            let url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.download = `${this.productionObj.productionOrderNo}_生产工艺计划表.xlsx`;
            link.click();
            window.URL.revokeObjectURL(url);

            this.$message.success('生产工艺计划表下载成功');
          })
          .catch(error => {
            console.error('下载失败:', error);
            // 后端异常会直接抛出，显示错误信息
            this.$message.error('下载失败: ' + (error.message || '项目未出图'));
          });
    },
  },
  beforeMount() {
    clearInterval(this.time);
    this.time = null;
  }
};
</script>

<style scoped>
/* 移除按钮样式，使用默认样式 */

/* 图纸类型下拉选项样式 */
.drawing-option {
  padding: 8px 0;
  line-height: 1.4;
  width: 100%;
}

.drawing-header {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
}

.drawing-header i {
  color: #409eff;
  margin-right: 8px;
  font-size: 14px;
}

.drawing-type {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.drawing-path {
  display: flex;
  align-items: flex-start;
  color: #909399;
  font-size: 12px;
  line-height: 1.3;
  margin-top: 6px;
  width: 100%;
  padding-left: 22px; /* 与上面的图标对齐 */
}

.drawing-path i {
  color: #c0c4cc;
  margin-right: 8px;
  margin-top: 1px;
  font-size: 12px;
  flex-shrink: 0;
}

.path-text {
  flex: 1;
  word-break: break-all;
  white-space: normal;
  line-height: 1.4;
  color: #909399;
  font-size: 12px;
  display: block;
  overflow: visible;
}

/* 全局下拉框宽度控制 */
:global(.drawing-select-dropdown) {
  min-width: 600px !important;
  max-width: 800px !important;
}

:global(.drawing-select-dropdown .el-select-dropdown__item) {
  padding: 12px 16px !important;
  min-height: 80px !important;
}

:global(.drawing-select-dropdown .el-select-dropdown__item .drawing-option) {
  width: 100% !important;
}

:global(.drawing-select-dropdown .el-select-dropdown__item .drawing-path) {
  display: flex !important;
  align-items: flex-start !important;
  margin-top: 6px !important;
  padding-left: 22px !important;
}

:global(.drawing-select-dropdown .el-select-dropdown__item .path-text) {
  flex: 1 !important;
  word-break: break-all !important;
  white-space: normal !important;
  line-height: 1.4 !important;
  color: #909399 !important;
  font-size: 12px !important;
  display: block !important;
  overflow: visible !important;
}

:global(.drawing-select-dropdown .el-select-dropdown__item.selected .drawing-path) {
  color: rgba(255, 255, 255, 0.8) !important;
}

:global(.drawing-select-dropdown .el-select-dropdown__item.selected .path-text) {
  color: rgba(255, 255, 255, 0.8) !important;
}

.chain-suggestion-item {
  padding: 8px 10px;
  border-bottom: 1px solid #1e0d0d;
}

.chain-suggestion-item:last-child {
  border-bottom: none;
}

.chain-name {
  font-size: 14px;
  color: #124dc4;
  margin-bottom: 4px;
}

.chain-info {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  color: #909399;
  font-size: 12px;
  margin-top: 2px;
  line-height: 1.3;
  word-break: break-all;
}

.chain-info span {
  margin-right: 8px;
}

.el-select {
  width: 100%;
  margin-bottom: 20px;
}

.project-name-column {
  color: #008B8B; /* 深青绿色 */
  font-weight: 500;
}

.project-name-column {
  color: #008B8B; /* 深青绿色 */
  font-weight: 500;
}

/* MRP运算结果复查表格样式 */
.mrp-result-card .el-card__header {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 2px solid #409EFF;
}

.mrp-result-card .el-table {
  margin-top: 10px;
}

.mrp-result-card .el-table th {
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7ed 100%) !important;
  color: #606266;
  font-weight: 600;
}

.mrp-result-card .el-table--striped .el-table__body tr.el-table__row--striped td {
  background-color: #fafafa;
}

.mrp-result-card .el-table__body tr:hover > td {
  background-color: #f0f9ff !important;
}

/* 数值列的颜色样式 */
.mrp-result-card .el-table .cell {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
}

/* 分页样式 */
.mrp-result-card .el-pagination {
  margin-top: 20px;
  text-align: right;
}

.mrp-result-card .el-pagination .el-pager li {
  background: #fff;
  border: 1px solid #d9d9d9;
  color: #606266;
}

.mrp-result-card .el-pagination .el-pager li.active {
  background: #409EFF;
  color: #fff;
  border-color: #409EFF;
}

/* 负库存行样式 */
.mrp-result-card .el-table .negative-stock-row {
  background-color: #fef0f0 !important;
}

.mrp-result-card .el-table .negative-stock-row:hover > td {
  background-color: #fde2e2 !important;
}

/* 零库存行样式 */
.mrp-result-card .el-table .zero-stock-row {
  background-color: #fdf6ec !important;
}

.mrp-result-card .el-table .zero-stock-row:hover > td {
  background-color: #faecd8 !important;
}

/* MRP运算状态指示器样式 */
.mrp-status-indicator {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border: 1px solid #bae6fd;
  border-radius: 6px;
  color: #0369a1;
  font-size: 13px;
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.mrp-status-indicator i {
  color: #0ea5e9;
  font-size: 14px;
}

/* MRP核算按钮样式 */
.mrp-calculate-btn {
  min-width: 100px;
  height: 36px;
  font-weight: 500;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.2);
  transition: all 0.3s ease;
}

.mrp-calculate-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.3);
}

.mrp-calculate-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

/* MRP导出按钮样式 */
.mrp-export-btn {
  min-width: 90px;
  height: 32px;
  font-weight: 500;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(103, 194, 58, 0.2);
  transition: all 0.3s ease;
}

.mrp-export-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(103, 194, 58, 0.3);
}

.mrp-export-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

/* MRP搜索输入框样式 */
.mrp-search-input {
  transition: all 0.3s ease;
}

.mrp-search-input:hover .el-input__inner {
  border-color: #409EFF;
}

.mrp-search-input .el-input__inner:focus {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}
</style>
