<template>
  <div class="p-2">
    <<<<<<< HEAD <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="110px">
            <el-form-item label="分包类型名称" prop="dictName">
              <el-input v-model="queryParams.dictName" placeholder="请输入分包类型名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="计划招标时间" prop="plannedBiddingTime">
              <el-date-picker clearable v-model="queryParams.plannedBiddingTime" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择计划招标时间" />
            </el-form-item>
            <el-form-item label="招标方式" prop="plannedBiddingMethod">
              <el-select v-model="queryParams.plannedBiddingMethod" placeholder="请选择招标方式" clearable
                @change="handleQuery">
                <el-option label="公招" value="公招"></el-option>
                <el-option label="邀标" value="邀标"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="总价" prop="price">
              <el-input v-model="queryParams.price" placeholder="请输入总价" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="限价" prop="limitPrice">
              <el-input v-model="queryParams.limitPrice" placeholder="请输入限价" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="合同额" prop="contractPrice">
              <el-input v-model="queryParams.contractPrice" placeholder="请输入合同额" clearable @keyup.enter="handleQuery" />
              =======
              <el-tabs type="border-card" @tab-change="handleTabChange" v-model="activeTab">
                <el-tab-pane v-for="(item, index) in tabList" :key="item.index" :label="item.label" :name="item.value">
                  <el-card shadow="always">
                    <el-form :model="queryForm" :inline="true" ref="queryFormRef">
                      <el-form-item label="名称" prop="versions">
                        <el-input v-model="queryForm.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
                      </el-form-item>
                      <el-form-item label="内容" prop="sheet">
                        <el-input v-model="queryForm.content" placeholder="请输入内容" clearable
                          @keyup.enter="handleQuery" />
                        >>>>>>> aab67593ebb8d9116738d0d867a6119ba61615c8
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                        <<<<<<< HEAD </el-form-item>
                    </el-form>
                  </el-card>
      </div>
      </transition>

      <el-card shadow="never">
        <template #header>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
                v-hasPermi="['plan:plan:edit']">修改</el-button>
            </el-col>
            <!-- 多文件上传按钮 -->
            <el-col :span="2">
              <el-button type="primary" plain icon="Upload" @click="openFileUploadDialog()"
                v-hasPermi="['plan:plan:upload']"> 上传文件 </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" plain icon="Download" @click="handleExport"
                v-hasPermi="['plan:plan:export']">导出</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>
        </template>

        <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="主键ID" align="center" prop="id" v-if="false" />
          <el-table-column label="项目Id" align="center" prop="projectId" v-if="false" />
          <el-table-column label="分包类型名称" align="center" prop="dictName" />
          <el-table-column label="名称" align="center" prop="name" />
          <el-table-column label="计划招标时间" align="center" prop="plannedBiddingTime" width="180" v-if="false">
            <template #default="scope">
              <span>{{ parseTime(scope.row.plannedBiddingTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="招标方式" align="center" prop="plannedBiddingMethod">
            <template #default="scope">
              {{
                ['1', 1].includes(scope.row.plannedBiddingMethod)
                  ? '公招'
                  : ['2', 2].includes(scope.row.plannedBiddingMethod)
                    ? '邀标'
                    : scope.row.plannedBiddingMethod || '-'
              }}
            </template>
          </el-table-column>
          <el-table-column label="总价" align="center" prop="price" v-if="false" />
          <el-table-column label="限价" align="center" prop="limitPrice" />
          <el-table-column label="合同额" align="center" prop="contractPrice" />
          <el-table-column label="分包内容" align="center" prop="content" />
          <el-table-column label="中标通知书" align="center" prop="bidFile">
            <template #default="scope">
              <el-link @click="handleView(scope.row, 'bidFile')" type="primary" v-if="scope.row.bidFile">查看</el-link>
            </template>
          </el-table-column>
          <el-table-column label="招标通知书" align="center" prop="tenderFile">
            <template #default="scope">
              <el-link @click="handleView(scope.row, 'tenderFile')" type="primary"
                v-if="scope.row.tenderFile">查看</el-link>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="修改" placement="top">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['plan:plan:edit']"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-card>

      <!-- 多文件上传对话框 -->
      <el-dialog :title="fileUploadDialog.title" v-model="fileUploadDialog.visible" width="600px" append-to-body>
        <div class="upload-container">
          <el-upload class="upload-demo" drag action="" :http-request="handleFileUpload" :multiple="true"
            :on-preview="handleFilePreview" :on-remove="handleFileRemove" :file-list="fileList" :auto-upload="false">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">点击或拖拽文件到此处上传</div>
            <template #tip>
              <div class="el-upload__tip text-sm text-gray-500">支持上传多个文件，格式不限，单个文件大小不超过10MB</div>
            </template>
          </el-upload>

          <div class="mt-4 flex justify-end">
            <el-button @click="cancelFileUpload">取消</el-button>
            <el-button type="primary" @click="submitFileUpload" class="ml-2"> 确认上传 </el-button>
          </div>
        </div>
      </el-dialog>

      <!-- 添加或修改招标计划对话框 -->
      <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
        <el-form ref="planFormRef" :model="form" :rules="rules" label-width="120px">
          <!-- 调整项目ID表单项：与目标代码一致，自动关联当前项目并显示提示 -->
          <el-input v-model="form.projectId" placeholder="请输入项目ID" :readonly="!!currentProjectId"
            :disabled="!!currentProjectId" v-if="false" />
          <template #help>
            <span v-if="currentProjectId" class="text-success">已自动关联当前选中项目</span>
          </template>
          <el-input v-model="form.id" placeholder="ID" readonly v-if="false" />
          <el-form-item label="分包类型名称" prop="dictName" v-if="false">
            <el-input v-model="form.dictName" placeholder="请输入分包类型名称" />
          </el-form-item>

          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入名称" />
          </el-form-item>

          <el-form-item label="计划招标时间" prop="plannedBiddingTime" v-if="false">
            <el-date-picker clearable v-model="form.plannedBiddingTime" type="date" value-format="YYYY-MM-DD"
              placeholder="请选择计划招标时间" />
          </el-form-item>

          <!-- 核心修改：招标方式改为下拉框，根据限价自动赋值 -->
          <el-form-item label="招标方式" prop="plannedBiddingMethod">
            <el-select v-model="form.plannedBiddingMethod" placeholder="自动生成/选择" :disabled="!!form.limitPrice">
              <el-option label="公招" value="公招"></el-option>
              <el-option label="邀标" value="邀标"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="总价" prop="price" v-if="false">
            <el-input v-model="form.price" placeholder="请输入总价" />
          </el-form-item>

          <!-- 限价输入：添加@input事件，实时触发招标方式判断 -->
          <el-form-item label="限价(单位万元)" prop="limitPrice">
            <el-input v-model.number="form.limitPrice" placeholder="请输入限价(单位万元)" type="number"
              @input="autoSetBiddingMethod" />
          </el-form-item>

          <el-form-item label="合同额" prop="contractPrice">
            <el-input v-model="form.contractPrice" placeholder="请输入合同额" />
          </el-form-item>

          <el-form-item label="分包内容" prop="content">
            <el-input v-model="form.content" type="textarea" placeholder="请输入分包内容" rows="3" />
          </el-form-item>

          <el-form-item label="中标通知书" prop="bidFile">
            <file-upload v-model="form.bidFile" :limit="1" />
          </el-form-item>
          <el-form-item label="招标通知书" prop="files">
            <file-upload v-model="form.tenderFile" :limit="100" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
      <el-dialog title="文件列表" v-model="viewVisible" width="45%">
        <el-table :data="viewFileList" style="width: 100%" border>
          <el-table-column prop="fileName" label="文件" align="center">
            <template #default="scope">
              <el-link :key="scope.row.ossId" :href="scope.row.url" target="_blank" type="primary" :underline="false">
                {{ scope.row.originalName || '查看文件' }}
              </el-link>
            </template>
          </el-table-column>
        </el-table>
        <template #footer>
          <span>
            <el-button type="primary" @click="viewVisible = false">关闭</el-button>
          </span>
        </template>
        =======
        <el-button type="primary" plain :icon="Plus" @click="openDialog"
          v-hasPermi="['tender:segmentedIndicatorPlanning:add']">新增</el-button>
        </el-form-item>
        </el-form>
        </el-card>
        <el-table :data="tableData" row-key="id" border v-loading="loading">
          <el-table-column label="序号" width="80" align="center">
            <template #default="scope">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="名称" />
          <el-table-column prop="content" label="内容" />
          <el-table-column prop="plannedBiddingTime" label="计划招标时间" align="center">
            <template #default="scope">
              <el-date-picker v-model="scope.row.plannedBiddingTime" type="date" value-format="YYYY-MM-DD"
                placeholder="选择时间" />
            </template>
          </el-table-column>
          <el-table-column prop="price" label="操作" align="center">
            <template #default="scope">
              <el-button type="warning" size="small" @click="handleDetail(scope.row)"
                v-hasPermi="['tender:segmentedIndicatorPlanning:getMore']">详情</el-button>
              <el-button type="primary" size="small" @click="handleSave(scope.row)"
                v-hasPermi="['tender:segmentedIndicatorPlanning:edit']">修改</el-button>
              <el-button type="danger" size="small" @click="delHandle(scope.row)"
                v-hasPermi="['tender:segmentedIndicatorPlanning:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
<<<<<<< HEAD
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
        </el-tab-pane>
        </el-tabs>
        <el-dialog title="新增" v-model="dialogVisible" width="75%" draggable>
          <el-row>
            <el-col :span="11">
              <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
                <el-form-item label="名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入名称" clearable />
                </el-form-item>
                <el-form-item label="内容" prop="content">
                  <el-input v-model="form.content" placeholder="请输入内容" type="textarea" clearable :rows="4" />
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
          <el-row style="margin-top: 20px">
            <el-col :span="24">
              <el-card shadow="never">
                <el-form :model="treeForm" :inline="true">
                  <el-form-item label="表名" prop="sheet">
                    <el-select v-model="treeForm.sheet" placeholder="选择表名" @change="changeSheet">
                      <el-option v-for="item in sheets" :key="item" :label="item" :value="item" />
                    </el-select>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="toggleExpandAll(true)">一键展开</el-button>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="toggleExpandAll(false)">一键收起</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
              <el-table :data="treeData" ref="treeTableRef" v-loading="treeLoading" row-key="id" border lazy
                default-expand-all @selection-change="handleSelection">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="num" label="编号" />
                <el-table-column prop="name" label="工程或费用名称" />
                <el-table-column prop="unit" label="单位" />
                <!-- <el-table-column prop="quantity" label="数量" /> -->
                <el-table-column prop="selectNum" label="选择数量" align="center">
                  <template #default="scope">
                    <el-input-number :model-value="scope.row.selectNum" @change="
                      (val) => {
                        scope.row.selectNum = val;
                        handleNumberChange(scope.row);
                      }
                    " :precision="2" :step="1" :controls="false" :max="Math.floor(scope.row.quantity)"
                      v-if="scope.row.quantity && scope.row.quantity != 0" />
                  </template>
                </el-table-column>
                <el-table-column prop="unitPrice" label="单价" align="center" />
                <!-- <el-table-column prop="price" label="总价" align="center">
=======
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </el-tab-pane>
    </el-tabs>
    <el-dialog title="新增" v-model="dialogVisible" width="75%" draggable>
      <el-row>
        <el-col :span="11">
          <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" clearable />
            </el-form-item>
            <el-form-item label="内容" prop="content">
              <el-input v-model="form.content" placeholder="请输入内容" type="textarea" clearable :rows="4" />
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row style="margin-top: 20px">
        <el-col :span="24">
          <el-card shadow="never">
            <el-form :model="treeForm" :inline="true">
              <el-form-item label="版本号" prop="versions">
                <el-select v-model="treeForm.versions" placeholder="选择版本号" @change="changeVersions">
                  <el-option v-for="item in options" :key="item.versions" :label="item.versions" :value="item.versions" />
                </el-select>
              </el-form-item>
              <el-form-item label="表名" prop="sheet">
                <el-select v-model="treeForm.sheet" placeholder="选择表名" @change="changeSheet">
                  <el-option v-for="item in sheets" :key="item" :label="item" :value="item" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="toggleExpandAll(true)">一键展开</el-button>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="toggleExpandAll(false)">一键收起</el-button>
              </el-form-item>
            </el-form>
          </el-card>
          <el-table
            :data="treeData"
            ref="treeTableRef"
            v-loading="treeLoading"
            row-key="id"
            border
            lazy
            default-expand-all
            @selection-change="handleSelection"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="num" label="编号" />
            <el-table-column prop="name" label="工程或费用名称" />
            <el-table-column prop="unit" label="单位" />
            <!-- <el-table-column prop="quantity" label="数量" /> -->
            <el-table-column prop="selectNum" label="选择数量" align="center">
              <template #default="scope">
                <el-input-number
                  :model-value="scope.row.selectNum"
                  @change="
                    (val) => {
                      scope.row.selectNum = val;
                      handleNumberChange(scope.row);
                    }
                  "
                  :precision="2"
                  :step="1"
                  :controls="false"
                  :max="Math.floor(scope.row.quantity)"
                  v-if="scope.row.quantity && scope.row.quantity != 0"
                />
              </template>
            </el-table-column>
            <el-table-column prop="unitPrice" label="单价" align="center" />
            <!-- <el-table-column prop="price" label="总价" align="center">
>>>>>>> f01487dc504b5118697a1f47b1c22d662f0ad48c
              <template #default="scope">
                {{ scope.row.price }}
              </template>
            </el-table-column> -->
              </el-table>
            </el-col>
          </el-row>
          <template #footer>
            <el-button @click="closeDialog">取消</el-button>
            <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
          </template>
        </el-dialog>
        <el-dialog title="详情" v-model="detailDialog" width="75%" draggable>
          <el-table :data="detailData" v-loading="detailLoading" row-key="id" border lazy default-expand-all>
            <el-table-column prop="num" label="编号" />
            <el-table-column prop="name" label="工程或费用名称" />
            <el-table-column prop="unit" label="单位" />
            <el-table-column prop="quantity" label="数量" />
            <el-table-column prop="unitPrice" label="单价" align="center" />
            <el-table-column prop="price" label="总价" align="center">
              <template #default="scope">
                {{ scope.row.price }}
              </template>
            </el-table-column>
          </el-table>
          >>>>>>> aab67593ebb8d9116738d0d867a6119ba61615c8
        </el-dialog>
  </div>
</template>

  <script setup name="Plan" lang="ts">
  import { listPlan, getPlan, addPlan, updatePlan, getSegmentedIndicatorPlanning } from '@/api/plan/plan/index';
  import { PlanVO, PlanQuery, PlanForm } from '@/api/plan/plan/types';
  import { getCurrentInstance, onMounted, ref, reactive, toRefs, computed, watch } from 'vue';
  import type { ElFormInstance } from 'element-plus';
  import { useUserStoreHook } from '@/store/modules/user';
<<<<<<< HEAD
  import { UploadFilled } from '@element-plus/icons-vue';
  import type { UploadFile, UploadRawFile } from 'element-plus';
  import { listByIds } from '@/api/system/oss';

  // 从用户Store获取当前选中项目及ID
  const userStore = useUserStoreHook();
  const currentProject = computed(() => userStore.selectedProject);
  const currentProjectId = computed(() => currentProject.value?.id);
  const viewVisible = ref(false);
  // 类型定义
  interface DialogOption {
    visible: boolean;
    title: string;
  }

  interface PageData<F, Q> {
    form: F;
    queryParams: Q;
    rules: Record<string, any[]>;
  }

  const { proxy } = getCurrentInstance() as ComponentInternalInstance;

  const planList = ref<PlanVO[]>([]);
  const buttonLoading = ref(false);
  const loading = ref(true);
  const showSearch = ref(true);
  const ids = ref<Array<string | number>>([]);
  const single = ref(true);
  const multiple = ref(true);
  const total = ref(0);

  const queryFormRef = ref<ElFormInstance>();
  const planFormRef = ref<ElFormInstance>();

  const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });

  // 文件上传相关状态
  const fileUploadDialog = reactive({
    visible: false,
    title: '上传文件'
  });
  const fileList = ref<UploadFile[]>([]);
  const viewFileList = ref([]);
  const uploadLoading = ref(false);
  const selectedPlanId = ref<string | number>('');

  // 初始化表单数据
  const initFormData: PlanForm & { dictName?: string; content?: string } = {
    id: '1958116259107012609',
    projectId: currentProjectId.value,
    file: [],
    plannedBiddingMethod: undefined,
    files: undefined,
    price: undefined,
    limitPrice: undefined,
    contractPrice: undefined,
    bidFile: undefined,
    dictName: '1',
    name: 'test1',
    content: 'trhbhbt'
  };

  // 页面数据
  const data = reactive<PageData<typeof initFormData, PlanQuery & { dictName?: string; content?: string }>>({
    form: { ...initFormData },
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      projectId: currentProjectId.value,
      dictName: undefined,
      name: undefined,
      plannedBiddingTime: undefined,
      plannedBiddingMethod: undefined,
      price: undefined,
      limitPrice: undefined,
      contractPrice: undefined,
      content: undefined,
      bidFile: undefined,
      params: {}
    },
    rules: {
      projectId: [{ required: true, message: '请输入项目ID', trigger: 'blur' }],
      name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      plannedBiddingMethod: [{ required: true, message: '请选择或输入限价生成招标方式', trigger: 'blur' }],
      limitPrice: [{ required: true, message: '请输入限价', trigger: 'blur' }],
      contractPrice: [{ required: true, message: '请输入合同额', trigger: 'blur' }],
      content: [{ required: true, message: '请输入分包内容', trigger: 'blur' }]
    }
  });

  const { queryParams, form, rules } = toRefs(data);

  // 监听当前项目ID变化
  watch(currentProjectId, (newVal) => {
    queryParams.value.projectId = newVal;
    if (!form.value.id) {
      form.value.projectId = newVal;
    }
    getList();
  });

  /** 查询招标计划列表 */
  const getList = async () => {
    loading.value = true;
    try {
      const res = await listPlan(queryParams.value);
      planList.value = res.rows || [];
      total.value = res.total || 0;
    } catch (error) {
      console.error('获取招标计划列表失败', error);
      proxy?.$modal.msgError('获取招标计划列表失败');
=======
import { getDicts } from '@/api/system/dict/data';
import { Plus } from '@element-plus/icons-vue';
import { FormInstance } from 'element-plus';
import {
  sheetList,
  tenderPlanList,
  addTenderPlan,
  delTenderPlan,
  updateTenderPlan,
  treeList,
  getTenderPlanDetail,
  obtainAllVersionNumbers
} from '@/api/tender/index';

const userStore = useUserStoreHook();
const currentProject = computed(() => userStore.selectedProject);
const tabList = ref<any[]>([]);
const tableData = ref<any[]>([]);
const queryFormRef = ref();
const formRef = ref();
const activeTab = ref();
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
});
const total = ref(0);
const queryForm = ref({
  name: '',
  content: ''
});
const dialogVisible = ref(false);
const form = ref({
  name: '',
  content: ''
});

