<template>
  <div class="p-2">
    <el-card shadow="never">
      <!-- 审批按钮组件 -->
      <approvalButton
        @submitForm="submitForm"
        @approvalVerifyOpen="approvalVerifyOpen"
        @handleApprovalRecord="handleApprovalRecord"
        :buttonLoading="buttonLoading"
        :id="projectReportForm.reportDetailId"
        :status="projectReportForm.flowStatus"
        :pageType="modifiedPageType"
        :mode="false"
      />
    </el-card>
    <el-alert
      v-if="showAddDetailFromMasterBanner"
      type="info"
      :closable="false"
      show-icon
      class="mb-2"
      title="正在为所选项目周报新增一条明细：上方为项目信息（只读），请在下方填写本周报明细。"
    />
    <el-card shadow="never">
      <el-form ref="projectFormRef" :model="form" :disabled="true" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请点击右侧图标选择项目">
                <template #suffix>
                  <el-icon
                    style="cursor: pointer; margin-right: 4px; font-size: 14px"
                    @click="openProjectSelect"
                    v-if="showProjectSearchSuffix"
                  >
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目编号" prop="projectCode">
              <el-input v-model="form.projectCode" placeholder="请输入项目编号" :disabled="projectCodeLockedInAddFromList" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="里程碑计划" prop="milestonePlan">
              <el-input v-model="form.milestonePlan" placeholder="请输入里程碑计划" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目经理" prop="managerName">
              <el-input
                v-model="form.managerName"
                placeholder="请输入项目经理"
                :disabled="routeParams.type === 'add' || routeParams.type === 'update'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="deptName">
              <el-input v-model="form.deptName" placeholder="请输入部门" :disabled="routeParams.type === 'add' || routeParams.type === 'update'" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门负责人" prop="chargeName">
              <el-input
                v-model="form.chargeName"
                placeholder="请输入部门负责人"
                :disabled="routeParams.type === 'add' || routeParams.type === 'update'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分管副总" prop="deputyName">
              <el-input
                v-model="form.deputyName"
                placeholder="请输入分管副总"
                :disabled="routeParams.type === 'add' || routeParams.type === 'update'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="周报情况说明" prop="informationNote">
              <el-input v-model="form.informationNote" type="textarea" placeholder="请说明情况" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="项目ID" prop="projectId">
              <el-input v-model="form.projectId" placeholder="请点击右侧图标选择项目" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="项目经理ID" prop="managerId">
              <el-input v-model="form.managerId" placeholder="请点击右侧图标选择项目" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="部门ID" prop="deptId">
              <el-input v-model="form.deptId" placeholder="请点击右侧图标选择项目" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="部门负责人ID" prop="chargeId">
              <el-input v-model="form.chargeId" placeholder="请点击右侧图标选择项目" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="分管副总ID" prop="deputyId">
              <el-input v-model="form.deputyId" placeholder="请点击右侧图标选择项目" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="附件ID" prop="ossId">
              <el-input v-model="form.ossId" placeholder="请点击右侧图标选择项目" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="排序号" prop="sortOrder">
              <el-input v-model="form.sortOrder" placeholder="请点击右侧图标选择项目" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="激活标识" prop="activeFlag">
              <el-input v-model="form.activeFlag" placeholder="请点击右侧图标选择项目" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="周报说明" prop="informationNote">
              <el-input v-model="form.informationNote" placeholder="请点击右侧图标选择项目" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <ProjectSelect ref="projectSelectRef" :multiple="false" @confirm-call-back="projectInfoSelectCallBack"></ProjectSelect>

    <!-- 项目周报具体信息管理区域 -->
    <el-card shadow="hover" style="margin-top: 20px">
      <div style="text-align: left; font-weight: bold; font-size: 18px">项目周报具体信息</div>
    </el-card>

    <el-card shadow="never">
      <template #header v-if="isMasterWeeklyListView">
        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['oa/erp:projectReportDetail:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete()"
              v-hasPermi="['oa/erp:projectReportDetail:remove']"
              >删除</el-button
            >
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:projectReportDetail:export']">导出</el-button>
          </el-col>
          <right-toolbar :search="false" :columns="columns" @queryTable="getProjectDetail"></right-toolbar>
        </el-row>
      </template>
      <el-table
        v-loading="loading"
        border
        :data="projectReportDetailList"
        v-if="isMasterWeeklyListView"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="项目周报明细ID" align="center" prop="reportDetailId" width="100" v-if="columns[0].visible" />
        <el-table-column label="项目周报ID" align="center" prop="reportId" width="100" v-if="columns[1].visible" />
        <el-table-column label="项目ID" align="center" prop="projectId" width="100" v-if="columns[2].visible" />
        <el-table-column label="填写日期" align="center" prop="fillTime" width="180" v-if="columns[3].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.fillTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="beginDate" width="180" v-if="columns[23].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.beginDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结束时间" align="center" prop="endDate" width="180" v-if="columns[24].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="所在的工作周" align="center" prop="currentWorkWeek" width="100" v-if="columns[4].visible" />
        <el-table-column label="所属里程碑" align="center" prop="milestonePlan" width="100" v-if="columns[5].visible" />
        <el-table-column label="二级进度阶段" align="center" prop="secondaryPhase" width="100" v-if="columns[6].visible" />
        <el-table-column label="本周完成工作" align="center" prop="tasksCompleted" width="150" v-if="columns[7].visible" />
        <el-table-column label="下周计划" align="center" prop="nextPlan" width="100" v-if="columns[8].visible" />
        <el-table-column label="风险及解决措施" align="center" prop="riskResolution" width="150" v-if="columns[9].visible" />
        <el-table-column label="项目状态" align="center" prop="scheduleStatus" width="100" v-if="columns[12].visible">
          <template #default="scope">
            <dict-tag :options="project_risk_status" :value="scope.row.scheduleStatus" />
          </template>
        </el-table-column>
        <el-table-column label="计划完成率" align="center" prop="plannedCompletionRate" width="100" v-if="columns[10].visible" />
        <el-table-column label="周报情况说明" align="center" prop="informationNote" width="150" v-if="columns[11].visible" />
        <el-table-column label="周报状态" align="center" prop="projectReportStatus" width="100" v-if="columns[13].visible">
          <template #default="scope">
            <dict-tag :options="project_report_status" :value="scope.row.projectReportStatus" />
          </template>
        </el-table-column>
        <el-table-column label="流程状态" align="center" prop="flowStatus" width="100" v-if="columns[14].visible" />
        <el-table-column label="排序号" align="center" prop="sortOrder" width="100" v-if="columns[15].visible" />
        <el-table-column label="项目阶段" align="center" prop="projectPhases" width="100" v-if="columns[16].visible" />
        <el-table-column label="合同ID" align="center" prop="contractId" width="100" v-if="columns[17].visible" />
        <el-table-column label="附件ID" align="center" prop="ossId" width="100" v-if="columns[18].visible">
          <template #default="scope">
            <el-button v-if="scope.row.ossId" link type="primary" icon="Download" @click="downloadOss(scope.row.ossId)">下载 </el-button>
            <span v-else style="color: #999">未上传</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" width="150" v-if="columns[19].visible" />
        <el-table-column label="激活标识" align="center" prop="activeFlag" width="100" v-if="columns[20].visible" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="100" v-if="columns[21].visible" />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="100" v-if="columns[22].visible" />
        <el-table-column label="操作" align="center" fixed="right" width="150">
          <template #default="scope">
            <el-tooltip content="审批记录" placement="top">
              <el-button link type="info" icon="View" @click="handleApprovalRecord(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0 && isMasterWeeklyListView"
        :total="total"
        v-model:page="projectReportFormQuery.pageNum"
        v-model:limit="projectReportFormQuery.pageSize"
        @pagination="getProjectDetail"
      />
      <el-form
        ref="projectReportDetailFormRef"
        :model="projectReportForm"
        :disabled="isDetailFormDisabled"
        :rules="reportRules"
        label-width="120px"
        v-if="showDetailEditorForm"
      >
        <el-row :gutter="20">
          <el-col :span="12" v-show="false">
            <el-form-item label="项目周报ID" prop="reportId">
              <el-input v-model="projectReportForm.reportId" placeholder="请输入项目周报ID" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="项目ID" prop="projectId">
              <el-input v-model="projectReportForm.projectId" placeholder="请输入项目ID" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="填写日期" prop="fillTime">
              <el-date-picker
                clearable
                v-model="projectReportForm.fillTime"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择填写日期"
                :disabled="true"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="所在的工作周" prop="currentWorkWeek">
              <el-input v-model="projectReportForm.currentWorkWeek" placeholder="请输入所在的工作周" clearable />
            </el-form-item>
          </el-col> -->
          <el-form-item label="起始时间">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            ></el-date-picker>
          </el-form-item>
          <el-col :span="12">
            <el-form-item label="所属里程碑" prop="milestonePlan">
              <el-input v-model="projectReportForm.milestonePlan" placeholder="请输入所属里程碑" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二级进度阶段" prop="secondaryPhase">
              <el-input v-model="projectReportForm.secondaryPhase" placeholder="请输入二级进度阶段" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目状态" prop="scheduleStatus">
              <el-select v-model="projectReportForm.scheduleStatus" placeholder="请选择项目状态" clearable>
                <el-option v-for="dict in project_risk_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划完成率" prop="plannedCompletionRate">
              <el-input
                v-model="projectReportForm.plannedCompletionRate"
                placeholder="请输入0-1之间的数字"
                clearable
                type="number"
                :min="0"
                :max="1"
                :step="0.01"
                @input="validatePlannedCompletionRate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本周完成工作" prop="tasksCompleted">
              <el-input v-model="projectReportForm.tasksCompleted" type="textarea" placeholder="请输入本周完成工作" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下周计划" prop="nextPlan">
              <el-input v-model="projectReportForm.nextPlan" type="textarea" placeholder="请输入下周计划" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="风险及解决措施" prop="riskResolution">
              <el-input v-model="projectReportForm.riskResolution" type="textarea" placeholder="请输入风险及解决措施" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="周报情况说明" prop="informationNote">
              <el-input v-model="projectReportForm.informationNote" type="textarea" placeholder="请输入周报情况说明" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="排序号" prop="sortOrder">
              <el-input v-model="projectReportForm.sortOrder" placeholder="请输入排序号" clearable />
            </el-form-item>
          </el-col>
          <!-- 添加周报状态显示 -->
          <el-col :span="12">
            <el-form-item label="周报状态" prop="projectReportStatus" v-show="projectReportForm.flowStatus === 'waiting'">
              <el-select v-model="projectReportForm.projectReportStatus" placeholder="请选择周报状态" clearable :disabled="isDetailFormDisabled">
                <el-option v-for="dict in project_report_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="合同ID" prop="contractId">
              <el-input v-model="projectReportForm.contractId" placeholder="请输入合同ID" clearable />
            </el-form-item>
          </el-col>
          <!-- 项目周报明细表单文件上传 -->
          <el-col :span="12">
            <el-form-item label="周报附件" prop="ossId">
              <FileUpload
                v-model="projectReportOssIdString"
                :limit="5"
                :fileSize="20"
                :fileType="['doc', 'docx', 'pdf', 'xls', 'xlsx', 'jpg', 'jpeg', 'png']"
                :disabled="isFormDisabled"
                :isShowTip="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="false">
            <el-form-item label="激活标识" prop="activeFlag">
              <el-input v-model="projectReportForm.activeFlag" placeholder="请输入激活标识" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 修改项目周报明细对话框 -->
    <el-dialog :title="ReportDialog.title" v-model="ReportDialog.visible" width="800px" append-to-body>
      <el-form ref="projectReportDetailDialogFormRef" :model="detailForm" :rules="detailRules" label-width="120px">
        <el-row :gutter="10" class="form-row">
          <el-col :span="12">
            <el-form-item label="项目周报ID" prop="reportId">
              <el-input v-model="detailForm.reportId" placeholder="请输入项目周报ID" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目ID" prop="projectId">
              <el-input v-model="detailForm.projectId" placeholder="请输入项目ID" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="form-row">
          <!-- 修改对话框中的日期选择器 -->
          <el-col :span="12">
            <el-form-item label="填写日期" prop="fillTime">
              <el-date-picker
                clearable
                v-model="modifyDatePart"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="请选择填写日期"
                style="width: 100%"
                @change="handleModifyDateChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在的工作周" prop="currentWorkWeek">
              <el-input v-model="detailForm.currentWorkWeek" placeholder="请输入所在的工作周" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="form-row">
          <el-col :span="12">
            <el-form-item label="所属里程碑" prop="milestonePlan">
              <el-input v-model="detailForm.milestonePlan" placeholder="请输入所属里程碑" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二级进度阶段" prop="secondaryPhase">
              <el-input v-model="detailForm.secondaryPhase" placeholder="请输入二级进度阶段" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10" class="form-row">
          <el-col :span="24">
            <el-form-item label="本周完成工作" prop="tasksCompleted">
              <el-input v-model="detailForm.tasksCompleted" type="textarea" placeholder="请输入内容" :rows="4" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10" class="form-row">
          <el-col :span="24">
            <el-form-item label="下周计划" prop="nextPlan">
              <el-input v-model="detailForm.nextPlan" type="textarea" placeholder="请输入内容" :rows="4" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10" class="form-row">
          <el-col :span="24">
            <el-form-item label="风险及解决措施" prop="riskResolution">
              <el-input v-model="detailForm.riskResolution" type="textarea" placeholder="请输入内容" :rows="4" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="10" class="form-row">
          <el-col :span="12">
            <el-form-item label="计划完成率" prop="plannedCompletionRate">
              <el-input
                v-model="detailForm.plannedCompletionRate"
                placeholder="请输入0-1之间的数字"
                clearable
                type="number"
                :min="0"
                :max="1"
                :step="0.01"
                @input="validateModifyPlannedCompletionRate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目状态" prop="scheduleStatus">
              <el-select v-model="detailForm.scheduleStatus" placeholder="请选择项目状态">
                <el-option label="正常" value="1" />
                <el-option label="拖期风险" value="2" />
                <el-option label="已拖期" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="form-row">
          <el-col :span="12">
            <el-form-item label="周报状态" prop="projectReportStatus">
              <el-select v-model="detailForm.projectReportStatus" placeholder="请选择周报状态" :disabled="true">
                <el-option label="暂存" value="1" />
                <el-option label="审批中" value="2" />
                <el-option label="可用" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="流程状态" prop="flowStatus">
              <el-input v-model="detailForm.flowStatus" placeholder="流程状态" :disabled="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="form-row">
          <el-col :span="12">
            <el-form-item label="项目阶段" prop="projectPhases">
              <el-input v-model="detailForm.projectPhases" placeholder="请输入项目阶段(预留)" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同ID" prop="contractId">
              <el-input v-model="detailForm.contractId" placeholder="请输入合同ID(预留)" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="form-row">
          <el-col :span="12">
            <el-form-item label="排序号" prop="sortOrder">
              <el-input v-model="detailForm.sortOrder" placeholder="请输入排序号" />
            </el-form-item>
          </el-col>
          <!-- 修改对话框中的文件上传 -->
          <el-col :span="12">
            <el-form-item label="附件" prop="ossId">
              <FileUpload
                v-model="detailFormOssIdString"
                :limit="5"
                :fileSize="20"
                :fileType="['doc', 'docx', 'pdf', 'xls', 'xlsx', 'jpg', 'jpeg', 'png']"
                :disabled="false"
                :isShowTip="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="form-row">
          <el-col :span="24">
            <el-form-item label="周报情况说明" prop="informationNote">
              <el-input v-model="detailForm.informationNote" type="textarea" placeholder="请输入内容" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="form-row">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="detailForm.remark" type="textarea" placeholder="请输入备注" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 隐藏字段 -->
        <el-row :gutter="10" class="form-row" v-show="false">
          <el-col :span="12">
            <el-form-item label="激活标识" prop="activeFlag">
              <el-input v-model="detailForm.activeFlag" placeholder="请输入激活标识" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitProjectReportForm">确 定</el-button>
          <el-button @click="cancelProjectReportForm">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 提交审批组件 -->
    <submitVerify ref="submitVerifyRef" :task-variables="taskVariables" @submit-callback="submitCallback" />
    <!-- 审批记录 -->
    <approvalRecord ref="approvalRecordRef" />
  </div>
</template>

<script setup name="ProjectReportEdit" lang="ts">
import { getRuleGenerateCode } from '@/api/system/codeRule';
import { StartProcessBo } from '@/api/workflow/workflowCommon/types';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import { ref } from 'vue';
import { CodeRuleEnum, FlowCodeEnum } from '@/enums/OAEnum';
import { ProjectReportVO, ProjectReportQuery, ProjectReportForm } from '@/api/oa/erp/projectReport/types';
import { listProjectReport, getProjectReport, getErpProjectReportList, addProjectReport, updateProjectReport } from '@/api/oa/erp/projectReport';
import {
  listProjectReportDetail,
  getProjectReportDetail,
  delProjectReportDetail,
  addProjectReportDetail,
  updateProjectReportDetail,
  projectReportSubmitAndFlowStart
} from '@/api/oa/erp/projectReportDetail/index';
import {
  ProjectReportDetailVO,
  ProjectReportDetailQuery,
  ProjectReportDetailForm,
  ProjectReportDetailFormEx
} from '@/api/oa/erp/projectReportDetail/types';
import ProjectSelect from '@/components/ProjectSelect/index.vue';
import FileUpload from '@/components/FileUpload/index.vue';
import download from '@/plugins/download';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const modifiedPageType = computed(() => {
  // 在新增状态下且存在审批中记录时，将 pageType 改为 'view' 来隐藏提交按钮
  if (routeParams.value.type === 'add' && projectReportForm.value.flowStatus === 'waiting') {
    return 'view'; // 这样 submitButtonShow 会返回 false
  }

  return routeParams.value.type;
});

// 路由参数
const routeParams = ref<Record<string, any>>({});

/** 列表「查看」：按周报主表查看多条明细（reportId 或旧 reportData） */
const isMasterWeeklyListView = computed(() => {
  if (routeParams.value.type !== 'view') return false;
  if (routeParams.value.reportId != null && String(routeParams.value.reportId) !== '') return true;
  return !!routeParams.value.reportData;
});

/** 是否带有主表上下文（带 reportId / 旧 reportData；纯新增无） */
const hasMasterReportContextQuery = computed(() => {
  if (routeParams.value.reportId != null && String(routeParams.value.reportId) !== '') return true;
  return !!routeParams.value.reportData;
});

/** 底部明细编辑表单（主表多行查看时不展示） */
const showDetailEditorForm = computed(() => {
  const t = routeParams.value.type;
  if (t === 'add' || t === 'approval' || t === 'update') return true;
  if (t === 'view' && !isMasterWeeklyListView.value) return true;
  return false;
});

const showProjectSearchSuffix = computed(() => routeParams.value.type === 'add' && !hasMasterReportContextQuery.value);

const projectCodeLockedInAddFromList = computed(
  () => routeParams.value.type === 'add' && hasMasterReportContextQuery.value
);

/** 从列表「在已有周报下新增明细」进入（显式 addMode，避免与纯新增混淆） */
const showAddDetailFromMasterBanner = computed(
  () => routeParams.value.type === 'add' && routeParams.value.addMode === 'detail'
);
//字典
const { project_report_status, project_risk_status } = toRefs<any>(proxy?.useDict('project_report_status', 'project_risk_status'));

//按钮加载控制
const buttonLoading = ref(false);

// 审批相关组件引用
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();

// 流程相关数据
const submitFormData = ref<StartProcessBo>({
  businessId: '',
  flowCode: 'XMZB',
  variables: {},
  bizExt: {}
});

// 任务变量
const taskVariables = ref<Record<string, any>>({});
const flowInstanceBizExtBo = ref<Record<string, any>>({});

const total = ref(0);
const loading = ref(false);

// 判断表单是否禁用
const isFormDisabled = computed(() => {
  return routeParams.value.type === 'view' || routeParams.value.type === 'approval';
});

// 项目周报明细表单附件ID字符串转换
const projectReportOssIdString = computed({
  get() {
    const v = projectReportForm.value.ossId as any;
    return v === undefined || v === null ? '' : String(v);
  },
  set(val: string) {
    projectReportForm.value.ossId = val || (undefined as any);
    form.value.ossId = val || (undefined as any);
  }
});
// 下载附件
const downloadOss = (ossId: string | number) => {
  download.oss(ossId);
};
// 修改对话框明细表单附件ID字符串转换
const detailFormOssIdString = computed({
  get() {
    const v = detailForm.value.ossId as any;
    return v === undefined || v === null ? '' : String(v);
  },
  set(val: string) {
    detailForm.value.ossId = val || (undefined as any);
    form.value.ossId = val || (undefined as any);
  }
});

// 项目周报上半部分
// 项目周报上半部分表单引用
const projectFormRef = ref<ElFormInstance>();
const initFormData: ProjectReportForm = {
  reportId: undefined,
  projectId: undefined,
  projectName: undefined,
  projectCode: undefined,
  milestonePlan: undefined,
  managerId: undefined,
  deptId: undefined,
  chargeId: undefined,
  deputyId: undefined,
  informationNote: undefined,
  sortOrder: undefined,
  ossId: undefined,
  remark: undefined,
  activeFlag: undefined,
  deptName: undefined,
  managerName: undefined,
  chargeName: undefined,
  deputyName: undefined,
  status: undefined
};
const data = reactive<PageData<ProjectReportForm, ProjectReportQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    reportId: undefined,
    projectId: undefined,
    projectName: undefined,
    projectCode: undefined,
    milestonePlan: undefined,
    managerId: undefined,
    deptId: undefined,
    chargeId: undefined,
    deputyId: undefined,
    informationNote: undefined,
    sortOrder: undefined,
    ossId: undefined,
    activeFlag: undefined,
    deptName: undefined,
    managerName: undefined,
    chargeName: undefined,
    deputyName: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
    projectCode: [{ required: true, message: '项目编号不能为空', trigger: 'blur' }],
    deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
    managerName: [{ required: true, message: '项目经理不能为空', trigger: 'blur' }],
    chargeName: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }],
    deputyName: [{ required: true, message: '分管副总不能为空', trigger: 'blur' }]
  }
});
const { form, queryParams, rules } = toRefs(data);