const rules = ref({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
});
const loading = ref(false);
const planType = computed(() => {
  return activeTab.value == '2' ? '3' : '2';
});

//字典获取数据
const getTabsList = async () => {
  const res = await getDicts('subcontracting_type');
  if (res.code == 200) {
    activeTab.value = res.data[0].dictValue;
    tabList.value = res.data.map((item: any) => {
      return {
        label: item.dictLabel,
        value: item.dictValue
      };
    });
    getList();
  }
};
//获取表格数据
const getList = async () => {
  try {
    loading.value = true;
    const params = {
      projectId: currentProject.value?.id,
      ...queryParams.value,
      ...queryForm.value,
      dictName: activeTab.value,
      type: planType.value
    };
    const res = await tenderPlanList(params);
    if (res.code == 200) {
      tableData.value = res.rows;
      total.value = res.total;
    }
  } catch (error) {
    console.log(error);
    ElMessage({
      message: '获取数据失败',
      type: 'error'
    });
>>>>>>> aab67593ebb8d9116738d0d867a6119ba61615c8
    } finally {
      loading.value = false;
    }
  };
<<<<<<< HEAD

  // const handleSuccess = (list, res, fileType) => {
  //   console.log(list);
  //   const arr = list.map((item) => {
  //     return { fileId: item.ossId, fileUrl: item.url, fileType };
  //   });
  //   console.log(arr);
  //   if (!form.value.file) form.value.file = [];
  //   form.value.file = [...form.value.file, ...arr];
  //   console.log(form.value.file);
  // };

  const handleView = async (row, type) => {
    const res = await listByIds(row[type]);
    if (type == 'tenderFile') {
      viewVisible.value = true;
      viewFileList.value = res.data;
    } else {
      window.open(res.data[0].url);
    }
  };

  /** 取消按钮 */
  const cancel = () => {
    reset();
    dialog.visible = false;
  };

  /** 表单重置 */
  const reset = () => {
    form.value = { ...initFormData, projectId: currentProjectId.value };
    planFormRef.value?.resetFields();
  };