// 新增模式下项目周报明细表单引用
const projectReportDetailFormRef = ref<ElFormInstance>();
// 新增模式下项目周报明细表单数据
const initProjectReportFormData: ProjectReportDetailFormEx = {
  reportDetailId: undefined,
  reportId: undefined,
  projectId: undefined,
  fillTime: undefined,
  currentWorkWeek: undefined,
  milestonePlan: undefined,
  secondaryPhase: undefined,
  tasksCompleted: undefined,
  nextPlan: undefined,
  riskResolution: undefined,
  plannedCompletionRate: undefined,
  informationNote: undefined,
  scheduleStatus: undefined,
  projectReportStatus: undefined,
  flowStatus: undefined,
  sortOrder: undefined,
  projectPhases: undefined,
  contractId: undefined,
  ossId: undefined,
  remark: undefined,
  activeFlag: undefined,
  flowCode: undefined,
  bizExt: undefined,
  variables: undefined,
  createTime: undefined,
  updateTime: undefined,
  beginDate: undefined,
  endDate: undefined
} as any;
const projectReportForm = ref<ProjectReportDetailFormEx>({ ...initProjectReportFormData });
// 新增模式下项目周报明细表单规则验证
const reportRules = {
  tasksCompleted: [{ required: true, message: '本周完成工作不能为空', trigger: 'blur' }],
  nextPlan: [{ required: true, message: '下周计划不能为空', trigger: 'blur' }],
  secondaryPhase: [{ required: true, message: '二级进度阶段不能为空', trigger: 'blur' }],
  plannedCompletionRate: [
    { required: false, message: '请填写计划完成率', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value === null || value === undefined || value === '') {
          callback();
          return;
        }
        // 转换为数字
        const numValue = Number(value);
        // 检查是否为数字
        if (isNaN(numValue)) {
          callback(new Error('请输入有效的数字'));
          return;
        }
        // 检查是否在0-1之间
        if (numValue < 0 || numValue > 1) {
          callback(new Error('请输入0-1之间的数字'));
          return;
        }
        // 检查小数位数（可选）
        const decimalPlaces = value.toString().split('.')[1];
        if (decimalPlaces && decimalPlaces.length > 2) {
          callback(new Error('最多支持两位小数'));
          return;
        }
        callback();
      },
      trigger: 'blur'
    }
  ]
};