=======
const handleTabChange = (tabs: any) => {
  activeTab.value = tabs;
  getList();
};
>>>>>>> aab67593ebb8d9116738d0d867a6119ba61615c8
  /** 搜索按钮操作 */
  const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getList();
  };

  /** 重置按钮操作 */
  const resetQuery = () => {
<<<<<<< HEAD
    queryFormRef.value?.resetFields();
    queryParams.value.projectId = currentProjectId.value;
    handleQuery();
  };

  /** 多选框选中数据 */
  const handleSelectionChange = (selection: PlanVO[]) => {
    ids.value = selection.map((item) => item.id);
    single.value = selection.length !== 1;
    multiple.value = !selection.length;
  };

  /** 修改按钮操作 */
  const handleUpdate = async (row?: PlanVO) => {
    reset();
    const _id = row?.id || ids.value[0];
    if (!_id) {
      proxy?.$modal.msgWarning('请选择需要修改的招标计划');
      return;
    }
    try {
      // const res = await getPlan(_id);
      const res = await getSegmentedIndicatorPlanning(_id);

      Object.assign(form.value, res.data, {
        id: res.data.id || initFormData.id,
        dictName: res.data.dictName || initFormData.dictName,
        content: res.data.content || initFormData.content,
        projectId: res.data.projectId || currentProjectId.value
      });
      console.log(form.value);

      // 回显时根据限价同步招标方式（避免数据不一致）
      autoSetBiddingMethod();
      dialog.visible = true;
      dialog.title = '修改招标计划';
    } catch (error) {
      console.error('获取招标计划详情失败', error);
      proxy?.$modal.msgError('获取招标计划详情失败');
    }
  };

  /** 核心：根据限价自动设置招标方式 */
  const autoSetBiddingMethod = () => {
    const limit = form.value.limitPrice;
    // 逻辑：限价>1000万→公招，否则→邀标，为空则清空
    form.value.plannedBiddingMethod = limit ? (limit > 1000 ? '公招' : '邀标') : '';
  };

  /** 提交按钮 */
  const submitForm = () => {
    planFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        try {
          if (!form.value.id && currentProjectId.value) {
            form.value.projectId = currentProjectId.value;
          }
          if (form.value.id) {
            await updatePlan(form.value);
          } else {
            await addPlan(form.value);
          }
          proxy?.$modal.msgSuccess('操作成功');
          dialog.visible = false;
          await getList();
        } catch (error) {
          console.error('操作失败', error);
          proxy?.$modal.msgError('操作失败，请重试');
        } finally {
          buttonLoading.value = false;
        }
=======
  queryForm.value.content = '';
  queryForm.value.name = '';
  handleQuery();
};