// 对话框表单修改数据
// 对话框引用
const projectReportDetailDialogFormRef = ref<ElFormInstance>();
const initProjectReportDetailFormData: ProjectReportDetailForm = {
  reportDetailId: undefined,
  reportId: undefined,
  projectId: undefined,
  fillTime: undefined,
  currentWorkWeek: undefined,
  milestonePlan: undefined,
  secondaryPhase: undefined,
  tasksCompleted: undefined,
  nextPlan: undefined,
  riskResolution: undefined,
  plannedCompletionRate: undefined,
  informationNote: undefined,
  scheduleStatus: undefined,
  projectReportStatus: undefined,
  flowStatus: undefined,
  sortOrder: undefined,
  projectPhases: undefined,
  contractId: undefined,
  ossId: undefined,
  remark: undefined,
  activeFlag: undefined,
  beginDate: undefined,
  endDate: undefined
};
const projectReportDetailData = reactive<PageData<ProjectReportDetailForm, ProjectReportDetailQuery>>({
  form: { ...initProjectReportDetailFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    reportId: undefined,
    projectId: undefined,
    fillTime: undefined,
    currentWorkWeek: undefined,
    milestonePlan: undefined,
    secondaryPhase: undefined,
    tasksCompleted: undefined,
    nextPlan: undefined,
    riskResolution: undefined,
    plannedCompletionRate: undefined,
    informationNote: undefined,
    scheduleStatus: undefined,
    projectReportStatus: undefined,
    flowStatus: undefined,
    sortOrder: undefined,
    projectPhases: undefined,
    contractId: undefined,
    ossId: undefined,
    activeFlag: undefined,
    beginDate: undefined,
    endDate: undefined,
    params: {}
  },
  rules: {
    tasksCompleted: [{ required: true, message: '本周完成工作不能为空', trigger: 'blur' }],
    nextPlan: [{ required: true, message: '下周计划不能为空', trigger: 'blur' }],
    secondaryPhase: [{ required: true, message: '二级进度阶段不能为空', trigger: 'blur' }],
    // 在 detailRules 中添加计划完成率的验证规则
    plannedCompletionRate: [
      { required: false, message: '请填写计划完成率', trigger: 'blur' },
      {
        validator: (rule: any, value: any, callback: any) => {
          if (value === null || value === undefined || value === '') {
            callback();
            return;
          }
          // 转换为数字
          const numValue = Number(value);
          // 检查是否为数字
          if (isNaN(numValue)) {
            callback(new Error('请输入有效的数字'));
            return;
          }
          // 检查是否在0-1之间
          if (numValue < 0 || numValue > 1) {
            callback(new Error('请输入0-1之间的数字'));
            return;
          }
          // 检查小数位数（可选）
          const decimalPlaces = value.toString().split('.')[1];
          if (decimalPlaces && decimalPlaces.length > 2) {
            callback(new Error('最多支持两位小数'));
            return;
          }
          callback();
        },
        trigger: 'blur'
      }
    ]
  }
});
const { form: detailForm, queryParams: detailQueryParams, rules: detailRules } = toRefs(projectReportDetailData);

// 验证修改对话框中的计划完成率输入
const validateModifyPlannedCompletionRate = (value: string) => {
  if (!value) return;
  // 转换为数字
  const numValue = Number(value);
  // 如果输入无效或超出范围，重置为有效值
  if (isNaN(numValue)) {
    detailForm.value.plannedCompletionRate = 0;
    return;
  }
  // 限制在0-1之间
  if (numValue < 0) {
    detailForm.value.plannedCompletionRate = 0;
  } else if (numValue > 1) {
    detailForm.value.plannedCompletionRate = 1;
  } else {
    // 限制小数位数（可选）
    const decimalPlaces = value.split('.')[1];
    if (decimalPlaces && decimalPlaces.length > 2) {
      detailForm.value.plannedCompletionRate = parseFloat(numValue.toFixed(2));
    }
  }
};

// 根据项目名称选择项目组件引用
const projectSelectRef = ref<InstanceType<typeof ProjectSelect>>();
// 打开项目选择框
const openProjectSelect = () => {
  projectSelectRef.value.open();
};
//根据项目名称回调项目信息
const projectInfoSelectCallBack = async (data: any) => {
  if (data.length > 0) {
    proxy?.$modal.loading('正在导出数据，请稍后...');
    const res = await getErpProjectReportList({ projectId: data[0].projectId });
    // console.log(res.data);
    if (res.data.length > 0) {
      if (res.data[0].status === '0') {
        projectFormRef.value?.resetFields();
        projectReportDetailFormRef.value?.resetFields();
        proxy?.$modal.closeLoading();
        proxy?.$modal.notifyError('该项目周报记录已存在，请在项目周报信息界面维护！');
      } else {
        projectFormRef.value?.resetFields();
        projectReportDetailFormRef.value?.resetFields();
        proxy?.$modal.closeLoading();
        proxy?.$modal.notifyError('已存在暂存记录，请在项目周报信息界面维护！');
      }
    } else {
      proxy?.$modal.closeLoading();
      proxy?.$modal.msgSuccess('选择成功');
      Object.assign(form.value, data[0]);
    }
  } else {
    projectFormRef.value?.resetFields();
    projectReportDetailFormRef.value?.resetFields();
    proxy?.$modal.closeLoading();
    proxy?.$modal.msgWarning('请选择项目信息');
  }
};

const ReportDialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
// el-table绑定数据
const projectReportDetailList = ref<ProjectReportDetailVO[]>([]);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);

// el-table分页数据查询
const projectReportFormQuery = ref<ProjectReportDetailQuery>({
  pageNum: 1,
  pageSize: 10,
  reportId: undefined,
  projectId: undefined,
  fillTime: undefined,
  currentWorkWeek: undefined,
  milestonePlan: undefined,
  secondaryPhase: undefined,
  tasksCompleted: undefined,
  nextPlan: undefined,
  riskResolution: undefined,
  plannedCompletionRate: undefined,
  informationNote: undefined,
  scheduleStatus: undefined,
  projectReportStatus: undefined,
  flowStatus: undefined,
  sortOrder: undefined,
  projectPhases: undefined,
  contractId: undefined,
  ossId: undefined,
  activeFlag: undefined,
  params: {}
});

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProjectReportDetailVO[]) => {
  ids.value = selection.map((item) => item.reportDetailId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};
// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `项目周报明细ID`, visible: false },
  { key: 1, label: `项目周报ID`, visible: false },
  { key: 2, label: `项目ID`, visible: false },
  { key: 3, label: `填写日期`, visible: true },
  { key: 4, label: `所在的工作周`, visible: false },
  { key: 5, label: `所属里程碑`, visible: true },
  { key: 6, label: `二级进度阶段`, visible: true },
  { key: 7, label: `本周完成工作`, visible: true },
  { key: 8, label: `下周计划`, visible: true },
  { key: 9, label: `风险及解决措施`, visible: true },
  { key: 10, label: `计划完成率`, visible: true },
  { key: 11, label: `周报情况说明`, visible: true },
  { key: 12, label: `项目状态`, visible: true },
  { key: 13, label: `周报状态(1暂存 2审批中 3可用)`, visible: true },
  { key: 14, label: `流程状态`, visible: true },
  { key: 15, label: `排序号`, visible: false },
  { key: 16, label: `项目阶段(预留)`, visible: false },
  { key: 17, label: `合同ID(预留)`, visible: false },
  { key: 18, label: `附件ID`, visible: true },
  { key: 19, label: `备注`, visible: false },
  { key: 20, label: `激活标识`, visible: false },
  { key: 21, label: `创建时间`, visible: true },
  { key: 22, label: `更新时间`, visible: true },
  // { key: 21, label: `删除标志`, visible: true },
  // { key: 22, label: `创建部门`, visible: true },
  { key: 23, label: `开始时间`, visible: true },
  { key: 24, label: `结束时间`, visible: true }
  // { key: 25, label: `更新人`, visible: true },
  // { key: 26, label: `更新时间`, visible: true }
]);