const openDialog = () => {
  dialogVisible.value = true;
  getVersionNums();
};
const closeDialog = () => {
  dialogVisible.value = false;
  form.value = {
    name: '',
    content: ''
  };
  formRef.value?.resetFields();
};
const treeData = ref<any[]>([]);
const treeForm = ref({
  sheet: '',
  versions: ''
});
const sheets = ref<any[]>([]);
const treeTableRef = ref();
const isExpandAll = ref(false);
const treeLoading = ref(false);
const selectionData = ref<any>([]);
const options = ref([]);
//切换版本
const changeVersions = () => {
  getSheetName();
};
//获取版本号
const getVersionNums = async () => {
  try {
    const params = {
      projectId: currentProject.value?.id,
      workOrderType: planType.value,
      pageSize: 1000,
      pageNum: 1
    };

    const res = await obtainAllVersionNumbers(params);
    if (res.code == 200) {
      options.value = res.data;
      if (res.data.length > 0) {
        treeForm.value.versions = res.data[0].versions;
        getSheetName();
      } else {
        treeForm.value.versions = '';
        getSheetName();
      }
    }
  } catch (error) {
    console.log(error);
  }
};
//获取表名
const getSheetName = async () => {
  try {
    const params = {
      projectId: currentProject.value?.id,
      versions: treeForm.value.versions
    };
    const res = await sheetList(params);
    if (res.code == 200) {
      sheets.value = res.data;
      if (res.data.length > 0) {
        treeForm.value.sheet = res.data[0];
      } else {
        treeForm.value.sheet = '';
        ElMessage({
          message: '获取表名失败',
          type: 'warning'
        });
      }
      getTreeList();
    }
  } catch (error) {
    console.log(error);
    ElMessage({
      message: '获取表名失败',
      type: 'warning'
    });
  }
};
const handleSelection = (selection: any) => {
  selectionData.value = selection;
};
const handleNumberChange = (row: any) => {
  const selectedIds = selectionData.value.map((item) => item.id);
  nextTick(() => {
    treeTableRef.value.toggleRowSelection(row, true);
  });
  restoreSelections(treeData.value, selectedIds);
};