// 验证计划完成率输入
const validatePlannedCompletionRate = (value: string) => {
  if (!value) return;
  // 转换为数字
  const numValue = Number(value);
  // 如果输入无效或超出范围，重置为有效值
  if (isNaN(numValue)) {
    projectReportForm.value.plannedCompletionRate = 0;
    return;
  }
  // 限制在0-1之间
  if (numValue < 0) {
    projectReportForm.value.plannedCompletionRate = 0;
  } else if (numValue > 1) {
    projectReportForm.value.plannedCompletionRate = 1;
  } else {
    // 限制小数位数（可选）
    const decimalPlaces = value.split('.')[1];
    if (decimalPlaces && decimalPlaces.length > 2) {
      projectReportForm.value.plannedCompletionRate = parseFloat(numValue.toFixed(2));
    }
  }
};
// 计算属性：格式化显示计划完成率
const formattedPlannedCompletionRate = computed(() => {
  if (projectReportForm.value.plannedCompletionRate === null || projectReportForm.value.plannedCompletionRate === undefined) {
    return '';
  }

  const value = Number(projectReportForm.value.plannedCompletionRate);
  if (isNaN(value)) return '';

  // 转换为百分比显示（保留2位小数）
  return `${(value * 100).toFixed(2)}%`;
});
/** 表单重置 */
const reset = () => {
  detailForm.value = { ...initProjectReportDetailFormData };
  modifyDatePart.value = ''; // 重置修改对话框的日期部分
  projectReportDetailDialogFormRef.value?.resetFields();
};
/** 修改按钮操作 */
const handleUpdate = async (row?: ProjectReportDetailVO) => {
  reset();
  const _reportDetailId = row?.reportDetailId || ids.value[0];
  const res = await getProjectReportDetail(_reportDetailId);
  Object.assign(detailForm.value, res.data);

  // 从 fillTime 中提取日期部分，用于日期选择器
  if (detailForm.value.fillTime) {
    const [date] = detailForm.value.fillTime.split(' ');
    if (date) {
      modifyDatePart.value = date;
      // 计算工作周
      detailForm.value.currentWorkWeek = getWorkWeek(date);
    }
  } else {
    // 如果没有日期，设置当前日期
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const dateStr = `${year}-${month}-${day}`;

    // 设置当前时间
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    const timeStr = `${hours}:${minutes}:${seconds}`;

    modifyDatePart.value = dateStr;
    detailForm.value.fillTime = `${dateStr} ${timeStr}`;
    detailForm.value.currentWorkWeek = getWorkWeek(dateStr);
  }

  ReportDialog.visible = true;
  ReportDialog.title = '修改项目周报明细';
};
/** 删除按钮操作 */
const handleDelete = async (row?: ProjectReportDetailVO) => {
  const _reportDetailIds = row?.reportDetailId || ids.value;
  await proxy?.$modal.confirm('是否确认删除项目周报明细编号为"' + _reportDetailIds + '"的数据项？').finally(() => (buttonLoading.value = false));
  await delProjectReportDetail(_reportDetailIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getProjectDetail();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'oa/erp/projectReportDetail/export',
    {
      reportId: form.value.reportId
    },
    `projectReportDetail_${new Date().getTime()}.xlsx`
  );
};
// 重置项目周报添加对话框
const resetProjectReportForm = () => {
  detailForm.value = { ...initProjectReportDetailFormData };
  projectReportDetailDialogFormRef.value?.resetFields();
};

// 取消项目周报添加对话框
const cancelProjectReportForm = () => {
  resetProjectReportForm();
  ReportDialog.visible = false;
};

/** 提交按钮 */
const submitProjectReportForm = () => {
  projectReportDetailDialogFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (detailForm.value.reportDetailId) {
        await updateProjectReportDetail(detailForm.value).finally(() => (buttonLoading.value = false));
      } else {
        await addProjectReportDetail(detailForm.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      ReportDialog.visible = false;
      await getProjectDetail();
    }
  });
};
// 审批记录
const handleApprovalRecord = (row?: ProjectReportDetailVO) => {
  if (row) {
    approvalRecordRef.value.init(row?.reportDetailId);
  } else {
    approvalRecordRef.value.init(projectReportForm.value.reportDetailId);
  }
};

// 提交回调
const submitCallback = async () => {
  await proxy.$tab.closePage(route);
  router.go(-1);
};

// 审批
const approvalVerifyOpen = async () => {
  await submitVerifyRef.value.openDialog(routeParams.value.taskId);
};

const isCodeGenerated = ref(false);

// 生成项目周报编号
const generateCode = async () => {
  if (isCodeGenerated.value) return; // 如果已经生成过，直接返回
  try {
    const params = { codeRuleCode: CodeRuleEnum.PROJECT_REPORT } as any;
    const res = await getRuleGenerateCode(params);
    isCodeGenerated.value = true; // 标记为已生成
    return res.msg;
  } catch (error) {
    console.error('生成业务编号失败:', error);
    proxy?.$modal.msgError('生成业务编号失败');
  }
};
// 查询项目周报明细
const getProjectDetail = async () => {
  loading.value = true;
  const res = await listProjectReportDetail({
    pageNum: projectReportFormQuery.value.pageNum,
    pageSize: projectReportFormQuery.value.pageSize,
    reportId: form.value.reportId
  });
  projectReportDetailList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

// 添加一个标志来表示是否存在审批中的数据
const hasApprovalData = ref(false);

// 判断明细表单是否禁用的计算属性（包含是否有审批中数据的判断）
const isDetailFormDisabled = computed(() => {
  return isFormDisabled.value || hasApprovalData.value;
});

// 新增/修改且带有主表上下文时，检查是否存在审批中的明细
const shouldCheckApprovalData = computed(() => {
  const t = routeParams.value.type;
  if (!(t === 'add' || t === 'update')) return false;
  return !!(routeParams.value.reportId || routeParams.value.reportData);
});

// 查询是否存在审批中的数据
const checkApprovalData = async () => {
  try {
    if (!shouldCheckApprovalData.value) return;

    let reportId: string | number | undefined = form.value.reportId ?? routeParams.value.reportId;
    const reportDataStr = routeParams.value.reportData as string | undefined;
    if (!reportId && reportDataStr) {
      const reportData = JSON.parse(decodeURIComponent(reportDataStr));
      reportId = reportData.reportId;
    }

    if (reportId) {
        // 查询是否存在审批中的数据（projectReportStatus = '2' 表示审批中）
        const res = await listProjectReportDetail({
          pageNum: 1,
          pageSize: 10,
          reportId: reportId,
          projectReportStatus: '2' // 审批中状态
        });

        if (res.rows && res.rows.length > 0) {
          hasApprovalData.value = true;
          // 填充第一条审批中的数据
          const approvalData = res.rows[0];
          Object.assign(projectReportForm.value, approvalData);

          // 确保 flowStatus 被正确设置为 'waiting'
          projectReportForm.value.flowStatus = 'waiting';
          // 设置日期范围
          if (approvalData.beginDate && approvalData.endDate) {
            dateRange.value = [approvalData.beginDate, approvalData.endDate];
          }
        } else {
          hasApprovalData.value = false;
        }
    }
  } catch (error) {
    console.error('检查审批数据失败:', error);
  }
};
// 或者使用一个统一的监听器
watch(
  [
    () => projectReportForm.value.informationNote,
    () => projectReportForm.value.remark,
    () => projectReportForm.value.ossId,
    () => projectReportForm.value.milestonePlan
  ],
  ([infoNote, remark, ossId, milestonePlan]) => {
    if (infoNote !== undefined) form.value.informationNote = infoNote;
    if (remark !== undefined) form.value.remark = remark;
    if (ossId !== undefined) form.value.ossId = ossId;
    if (milestonePlan !== undefined) form.value.milestonePlan = milestonePlan;
  },
  { deep: true }
);
/** 提交按钮 */
const submitForm = async (status: string, mode: boolean) => {
  try {
    buttonLoading.value = true;
    // 处理日期范围数据
    if (dateRange.value && dateRange.value.length === 2) {
      // 将日期范围拆分为 beginDate 和 endDate
      projectReportForm.value.beginDate = String(dateRange.value[0]);
      projectReportForm.value.endDate = String(dateRange.value[1]);
    } else if (projectReportForm.value.beginDate && projectReportForm.value.endDate) {
      // 如果已经存在 beginDate 和 endDate，则设置到 dateRange 中
      dateRange.value = [projectReportForm.value.beginDate, projectReportForm.value.endDate];
    }
    // 验证两个表单
    let formValid = false;
    let detailFormValid = false;
    // 验证第一个表单
    await new Promise((resolve) => {
      projectFormRef.value?.validate((valid: boolean) => {
        formValid = valid;
        resolve(null);
      });
    });
    if (!formValid) {
      proxy?.$modal.msgError('请完善项目周报信息');
      // 滚动到第一个错误字段
      const errorFields = document.querySelector('.el-form-item__error');
      if (errorFields) {
        errorFields.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
      buttonLoading.value = false;
      return;
    }
    // 验证第二个表单
    await new Promise((resolve) => {
      projectReportDetailFormRef.value?.validate((valid: boolean) => {
        detailFormValid = valid;
        resolve(null);
      });
    });
    if (!detailFormValid) {
      proxy?.$modal.msgError('请完善项目周报明细信息');
      // 滚动到第一个错误字段
      const errorFields = document.querySelector('.el-form-item__error');
      if (errorFields) {
        errorFields.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
      buttonLoading.value = false;
      return;
    }
    // 设置后端发起和不等于草稿状态 直接走流程发起
    if (status != 'draft') {
      // 后端发起流程模式
      projectReportForm.value.flowCode = FlowCodeEnum.PROJECT_REPRORT_CODE;
      const msg = await generateCode();
      // 流程变量
      projectReportForm.value.variables = {
        projectId: form.value.projectId
      };
      // 流程实例业务扩展字段
      projectReportForm.value.bizExt = {
        businessTitle: '项目周报明细',
        businessCode: msg
      };
      // 直接使用现有的两个表单数据
      projectReportForm.value.projectId = form.value.projectId;
      projectReportForm.value.flowStatus = 'waiting';

      const requestData = {
        projectReport: form.value, // 项目周报数据
        projectDetailReport: projectReportForm.value // 项目周报明细数据
      };
      const res = await projectReportSubmitAndFlowStart(requestData).finally(() => (buttonLoading.value = false));
      projectReportForm.value = { ...projectReportForm.value, ...res.data };

      proxy?.$modal.msgSuccess('操作成功');
      proxy?.$tab.closePage();
      router.go(-1);
    } else {
      // 暂存逻辑
      form.value.status = '1';
      projectReportForm.value.projectReportStatus = '1';
      projectReportForm.value.flowStatus = 'draft';
      if (form.value.reportId) {
        await updateProjectReport(form.value);
      } else {
        const reportRes = await addProjectReport(form.value);
        form.value.reportId = reportRes.data.reportId;
        form.value.projectId = reportRes.data.projectId;
      }
      projectReportForm.value.reportId = form.value.reportId;
      projectReportForm.value.projectId = form.value.projectId;

      if (projectReportForm.value.reportDetailId) {
        await updateProjectReportDetail(projectReportForm.value).finally(() => (buttonLoading.value = false));
      } else {
        await addProjectReportDetail(projectReportForm.value).finally(() => (buttonLoading.value = false));
      }

      proxy?.$modal.msgSuccess('暂存成功');
      proxy?.$tab.closePage();
      router.go(-1);
    }
  } catch (error) {
    console.error('提交失败:', error);
    proxy?.$modal.msgError('提交失败');
  }
};
onMounted(async () => {
  await nextTick(async () => {
    routeParams.value = { ...route.query };
    const type = String(routeParams.value.type || '');
    const reportDataStr = routeParams.value.reportData as string | undefined;
    const masterReportIdRaw = routeParams.value.reportId;
    const masterReportId =
      masterReportIdRaw !== undefined && masterReportIdRaw !== null && String(masterReportIdRaw) !== ''
        ? String(masterReportIdRaw)
        : undefined;
    const detailBizIdRaw = routeParams.value.id;
    const detailBizId =
      detailBizIdRaw !== undefined && detailBizIdRaw !== null && String(detailBizIdRaw) !== ''
        ? String(detailBizIdRaw)
        : undefined;

    const setFillTimeNow = () => {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      projectReportForm.value.fillTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    const clearDraftDetailFields = () => {
      projectReportForm.value.informationNote = undefined;
      projectReportForm.value.remark = undefined;
      projectReportForm.value.ossId = undefined;
      projectReportForm.value.sortOrder = undefined;
      projectReportForm.value.activeFlag = undefined;
      projectReportForm.value.createTime = undefined;
      projectReportForm.value.createBy = undefined;
      projectReportForm.value.updateBy = undefined;
      projectReportForm.value.updateTime = undefined;
    };

    try {
      // 兼容旧链接：整行 JSON 放在 reportData
      if (reportDataStr && (type === 'view' || type === 'add' || type === 'update')) {
        proxy?.$modal.loading('正在加载数据，请稍后...');
        const reportData = JSON.parse(decodeURIComponent(reportDataStr));
        Object.assign(form.value, reportData);

        if (type === 'add') {
          if (shouldCheckApprovalData.value) {
            await checkApprovalData();
          } else {
            Object.assign(projectReportForm.value, reportData);
            setFillTimeNow();
            clearDraftDetailFields();
          }
        } else if (type === 'view') {
          await getProjectDetail();
        } else {
          const rid = routeParams.value.id;
          const res = await listProjectReportDetail({ pageNum: 1, pageSize: 10, reportId: rid });
          if (res.rows && res.rows.length > 0) {
            Object.assign(projectReportForm.value, res.rows[0]);
          }
          if (projectReportForm.value.beginDate && projectReportForm.value.endDate) {
            dateRange.value = [projectReportForm.value.beginDate, projectReportForm.value.endDate];
          }
        }
        proxy?.$modal.closeLoading();
        return;
      }

      // 审批：业务 id 为明细主键
      if (type === 'approval' && detailBizId) {
        proxy?.$modal.loading('正在加载数据，请稍后...');
        const reportDetailRes = await getProjectReportDetail(detailBizId);
        const rid = reportDetailRes.data.reportId;
        if (rid) {
          const reportRes = await getProjectReport(rid);
          Object.assign(form.value, reportRes.data);
          Object.assign(projectReportForm.value, reportDetailRes.data);
        }
        if (projectReportForm.value.beginDate && projectReportForm.value.endDate) {
          dateRange.value = [projectReportForm.value.beginDate, projectReportForm.value.endDate];
        }
        proxy?.$modal.closeLoading();
        return;
      }

      // 列表进入：按主表周报编号查看（多明细）
      if (type === 'view' && masterReportId) {
        proxy?.$modal.loading('正在加载数据，请稍后...');
        const reportRes = await getProjectReport(masterReportId);
        Object.assign(form.value, reportRes.data);
        await getProjectDetail();
        proxy?.$modal.closeLoading();
        return;
      }

      // 列表进入：按主表周报编号修改草稿
      if (type === 'update' && masterReportId) {
        proxy?.$modal.loading('正在加载数据，请稍后...');
        const reportRes = await getProjectReport(masterReportId);
        Object.assign(form.value, reportRes.data);
        const res = await listProjectReportDetail({ pageNum: 1, pageSize: 10, reportId: masterReportId });
        if (res.rows && res.rows.length > 0) {
          Object.assign(projectReportForm.value, res.rows[0]);
        }
        if (projectReportForm.value.beginDate && projectReportForm.value.endDate) {
          dateRange.value = [projectReportForm.value.beginDate, projectReportForm.value.endDate];
        }
        proxy?.$modal.closeLoading();
        return;
      }

      // 列表进入：在已有主表下新增一条明细
      if (type === 'add' && masterReportId) {
        proxy?.$modal.loading('正在加载数据，请稍后...');
        const reportRes = await getProjectReport(masterReportId);
        Object.assign(form.value, reportRes.data);

        if (shouldCheckApprovalData.value) {
          await checkApprovalData();
        }
        if (!hasApprovalData.value) {
          projectReportForm.value = { ...initProjectReportFormData };
          projectReportForm.value.reportId = form.value.reportId;
          projectReportForm.value.projectId = form.value.projectId;
          projectReportForm.value.milestonePlan = form.value.milestonePlan;
          setFillTimeNow();
          clearDraftDetailFields();
          dateRange.value = ['', ''] as [DateModelType, DateModelType];
        }

        proxy?.$modal.closeLoading();
        return;
      }

      // 纯新增
      if (type === 'add') {
        setFillTimeNow();
        return;
      }

      // 仅带明细 id：查看单条（与流程/旧链接兼容）
      if (type === 'view' && detailBizId && !masterReportId) {
        proxy?.$modal.loading('正在加载数据，请稍后...');
        const reportDetailRes = await getProjectReportDetail(detailBizId);
        const rid = reportDetailRes.data.reportId;
        if (rid) {
          const reportRes = await getProjectReport(rid);
          Object.assign(form.value, reportRes.data);
          Object.assign(projectReportForm.value, reportDetailRes.data);
          projectReportDetailList.value = [reportDetailRes.data];
        }
        if (projectReportForm.value.beginDate && projectReportForm.value.endDate) {
          dateRange.value = [projectReportForm.value.beginDate, projectReportForm.value.endDate];
        }
        proxy?.$modal.closeLoading();
        return;
      }

      // 仅带明细 id：修改（与旧待办兼容）
      if (type === 'update' && detailBizId && !masterReportId) {
        proxy?.$modal.loading('正在加载数据，请稍后...');
        const reportDetailRes = await getProjectReportDetail(detailBizId);
        const rid = reportDetailRes.data.reportId;
        if (rid) {
          const reportRes = await getProjectReport(rid);
          Object.assign(form.value, reportRes.data);
          Object.assign(projectReportForm.value, reportDetailRes.data);
        }
        if (projectReportForm.value.beginDate && projectReportForm.value.endDate) {
          dateRange.value = [projectReportForm.value.beginDate, projectReportForm.value.endDate];
        }
        proxy?.$modal.closeLoading();
      }
    } catch (e) {
      console.error('项目周报编辑页加载失败:', e);
      proxy?.$modal.closeLoading();
    }
  });
});
</script>