//寻找节点选择
const restoreSelections = (data, selectedIds) => {
  const traverse = (nodes) => {
    nodes.forEach((node) => {
      if (selectedIds.includes(node.id)) {
        nextTick(() => {
          treeTableRef.value.toggleRowSelection(node, true);
        });
      }
      if (node.children && node.children.length > 0) {
        traverse(node.children);
      }
    });
  };
  traverse(data);
};
watch(
  () => selectionData.value,
  (newVal, oldVal) => {
    console.log(newVal, 55555555555555555);
  }
);

//选择表名
const changeSheet = () => {
  getTreeList();
};

const toggleExpandAll = (isExpand: boolean) => {
  treeData.value.forEach((row) => {
    treeTableRef.value.toggleRowExpansion(row, isExpand);
  });
  isExpandAll.value = isExpand;
};
//打开获取表数据
const getTreeList = async () => {
  try {
    treeLoading.value = true;
    const params = {
      projectId: currentProject.value?.id,
      sheet: treeForm.value.sheet,
      versions: treeForm.value.versions,
      type: planType.value
    };
    const res = await treeList(params);
    if (res.code == 200) {
      res.data.forEach((item: any) => {
        item.selectNum = '';
      });
      treeData.value = res.data;
    }
  } catch (error) {
    console.log(error);
    ElMessage({
      message: '获取表格失败',
      type: 'error'
    });
  } finally {
    treeLoading.value = false;
  }
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        if (selectionData.value.length == 0) {
          ElMessage({
            message: '请选择项目材料',
            type: 'warning'
          });
          return;
        }
        const newSelectionData = selectionData.value.filter((item) => item.quantity != '' && item.quantity != null);
        if (newSelectionData.some((item) => item.selectNum == '' || item.selectNum == null)) {
          ElMessage.error('存在未填写数量的工程或费用名称，请检查');
          return;
        }
        const limitListBos = newSelectionData.map((item: any) => {
          return {
            limitListId: item.id,
            num: item.selectNum
          };
        });
        const params = {
          projectId: currentProject.value?.id,
          ...form.value,
          dictName: activeTab.value,
          limitListBos,
          type: planType.value
        };

        const res = await addTenderPlan(params);
        if (res.code == 200) {
          ElMessage({
            message: '新增成功',
            type: 'success'
          });
          closeDialog();
          getList();
        }
      } catch (error) {
        console.log(error);
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};
//确定修改
const handleSave = (row: any) => {
  try {
    if (!row.plannedBiddingTime) {
      ElMessage({
        message: '请输入计划招标时间',
        type: 'warning'
      });
      return;
    }
    updateTenderPlan({ ...row, type: planType.value }).then((res) => {
      if (res.code == 200) {
        ElMessage({
          message: '修改成功',
          type: 'success'
        });
        getList();
      }
    });
  } catch (error) {
    console.log(error);
    ElMessage({
      message: '修改失败',
      type: 'error'
    });
  }
};
//删除
const delHandle = (row: any) => {
  try {
    const params = { ids: row.id };
    delTenderPlan(params).then((res) => {
      if (res.code == 200) {
        ElMessage({
          message: '删除成功',
          type: 'success'
        });
        getList();
      }
    });
  } catch (error) {
    console.log(error);
    ElMessage({
      message: '删除失败',
      type: 'error'
    });
  }
};
const detailDialog = ref();
const detailData = ref([]);
const detailLoading = ref(false);

//详情
const handleDetail = (row: any) => {
  detailDialog.value = true;
  getDetails(row);
};
const getDetails = (row: any) => {
  getTenderPlanDetail({ id: row.id }).then((res) => {
    if (res.code == 200) {
      detailData.value = res.data;
>>>>>>> aab67593ebb8d9116738d0d867a6119ba61615c8
      }
    });
  };

<<<<<<< HEAD
  /** 删除按钮操作（原代码存在但模板未引用，保留逻辑） */
  const handleDelete = async (row?: PlanVO) => {
    const _ids = row?.id || ids.value;
    if (!_ids || (_ids instanceof Array && _ids.length === 0)) {
      proxy?.$modal.msgWarning('请选择需要删除的招标计划');
      return;
    }
    try {
      await proxy?.$modal.confirm('是否确认删除选中的招标计划？');
      await delPlan(_ids);
      proxy?.$modal.msgSuccess('删除成功');
      await getList();
    } catch (error) {
      console.error('删除失败', error);
      if (error !== 'cancel') {
        proxy?.$modal.msgError('删除失败，请重试');
      }
    }
  };

  /** 导出按钮操作 */
  const handleExport = () => {
    proxy?.download(
      'plan/plan/export',
      {
        ...queryParams.value
      },
      `plan_${new Date().getTime()}.xlsx`
    );
  };

  /** 打开文件上传对话框 */
  const openFileUploadDialog = () => {
    if (ids.value.length !== 1) {
      proxy?.$modal.msgWarning('请选择单个招标计划进行文件上传');
      return;
    }
    selectedPlanId.value = ids.value[0];
    fileList.value = [];
    fileUploadDialog.visible = true;
  };

  /** 处理文件上传 */
  const handleFileUpload = async (params: { file: UploadRawFile }) => {
    const formData = new FormData();
    formData.append('file', params.file);
    formData.append('planId', selectedPlanId.value as string);

    try {
      const response = await uploadFile(formData);
      return response;
    } catch (error) {
      console.error('文件上传失败', error);
      throw error;
    }
  };

  /** 提交文件上传 */
  const submitFileUpload = async () => {
    if (fileList.value.length === 0) {
      proxy?.$modal.msgWarning('请选择需要上传的文件');
      return;
    }

    uploadLoading.value = true;
    try {
      for (const file of fileList.value) {
        if (file.raw) {
          await handleFileUpload({ file: file.raw });
        }
      }

      proxy?.$modal.msgSuccess('文件上传成功');
      fileUploadDialog.visible = false;
    } catch (error) {
      proxy?.$modal.msgError('文件上传失败');
    } finally {
      uploadLoading.value = false;
    }
  };

  /** 取消文件上传 */
  const cancelFileUpload = () => {
    fileList.value = [];
    fileUploadDialog.visible = false;
  };

  /** 文件预览 */
  const handleFilePreview = (file: UploadFile) => {
    console.log('预览文件:', file);
    // 可扩展：通过文件URL打开预览
    // if (file.url) window.open(file.url);
  };

  /** 移除文件 */
  const handleFileRemove = (file: UploadFile) => {
    console.log('移除文件:', file);
  };

  // 监听项目id刷新数据
  const listeningProject = watch(
    () => currentProject.value?.id,
    (nid, oid) => {
      queryParams.value.projectId = nid;
      form.value.projectId = nid;
      getList();
    }
  );

  onUnmounted(() => {
    listeningProject();
  });
</script>

  <style scoped lang="scss">
  <<<<<<< HEAD .mb-4 {
    margin-bottom: 16px;
  }

  .el-table .small-padding .cell {
    padding: 0 5px;
  }

  .el-table .fixed-width {
    width: 120px !important;
  }

  .el-table-column .el-button--text+.el-button--text {
    margin-left: 10px;
  }

  .upload-container {
    padding: 10px 0;

    =======.Region {
      width: 100%;
      height: 100%;
      border: 1px solid #ccc;
      border-radius: 10px;
      padding: 10px;
      >>>>>>>aab67593ebb8d9116738d0d867a6119ba61615c8
    }
  </style>