<template>
  <el-card class="hl-card" style="position: relative">
    <template #header>
      <span>编辑页</span>
    </template>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="160px" v-loading="formLoading">
      <el-card class="hl-card-info">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">基础信息</span>
        </template>

        <el-row>
          <el-col :span="24">
            <el-row>

              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="计划编号" prop="planNo">
                      <el-input class="!w-265px" placeholder="系统自动生成" v-model="formData.planNo" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目名称" prop="projectName">
                      <el-input class="!w-265px" placeholder="项目名称" v-model="formData.projectName" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目负责人" prop="projectOwner">
                      <!-- <el-select class="!w-265px" v-model="formData.projectOwner" filterable >
                        <el-option v-for="dict in userInit" :key="dict.id"
                          :label="dict.username+' '+dict.nickname" :value="dict.id" />
                      </el-select> -->
                       <UserSelect v-model="formData.projectOwner"  @update:new-value="handleSelectedUser1" class="!w-265px"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="是否要工艺" prop="hasCraft">
                      <el-radio-group v-model="formData.hasCraft" @change="handleCraftInfo">
                        <el-radio
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_COMMON_IS_OR_NOT)" :key="dict.value"
                          :label="dict.value">
                          {{ dict.label }}
                        </el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="计划编制人" prop="editor">
                      <!-- <el-select class="!w-265px" v-model="formData.editor" filterable >
                        <el-option v-for="dict in userInit" :key="dict.id"
                          :label="dict.username+' '+dict.nickname" :value="dict.id" />
                      </el-select> -->
                      <UserSelect v-model="formData.editor"  @update:new-value="handleSelectedUser3" class="!w-265px"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="计划编制日期" prop="editorDate">
                      <el-date-picker
class="!w-265px" v-model="formData.editorDate" type="date" value-format="x"
                        placeholder="计划编制日期" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="80">
                    <el-form-item label="备注" prop="description">
                      <el-input
class="!w-713px" type="textarea" v-model="formData.description" show-word-limit
                        maxlength="200" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目编号" prop="projectCode">
                      <el-input class="!w-265px" placeholder="项目编号" v-model="formData.projectCode" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="业务员" prop="businessMan">
                      <el-input class="!w-265px" placeholder="业务员" v-model="formData.businessMan" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="所属业务线" prop="businessLine">
                      <el-select class="!w-265px" v-model="formData.businessLine" disabled>
                        <el-option
v-for="dict in getStrDictOptions(DICT_TYPE.HELI_BUSINESS_LINE)" :key="dict.value"
                          :label="dict.label" :value="dict.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="工艺负责人" prop="craftOwner">
                      <!-- <el-select class="!w-265px" v-model="formData.craftOwner" filterable :disabled="!formData.hasCraft " >
                        <el-option v-for="dict in userInit" :key="dict.id"
                          :label="dict.username+' '+dict.nickname" :value="dict.id" />
                      </el-select> -->
                       <UserSelect v-model="formData.craftOwner"  @update:new-value="handleSelectedUser2" class="!w-265px"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="计划审核人" prop="auditor">
                      <!-- <el-select class="!w-265px" v-model="formData.auditor" filterable >
                        <el-option v-for="dict in userInit" :key="dict.id"
                          :label="dict.username+' '+dict.nickname" :value="dict.id" />
                      </el-select> -->
                      <UserSelect v-model="formData.auditor"  @update:new-value="handleSelectedUser4" class="!w-265px"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="计划审核日期" prop="auditDate">
                      <el-date-picker
class="!w-265px" v-model="formData.auditDate" type="date" value-format="x"
                        placeholder="计划审核日期" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目状态" prop="projectStatus">
                      <el-select v-model="formData.projectStatus" placeholder="项目状态" clearable class="!w-265px" disabled>
                        <el-option
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_PROJECT_ORDER_STATUS)"
                          :key="dict.value" :label="dict.label" :value="dict.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目开始日期" prop="projectStartTime">
                      <el-date-picker
class="!w-265px" v-model="formData.projectStartTime" type="date" value-format="x"
                        placeholder="项目开始日期" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="性质" prop="property">
                      <el-select class="!w-265px" v-model="formData.property" placeholder="下拉选择" disabled>
                        <el-option
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_PROJECT_PROPERTY)" :key="dict.value"
                          :label="dict.label" :value="dict.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="工艺开始日期" prop="craftStartTime">
                      <el-date-picker
class="!w-265px" v-model="formData.craftStartDate" type="date" value-format="x"
                        placeholder="工艺开始日期" :disabled="!formData.hasCraft "/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="计划批准人" prop="approver">
                      <!-- <el-select class="!w-265px" v-model="formData.approver" filterable >
                        <el-option v-for="dict in userInit" :key="dict.id"
                          :label="dict.username+' '+dict.nickname" :value="dict.id" />
                      </el-select> -->
                       <UserSelect v-model="formData.approver"  @update:new-value="handleSelectedUser5" class="!w-265px"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="计划批准日期" prop="approveDate">
                      <el-date-picker
class="!w-265px" v-model="formData.approveDate" type="date" value-format="x"
                        placeholder="计划批准日期" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="生产状态" prop="status">
                      <el-select v-model="formData.status" placeholder="生产状态" clearable class="!w-265px" disabled>
                        <el-option
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_PROJECT_PLAN_STATUS)" :key="dict.value"
                          :label="dict.label" :value="dict.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="客户名称" prop="customerName">
                      <el-input class="!w-265px" v-model="formData.customerName" placeholder="客户名称" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目结束日期" prop="projectEndTime">
                      <el-date-picker
class="!w-265px" v-model="formData.projectEndTime" type="date" value-format="x"
                        placeholder="项目结束日期" disabled />
                         <span style="position: absolute; left: 0; top: 30px" v-if="formData.projectStartTime && formData.projectEndTime">{{
                          ' 共计' +
                          betweenDay1(
                            new Date(formData.projectStartTime),
                            new Date(formData.projectEndTime)
                          ) +
                          '天'
                        }}</span>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="是否紧急" prop="isUrgency">
                      <el-select class="!w-265px" v-model="formData.isUrgency" disabled>
                        <el-option
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_COMMON_IS_OR_NOT)" :key="dict.value"
                          :label="dict.label" :value="dict.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="工艺结束日期" prop="craftEndTime">
                      <el-date-picker
class="!w-265px" v-model="formData.craftEndDate" type="date" value-format="x"
                        placeholder="工艺结束日期" :disabled="!formData.hasCraft " />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="创建时间" prop="createTime">
                      <el-date-picker
class="!w-265px" v-model="formData.createTime" type="date" value-format="x"
                        placeholder="创建时间" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目变更日期" prop="changeLastDate">
                      <el-date-picker
class="!w-265px" v-model="formData.changeLastDate" type="date" value-format="x"
                        placeholder="项目变更日期" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目变更次数" prop="changeNum">
                      <el-input class="!w-265px" placeholder="项目变更次数" v-model="formData.changeNum"  disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

				<el-col :span="6">
				  <el-row>
					<el-col :span="24">
						<el-form-item label="要求设计结束日期" prop="changeEndTime">
						  <el-date-picker
class="!w-265px" v-model="formData.changeEndTime" type="date" value-format="x"
						    placeholder="要求设计结束日期" />
						</el-form-item>
					</el-col>
				  </el-row>
				</el-col>

            </el-row>
          </el-col>
        </el-row>

      </el-card>

      <el-card class="hl-card-info">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">子项目信息</span>
        </template>
        <el-row>
          <el-col>
            <el-card class="hl-incard">
              <el-form
ref="subFormRef" :model="formData.projectPlanSubs" :rules="subFormRules"
                v-loading="subFormLoading" label-width="0">
                <el-table :show-overflow-tooltip="true" :data="formData.projectPlanSubs" class="hl-table">
                  <el-table-column label="序号" align="center" type="index" width="70px" fixed />
                  <el-table-column prop="name" label="子项目名称" min-width="140px" align="center" fixed />
                  <el-table-column prop="projectSubShortName" min-width="130px" align="center">
                    <template #header><span class="hl-table_header">*</span>子项目简码</template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.projectSubShortName`" :rules="subFormRules.projectSubShortName" class="mb-0px!">
                        <el-input
v-model="row.projectSubShortName" placeholder="子项目简码"
                          @change="(name) => handleSubCode(row, name)" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="amount" label="数量" min-width="70px" align="center" />
                  <el-table-column prop="mouldId" align="center" min-width="130px">
                    <template #header> 模具类型 </template>
                    <template #default="scope">
                      <el-form-item :prop="`${scope.$index}.mouldId`" class="mb-0px!">
                        <el-select
v-model="scope.row.mouldId" clearable placeholder="下拉选择" disabled
                          @change="(mid) => handleMouldType(scope, mid)" style="width: 100%">
                          <el-option v-for="dict in mouldTypeList" :key="dict.id" :label="dict.name" :value="dict.id" />
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="equipId" align="center" min-width="140px">
                    <template #header> 设备型号 </template>
                    <template #default="scope">
                      <el-form-item :prop="`${scope.$index}.equipId`" class="mb-0px!">
                        <!-- <el-select v-model="scope.row.equipId" clearable placeholder="下拉选择" style="width: 100%">
                          <el-option v-for="dict in scope.row.equipList" :key="dict.id" :label="dict.name"
                            :value="dict.id" />
                        </el-select> -->
                        <EquipSelect v-model="scope.row.equipId" @update:new-value="handleSelectedequip(scope, $event)"  />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column min-width="180px" align="center">
                    <template #header>毛坯开始日期</template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.startBlankDate`" class="mb-0px!">
                        <el-date-picker
class="!w-265px" v-model="row.startBlankDate" type="date" value-format="x"
                                        placeholder="毛坯开始日期" @change="handleDateChange($index, row.startBlankDate,row.blankDate,'1',row.blankOwner,row.id)"/>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column min-width="180px" align="center">
                    <template #header>毛坯结束日期</template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.blankDate`" class="mb-0px!">
                        <el-date-picker
class="!w-265px" v-model="row.blankDate" type="date" value-format="x"
                                        placeholder="毛坯结束日期" @change="handleDateChange($index, row.startBlankDate,row.blankDate,'1',row.blankOwner,row.id)" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="blankNum" label="毛坯工时" min-width="110px" align="center" />
                  <el-table-column min-width="150px" align="center">
                    <template #header>毛坯负责人</template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.blankOwner`" class="mb-0px!">
                     <el-select class="!w-265px" v-model="row.blankOwner" clearable  @update:new-value="handleSelectedUser6($index,$event)" @change="handleDateChange($index, row.startBlankDate,row.blankDate,'1',row.blankOwner,row.id)" >
                          <el-option v-for="dict in userInit" :key="dict.id"
                            :label="dict.username+'  '+dict.nickname" :value="dict.id" />
                        </el-select>
<!--                        <UserSelect v-model="row.blankOwner"  @update:new-value="handleSelectedUser6($index,$event)" @change="handleDateChange($index, row.startBlankDate,row.blankDate,'1',row.blankOwner,row.id)"  class="!w-265px"/>-->
                      </el-form-item>
                    </template>
                  </el-table-column>




				<el-table-column min-width="180px" align="center">
				  <template #header>2D开始日期</template>
				  <template #default="{ row, $index }">
				    <el-form-item :prop="`${$index}.startTwoDimDate`" class="mb-0px!">
				      <el-date-picker
class="!w-265px" v-model="row.startTwoDimDate" type="date" value-format="x"
				        placeholder="2D开始日期"  @change="handleDateChange($index, row.startTwoDimDate,row.twoDimDate,'2',row.twoDimOwner,row.id)"/>
				    </el-form-item>
				  </template>
				</el-table-column>
                  <el-table-column min-width="180px" align="center">
                    <template #header>2D结束日期</template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.twoDimDate`" class="mb-0px!">
                        <el-date-picker
class="!w-265px" v-model="row.twoDimDate" type="date" value-format="x"
                          placeholder="2D结束日期" @change="handleDateChange($index, row.startTwoDimDate,row.twoDimDate,'2',row.twoDimOwner,row.id)"/>
                      </el-form-item>
                    </template> 
                  </el-table-column>
				  <el-table-column prop="twoDimNum" label="2D工时" min-width="90px" align="center" />
                  <el-table-column min-width="150" align="center">
                    <template #header>2D负责人</template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.twoDimOwner`" class="mb-0px!">
                     <el-select class="!w-265px" v-model="row.twoDimOwner"  clearable @update:new-value="handleSelectedUser7($index,$event)" @change="handleDateChange($index, row.startTwoDimDate,row.twoDimDate,'2',row.twoDimOwner,row.id)">
                          <el-option v-for="dict in userInit" :key="dict.id"
                            :label="dict.username+' '+dict.nickname" :value="dict.id" />
                        </el-select>
<!--                         <UserSelect v-model="row.twoDimOwner"  @update:new-value="handleSelectedUser7($index,$event)" @change="handleDateChange($index, row.startTwoDimDate,row.twoDimDate,'2',row.twoDimOwner,row.id)" class="!w-265px"/>-->
                      </el-form-item>
                    </template>
                  </el-table-column>
				<el-table-column min-width="180px" align="center">
				  <template #header>3D开始日期</template>
				  <template #default="{ row, $index }">
				    <el-form-item :prop="`${$index}.startThreeDimDate`" class="mb-0px!">
				      <el-date-picker
class="!w-265px" v-model="row.startThreeDimDate" type="date" value-format="x"
				        placeholder="3D开始日期" @change="handleDateChange($index, row.startThreeDimDate,row.threeDimDate,'3',row.threeDimOwner,row.id)"/>
				    </el-form-item>
				  </template>
				</el-table-column>
                  <el-table-column min-width="180" align="center">
                    <template #header>3D结束日期</template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.threeDimDate`" class="mb-0px!">
                        <el-date-picker
class="!w-265px" v-model="row.threeDimDate" type="date" value-format="x"
                          placeholder="3D结束日期" @change="handleDateChange($index, row.startThreeDimDate,row.threeDimDate,'3',row.threeDimOwner,row.id)"/>
                      </el-form-item> 
                    </template>
                  </el-table-column>
				  <el-table-column prop="threeDimNum" label="3D工时" min-width="90px" align="center" />
                  <el-table-column min-width="150" align="center">
                    <template #header>3D负责人</template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.threeDimOwner`" class="mb-0px!">
                        <el-select class="!w-265px" v-model="row.threeDimOwner" clearable @update:new-value="handleSelectedUser8($index,$event)" @change="handleDateChange($index, row.startThreeDimDate,row.threeDimDate,'3',row.threeDimOwner,row.id)">
                          <el-option v-for="dict in userInit" :key="dict.id"
                            :label="dict.username+' '+dict.nickname" :value="dict.id" />
                        </el-select>
<!--                         <UserSelect v-model="row.threeDimOwner"  @update:new-value="handleSelectedUser8($index,$event)" @change="handleDateChange($index, row.startThreeDimDate,row.threeDimDate,'3',row.threeDimOwner,row.id)" class="!w-265px"/>-->
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column prop="compositionName" label="主要材质" min-width="100px" align="center" />
                  <el-table-column prop="projectSubCode" label="子项目编号" min-width="180px" align="center" />
                  <el-table-column prop="unit" label="单位" min-width="90px" align="center">
                    <template #default="scope">
                      <dict-tag :type="DICT_TYPE.HELI_MATERIAL_UNIT" :value="scope.row.unit" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="id" label="id" min-width="80px" align="center"/>
                </el-table>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="hl-card-info">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">工艺流程</span>
        </template>
        <el-row>
          <el-col>
            <el-card class="hl-incard">
              <el-table :data="formData.craftInfos" class="hl-table">
                <el-table-column label="序号" prop="id" type="index" width="80" />

                <el-table-column min-width="120" prop="name" label="工艺流程" align="center" />
                <el-table-column min-width="150" label="开始日期" align="center">
                  <template #default="{ row, $index }">
                    <el-form-item :prop="`${$index}.startDate`" class="mb-0px!">
                      <el-date-picker
style="width: 100%" v-model="row.startDate" type="date" value-format="x"
                        placeholder="开始日期" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column min-width="150" label="结束日期" align="center">
                  <template #default="{ row, $index }">
                    <el-form-item :prop="`${$index}.endDate`" class="mb-0px!">
                      <el-date-picker
style="width: 100%" v-model="row.endDate" type="date" value-format="x"
                        placeholder="结束日期" />
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column min-width="150" label="责任人" align="center">
                  <template #default="{ row, $index }">
                    <el-form-item :prop="`${$index}.owner`" class="mb-0px!">
                       <el-select style="width: 100%" v-model="row.owner"  clearable @update:new-value="handleSelectedUser9($index,$event)" v-if="row.name!='检验'">
                          <el-option v-for="dict in userInit1" :key="dict.id"
                            :label="dict.username+' '+dict.nickname" :value="dict.id" />
                        </el-select>
                      <el-select style="width: 100%" v-model="row.owner"  clearable @update:new-value="handleSelectedUser9($index,$event)" v-if="row.name=='检验'">
                        <el-option v-for="dict in userInit2" :key="dict.id"
                                   :label="dict.username+' '+dict.nickname" :value="dict.id" />
                      </el-select>
<!--                          <UserSelect v-model="row.owner"  @update:new-value="handleSelectedUser9($index,$event)" class="!w-265px"/>-->
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column min-width="350" label="备注" align="center">
                  <template #default="{ row, $index }">
                    <el-form-item :prop="`${$index}.description`" class="mb-0px!">
                      <el-input style="width: 100%" v-model="row.description" placeholder="备注" />
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="hl-card-info" v-if="false">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">操作日志</span>
        </template>
        <el-row>
          <el-col>
            <el-card class="hl-incard">
              <el-table :data="formData.operateLogs" class="hl-table" :style="{ height: formData.operateLogs.length > 10 ? '450px' : '' }">
                <el-table-column prop="type" label="操作" align="center" width="200px">
                  <template #default="scope">
                    {{ getDictLabel(DICT_TYPE.SYSTEM_OPERATE_TYPE, scope.row.type) }}
                  </template>
                </el-table-column>
                <el-table-column prop="userNickname" label="操作人" align="center" />
                <el-table-column label="操作时间" align="center" prop="startTime" width="220" :formatter="dateFormatter" />
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <div class="hl-footer text-center">
      <el-button @click="() => router.back()" size="large">取 消</el-button>
      <el-button @click="submitForm" type="success" size="large">保 存</el-button>
    </div>
  </el-card>
  <ProjectOrderDialog ref="projectOrderDialog" @success="handleSelectedProjectOrder" />
   <ProjectSubDialog :title="dialogTitle" width="80%" v-model="dialogVisible" :parent-method="parentMethod" :parent-methods="clouse"  :projectOrderSubs="dataList" :ownerId="ownerId" :dateOne="dateOne" :dateTwo="dateTwo" :id="id" :diffDays="diffDays" :typeNames="typeNames"  @update="handleUpdate" :showCloseProp="false" center /><!-- :ownerId="ownerId" :dateOne="dateOne" :dateTwo="dateTwo" :id="id" :diffDays="diffDays" :typeNames="typeNames" -->


</template>
<script setup lang="ts">
import { inject } from 'vue'
import { getIntDictOptions, getStrDictOptions, getDictLabel, DICT_TYPE } from '@/utils/dict'
import {betweenDay, formatDate, dateFormatter, betweenDay1} from '@/utils/formatTime'
import { Search, Plus } from '@element-plus/icons-vue'
import ProjectOrderDialog from '@/views/heli/plan/projectOrderDialog.vue'
import ProjectSubDialog from '@/views/heli/plan/projectSubDialog.vue'
import * as PlanApi from '@/api/heli/plan'
import * as PlanSubApi from '@/api/heli/plansub'
import * as ProjectOrderApi from '@/api/heli/projectorder'
import * as CustomerApi from '@/api/heli/customer'
import * as UserApi from '@/api/system/user'
import * as EquipApi from '@/api/heli/equip'
import * as MouldTypeApi from '@/api/heli/mouldtype'
import { getOperateLogPage } from '@/api/system/operatelog'
import UserSelect from '@/views/heli/hlvuestyle/userSelect.vue'
import EquipSelect from '@/views/heli/hlvuestyle/equipSelect.vue'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { query } = useRoute()
const router = useRouter()
const reload = inject('reload')

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref('设计时间冲突信息窗'); // 弹窗的标题
const fuzerenId = ref();
const startTimeOne = ref();
const endTimeTwo = ref(); 
const dateThree = ref(); 
const formRef = ref() // 表单
const subFormRef = ref() //子表单 Ref

const prod = ref({
	projectPlanSubs: []
})

const currentTime = ref('');
const prods = ref({
	projectPlanSubs: []
})

const formData = ref({
  id: undefined,
  projectId: undefined,
  projectOwner: undefined,
  hasCraft: 1,
  craftOwner: undefined,
  craftStartTime: undefined,
  craftEndTime: undefined,
  editor: undefined,
  editorDate: undefined,
  auditor: undefined,
  auditDate: undefined,
  approver: undefined,
  approveDate: undefined,
  description: undefined,
  status: undefined,
  createTime: undefined,
  operateLogs: [],
  projectOrderSubs: [],
  projectPlanSubs: [],
  craftInfos: [],
  craftContent: undefined,
  changeEndTime: undefined
})
const ownerId = ref('');
const dateOne = ref('');
const dateTwo = ref('');
const id = ref('');
const diffDays = ref('');
const typeNames = ref('');
const dataList = ref({
	projectOrderSubs: []



})

const dataListShuju = ref([]);
const dataListShujus = ref([]);
const formRules = reactive({
  projectCode: [{ required: true, message: '项目编号不能为空', trigger: 'blur' }],

})
const subFormRules = reactive({
  projectSubShortName: [{ required: true, message: '子项目简称不能为空', trigger: 'blur' }],

})
const projectOrderDialog = ref()
const openProjectOrderDialog = () => {
  projectOrderDialog.value?.open()
}
const handleSelectedProjectOrder = (arr: ProjectOrderVO[]) => {
  if (arr) {
    formData.value.projectCode = arr.code
    formData.value.projectStatus = arr.orderStatus
    formData.value.customerName = arr.customerName
    formData.value.projectName = arr.projectName
    formData.value.businessMan = arr.businessManName
    formData.value.projectStartTime = arr.projectStartTime
    formData.value.projectEndTime = arr.projectEndTime
    formData.value.businessLine = arr.businessLine
    formData.value.property = arr.property
    formData.value.isUrgency = arr.isUrgency
    formData.value.projectId = arr.id

    handleInitPlanSub()
  }
};
const parentMethod = async () => {
   // 检查是否超过要求设计日期
   const isOverdue = dataList.value.projectOrderSubs.some(sub => {
    if (sub.changeEndTime) {
      return sub.blankDate > sub.changeEndTime ||
             sub.twoDimDate > sub.changeEndTime ||
             sub.threeDimDate > sub.changeEndTime;
    }
    return false;
   });
   if (isOverdue) {
    message.error("本次插活已经超过要求设计结束日期，无法插活");
    return; // 如果超过日期，直接返回，不执行后续代码
   }
   dialogVisible.value = false;
   // 更新 formData 中的数据
   dataList.value.projectOrderSubs.forEach(sub => {
    const matchingPlanSub = formData.value.projectPlanSubs.find(planSub => planSub.id === sub.id);
    if (matchingPlanSub) {
      matchingPlanSub.startBlankDate = sub.startBlankDate;
      matchingPlanSub.blankDate = sub.blankDate;
      matchingPlanSub.startTwoDimDate = sub.startTwoDimDate;
      matchingPlanSub.twoDimDate = sub.twoDimDate;
      matchingPlanSub.startThreeDimDate = sub.startThreeDimDate;
      matchingPlanSub.threeDimDate = sub.threeDimDate;
    }
   });
   // 直接调用提交方法
   await submitForm();
   // 清空数据
   dataListShuju.value = [];   
};
/* const parentMethod = () => {
//先判断是否超过要求设计日期，超过时给出提醒，不允许插活
    for(var a= 0;a<dataList.value.projectOrderSubs.length;a++){
		if(dataList.value.projectOrderSubs[a].changeEndTime){
			if(dataList.value.projectOrderSubs[a].blankDate>dataList.value.projectOrderSubs[a].changeEndTime
			|| dataList.value.projectOrderSubs[a].twoDimDate>dataList.value.projectOrderSubs[a].changeEndTime
			|| dataList.value.projectOrderSubs[a].threeDimDate>dataList.value.projectOrderSubs[a].changeEndTime)
			{
				message.error("本次插活已经超过要求设计结束日期，无法插活");
			}
		}
		
	}
	dialogVisible.value = false
	for(var a= 0;a<dataList.value.projectOrderSubs.length;a++){
		 for(var b=0;b<formData.value.projectPlanSubs.length;b++){
			 if(dataList.value.projectOrderSubs[a].id == formData.value.projectPlanSubs[b].id){
				formData.value.projectPlanSubs[b].startBlankDate 	= dataList.value.projectOrderSubs[a].startBlankDate
				formData.value.projectPlanSubs[b].blankDate			= dataList.value.projectOrderSubs[a].blankDate
	
				 formData.value.projectPlanSubs[b].startTwoDimDate  = dataList.value.projectOrderSubs[a].startTwoDimDate
				 formData.value.projectPlanSubs[b].twoDimDate	    = dataList.value.projectOrderSubs[a].twoDimDate
	
				 formData.value.projectPlanSubs[b].startThreeDimDate= dataList.value.projectOrderSubs[a].startThreeDimDate
				 formData.value.projectPlanSubs[b].threeDimDate     =dataList.value.projectOrderSubs[a].threeDimDate
			 }
	
		 }
	}
	//直接调用提交方法
	submitForm()
	dataListShuju.value = []; */
	
	
	
	/* if(formData.value.changeEndTime){
		if(currentTime.value>formData.value.changeEndTime){
			message.error("本次插活已经超过要求设计结束日期，无法插活");
		}else{
			//确定插活后，将日期进行更新，并在根据最后一个日期继续查看后面的时间是否有冲突
			 dialogVisible.value = false
			 console.log(dataList.value.projectOrderSubs);
			 for(var a= 0;a<dataList.value.projectOrderSubs.length;a++){
				 for(var b=0;b<formData.value.projectPlanSubs.length;b++){
					 if(dataList.value.projectOrderSubs[a].id == formData.value.projectPlanSubs[b].id){
						formData.value.projectPlanSubs[b].startBlankDate 	= dataList.value.projectOrderSubs[a].startBlankDate
						formData.value.projectPlanSubs[b].blankDate			= dataList.value.projectOrderSubs[a].blankDate
			
						 formData.value.projectPlanSubs[b].startTwoDimDate  = dataList.value.projectOrderSubs[a].startTwoDimDate
						 formData.value.projectPlanSubs[b].twoDimDate	    = dataList.value.projectOrderSubs[a].twoDimDate
			
						 formData.value.projectPlanSubs[b].startThreeDimDate= dataList.value.projectOrderSubs[a].startThreeDimDate
						 formData.value.projectPlanSubs[b].threeDimDate     =dataList.value.projectOrderSubs[a].threeDimDate
					 }
			
				 }
			
			 }
		}
	}else{
		//确定插活后，将日期进行更新，并在根据最后一个日期继续查看后面的时间是否有冲突
		 dialogVisible.value = false
		 console.log(dataList.value.projectOrderSubs);
		 for(var a= 0;a<dataList.value.projectOrderSubs.length;a++){
			 for(var b=0;b<formData.value.projectPlanSubs.length;b++){
				 if(dataList.value.projectOrderSubs[a].id == formData.value.projectPlanSubs[b].id){
					formData.value.projectPlanSubs[b].startBlankDate 	= dataList.value.projectOrderSubs[a].startBlankDate
					formData.value.projectPlanSubs[b].blankDate			= dataList.value.projectOrderSubs[a].blankDate
		
					 formData.value.projectPlanSubs[b].startTwoDimDate  = dataList.value.projectOrderSubs[a].startTwoDimDate
					 formData.value.projectPlanSubs[b].twoDimDate	    = dataList.value.projectOrderSubs[a].twoDimDate
		
					 formData.value.projectPlanSubs[b].startThreeDimDate= dataList.value.projectOrderSubs[a].startThreeDimDate
					 formData.value.projectPlanSubs[b].threeDimDate     =dataList.value.projectOrderSubs[a].threeDimDate
				 }
		
			 }
		
		 }
	} */
	

 
 

//};
const clouse = () => {
	dialogVisible.value = false
	dataListShuju.value = [];
	}


/* 计算设计天数 */
const handleDateChange = (index, startBlankDate,blankDate,num,ownder,id) =>{
	dataListShuju.value = [];
	if (typeof startBlankDate === 'undefined' || startBlankDate === null || startBlankDate === '') {
		message.error("请选择开始日期，否则无法计算设计天数")
		return;
	}
	if(typeof blankDate === 'undefined' || blankDate === null || blankDate === ''){
		message.error("请选择结束日期，否则无法计算设计天数")
		return;
	}

	//用户选择完成后要取数据库中检索是否存在时间冲突，存在弹出插活框
    if(startBlankDate>blankDate){
		message.error("开始时间必须早于结束时间，否则无法计算设计天数，请检查")
		return;
	}
	
	//调用查询天数的后端接口
	getSearchRlTs(startBlankDate,blankDate,index,num,ownder);



	//计算天数
	 // 将日期字符串转换为Date对象
	  const date1 = new Date(startBlankDate);
	  const date2 = new Date(blankDate);

	  // 计算两个日期之间的天数差
	  const timeDiff = Math.abs(date2.getTime() - date1.getTime());
	  const diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
	  const tianshu = diffDays+1;
	  
	  



}

const getSearchRlTs = async(startDateTime:string,endDateTime:string,index:number ,num:string,ownder:number) => {
	let data = await PlanSubApi.getSearchRlTsS(formatDate(startDateTime,'YYYY-MM-DD'),formatDate(endDateTime,'YYYY-MM-DD'));
	if(num === "1"){
			  //调用接口查询检索设计时间是否冲突
			formData.value.projectPlanSubs[index].blankNum = data;
			
	
			 // formatDate(startBlankDate,'YYYY-MM-DD')
			if(ownder){
				prod.value.projectPlanSubs  = JSON.parse(JSON.stringify(formData.value.projectPlanSubs));
				startTimeOne.value = formatDate(startDateTime,'YYYY-MM-DD');
				endTimeTwo.value = formatDate(endDateTime,'YYYY-MM-DD');
				fuzerenId.value = ownder;
				getOwnderList(index)
			}
			
			 /* getOwnderList(index,ownder,startBlankDate,blankDate,id) */
	
			  
	}else if(num === "2"){
			  //调用接口查询检索设计时间是否冲突
			  formData.value.projectPlanSubs[index].twoDimNum = data;
			  
			  if(ownder){
				prod.value.projectPlanSubs  = JSON.parse(JSON.stringify(formData.value.projectPlanSubs)); 
				startTimeOne.value = formatDate(startDateTime,'YYYY-MM-DD');
				endTimeTwo.value = formatDate(endDateTime,'YYYY-MM-DD');
				fuzerenId.value = ownder;
				getOwnderLists(index)
			  }
			  
	}else{
			  formData.value.projectPlanSubs[index].threeDimNum = data;
			  if(ownder){
				prod.value.projectPlanSubs  = JSON.parse(JSON.stringify(formData.value.projectPlanSubs));
				startTimeOne.value = formatDate(startDateTime,'YYYY-MM-DD');
				endTimeTwo.value = formatDate(endDateTime,'YYYY-MM-DD');
				fuzerenId.value = ownder;
				getOwnderListss(index)  
			  }
			  
			  
	}
}

//选择3D
const getOwnderListss = async (index: number) => {
	prod.value.projectPlanSubs[index].projectPlanId = formData.value.id;
	prod.value.projectPlanSubs[index].type = 3;
	dataListShujus.value = [];
	
    const currentRow = prod.value.projectPlanSubs[index];
    dateThree.value = currentRow.threeDimDate;
    const blankOwner = currentRow.threeDimOwner;
	dataListShujus.value.push(prod.value.projectPlanSubs[index]);
    // 递归处理函数
    const processRecursive = async (i: number) => {
        const datas = { ...prod.value.projectPlanSubs[i] };

		if (i!== index && prod.value.projectPlanSubs[i].threeDimOwner === blankOwner) {
			if (isInRange(currentRow.startThreeDimDate,currentRow.threeDimDate, prod.value.projectPlanSubs[i].startThreeDimDate,prod.value.projectPlanSubs[i].threeDimDate)) {
                const datalists = await PlanSubApi.getOwnderPlanSub(formatDate(currentRow.threeDimDate, 'YYYY-MM-DD'), prod.value.projectPlanSubs[i].threeDimNum);
                prod.value.projectPlanSubs[i].startThreeDimDate = datalists[0].dates;
                prod.value.projectPlanSubs[i].threeDimDate = datalists[1].dates;
                datas.startThreeDimDates = datas.startThreeDimDate;
                datas.threeDimDates = datas.threeDimDate;
				datas.startThreeDimDate = datalists[0].dates;
                datas.threeDimDate = datalists[1].dates;
				
				
				
				
                datas.changeEndTime = formData.value.changeEndTime;
				datas.projectPlanId = formData.value.id;
				datas.type = 2;
                currentTime.value = datalists[1].dates;
                dateThree.value = datalists[1].dates;
                dataListShuju.value.push(datas);
				console.log("最新的一次");
				console.log(dataListShuju.value);
				dataListShujus.value.push(datas);	
                await processRecursive(i); // 递归调用
            } 
        }
    };

    // 处理所有相关行
    for (let i = 0; i < prod.value.projectPlanSubs.length; i++) {
        await processRecursive(i);
    }

    // 去重逻辑
    for (let a = 0; a < dataListShuju.value.length; a++) {
        for (let b = a + 1; b < dataListShuju.value.length; b++) {
            if (dataListShuju.value[a] && dataListShuju.value[a].id && dataListShuju.value[b] && dataListShuju.value[b].id && dataListShuju.value[a].id === dataListShuju.value[b].id) {
                dataListShuju.value[a].startThreeDimDate = dataListShuju.value[b].startThreeDimDate;
                dataListShuju.value[a].threeDimDate = dataListShuju.value[b].threeDimDate;
                dataListShuju.value.splice(b, 1);
                b--;
            }
        }
    }

    // 更新数据
    dataList.value.projectOrderSubs = dataListShuju.value;
    ownerId.value = blankOwner;
    dateOne.value = formatDate(currentRow.startThreeDimDate, 'YYYY-MM-DD');
    dateTwo.value = formatDate(currentRow.threeDimDate, 'YYYY-MM-DD');
    id.value = currentRow.id;
    diffDays.value = '1';
    typeNames.value = '1';

   

    // 递归执行完毕后，执行以下代码
    const datalistss = await PlanSubApi.getOwnderPlanChaHuo(dataListShujus.value)//(formData.value.id, fuzerenId.value, startTimeOne.value, endTimeTwo.value, "", 0, 1, formatDate(dateThree.value, 'YYYY-MM-DD'));
    prods.value.projectPlanSubs = [];
	for (let a = 0; a < datalistss.length; a++) {
        dataListShuju.value.push(datalistss[a]);
		prods.value.projectPlanSubs.push(datalistss[a]);

    }
	let lastEndTime = null;
	for (let a = 0; a < prods.value.projectPlanSubs.length; a++) {
	    const prodItem =  { ...prods.value.projectPlanSubs[a]};
	    for (let b = 0; b < prod.value.projectPlanSubs.length; b++) {
	        const existingItem = { ...prod.value.projectPlanSubs[b]};
			if (existingItem.threeDimOwner === prodItem.threeDimOwner) {
				if (isInRange(prodItem.startThreeDimDate, prodItem.threeDimDate, existingItem.startThreeDimDate, existingItem.threeDimDate)) {
					const queryStartTime = lastEndTime || prodItem.threeDimDate;
				    const datalists = await PlanSubApi.getOwnderPlanSub(formatDate(queryStartTime, 'YYYY-MM-DD'), prod.value.projectPlanSubs[b].threeDimNum);
					prod.value.projectPlanSubs[b].startThreeDimDate = datalists[0].dates;
				    prod.value.projectPlanSubs[b].threeDimDate = datalists[1].dates;
				    existingItem.startThreeDimDates = existingItem.startThreeDimDate;
				    existingItem.threeDimDates = existingItem.threeDimDate;
					existingItem.startThreeDimDate = datalists[0].dates;
				    existingItem.threeDimDate = datalists[1].dates;
					

					
					lastEndTime = datalists[1].dates;
				    existingItem.changeEndTime = formData.value.changeEndTime;
				    existingItem.projectPlanId = formData.value.id;
				    existingItem.type = 2;
				    currentTime.value = datalists[1].dates;
				    dateThree.value = datalists[1].dates;
				    dataListShuju.value.push(existingItem);
				    dataListShujus.value.push(existingItem); 
				}	
			}
	        
	    }
	}
	 
	 // 显示对话框
	 if (dataList.value.projectOrderSubs.length > 0) {
	     dialogVisible.value = true;
	 }
};
/* const getOwnderListss = async (index: number) => {
	
	//根据行索引获取到编辑行
	   
	const currentRow = prod.value.projectPlanSubs[index];
	//获取到负责人ID
	const blankOwner = currentRow.threeDimOwner;
	for (let i = 0; i < prod.value.projectPlanSubs.length; i++) {
		const datas = {...prod.value.projectPlanSubs[i] }
		if (i!== index && prod.value.projectPlanSubs[i].threeDimOwner === blankOwner) {
			if (isInRange(currentRow.startThreeDimDate,currentRow.threeDimDate, prod.value.projectPlanSubs[i].startThreeDimDate,prod.value.projectPlanSubs[i].threeDimDate)) {
				const datalists  = await PlanSubApi.getOwnderPlanSub(formatDate(currentRow.threeDimDate,'YYYY-MM-DD'),prod.value.projectPlanSubs[i].threeDimNum)
				prod.value.projectPlanSubs[i].startThreeDimDate = datalists[0].dates;
				prod.value.projectPlanSubs[i].threeDimDate = datalists[1].dates;
				datas.startThreeDimDate = datalists[0].dates;
				datas.threeDimDate	    = datalists[1].dates;
				datas.changeEndTime  = formData.value.changeEndTime;
				//将最后一次更新的数据的最晚时间进行记录，用于判断此次插活是否超过要求设计结束日期
				currentTime.value = datalists[1].dates;
				//赋值给集合
				 dataListShuju.value.push(datas);

				getOwnderListss(i);
			}
		}
	}
	for(let a=0;a<dataListShuju.value.length;a++){
		
		 for(let b=a+1;b<dataListShuju.value.length;b++){
			if (dataListShuju.value[a] && dataListShuju.value[a].id && dataListShuju.value[b] && dataListShuju.value[b].id &&dataListShuju.value[a].id === dataListShuju.value[b].id) {
				dataListShuju.value[a].startThreeDimDate = dataListShuju.value[b].startThreeDimDate;
				dataListShuju.value[a].threeDimDate = dataListShuju.value[b].threeDimDate;
				 // 删除下标为b的数据
				dataListShuju.value.splice(b, 1);
				// 由于删除了一个元素，需要调整内层循环的索引
				b--;
			}
		} 
	}
	
	 dataList.value.projectOrderSubs  = dataListShuju.value
	ownerId.value = blankOwner
	dateOne.value = formatDate(currentRow.startBlankDate,'YYYY-MM-DD')
	dateTwo.value = formatDate(currentRow.blankDate,'YYYY-MM-DD')
	id.value = currentRow.id
	diffDays.value = '1'
	typeNames.value = '1'
	
	if(dataList.value.projectOrderSubs.length>0){
		dialogVisible.value = true;
	} 
	


	 // 通知子组件数据已经更新
	  //emit('update');
} */

//选择2D
const getOwnderLists = async (index: number) => {
	prod.value.projectPlanSubs[index].projectPlanId = formData.value.id;
	prod.value.projectPlanSubs[index].type = 2;
	dataListShujus.value = [];
	
    const currentRow = prod.value.projectPlanSubs[index];
    dateThree.value = currentRow.twoDimDate;
    const blankOwner = currentRow.twoDimOwner;
	dataListShujus.value.push(prod.value.projectPlanSubs[index]);
    // 递归处理函数
    const processRecursive = async (i: number) => {
        const datas = { ...prod.value.projectPlanSubs[i] };

		if (i!== index && prod.value.projectPlanSubs[i].twoDimOwner === blankOwner) {
			if (isInRange(currentRow.startTwoDimDate,currentRow.twoDimDate, prod.value.projectPlanSubs[i].startTwoDimDate,prod.value.projectPlanSubs[i].twoDimDate)) {
                const datalists = await PlanSubApi.getOwnderPlanSub(formatDate(currentRow.twoDimDate, 'YYYY-MM-DD'), prod.value.projectPlanSubs[i].twoDimNum);
                prod.value.projectPlanSubs[i].startTwoDimDate = datalists[0].dates;
                prod.value.projectPlanSubs[i].twoDimDate = datalists[1].dates;
				
				datas.startTwoDimDates = datas.startTwoDimDate;
				datas.twoDimDates = datas.twoDimDate;
				
                datas.startTwoDimDate = datalists[0].dates;
                datas.twoDimDate = datalists[1].dates;
				
                datas.changeEndTime = formData.value.changeEndTime;
				datas.projectPlanId = formData.value.id;
				datas.type = 2;
                currentTime.value = datalists[1].dates;
                dateThree.value = datalists[1].dates;
                dataListShuju.value.push(datas);
				dataListShujus.value.push(datas);
				
				
				
                await processRecursive(i); // 递归调用
            } 
        }
    };

    // 处理所有相关行
    for (let i = 0; i < prod.value.projectPlanSubs.length; i++) {
        await processRecursive(i);
    }

    // 去重逻辑
    for (let a = 0; a < dataListShuju.value.length; a++) {
        for (let b = a + 1; b < dataListShuju.value.length; b++) {
            if (dataListShuju.value[a] && dataListShuju.value[a].id && dataListShuju.value[b] && dataListShuju.value[b].id && dataListShuju.value[a].id === dataListShuju.value[b].id) {
                dataListShuju.value[a].startTwoDimDate = dataListShuju.value[b].startTwoDimDate;
                dataListShuju.value[a].twoDimDate = dataListShuju.value[b].twoDimDate;
                dataListShuju.value.splice(b, 1);
                b--;
            }
        }
    }

    // 更新数据
    dataList.value.projectOrderSubs = dataListShuju.value;
    ownerId.value = blankOwner;
    dateOne.value = formatDate(currentRow.startTwoDimDate, 'YYYY-MM-DD');
    dateTwo.value = formatDate(currentRow.twoDimDate, 'YYYY-MM-DD');
    id.value = currentRow.id;
    diffDays.value = '1';
    typeNames.value = '1';

   

    // 递归执行完毕后，执行以下代码
    const datalistss = await PlanSubApi.getOwnderPlanChaHuo(dataListShujus.value)//(formData.value.id, fuzerenId.value, startTimeOne.value, endTimeTwo.value, "", 0, 1, formatDate(dateThree.value, 'YYYY-MM-DD'));
    prods.value.projectPlanSubs = [];
	for (let a = 0; a < datalistss.length; a++) {
        dataListShuju.value.push(datalistss[a]);
		prods.value.projectPlanSubs.push(datalistss[a]);

    }  
	
	let lastEndTime = null;
	for (let a = 0; a < prods.value.projectPlanSubs.length; a++) {
	    const prodItem =  { ...prods.value.projectPlanSubs[a]};
	    for (let b = 0; b < prod.value.projectPlanSubs.length; b++) {
	        const existingItem = { ...prod.value.projectPlanSubs[b]};
			if (existingItem.twoDimOwner === prodItem.twoDimOwner) {
				if (isInRange(prodItem.startTwoDimDate, prodItem.twoDimDate, existingItem.startTwoDimDate, existingItem.twoDimDate)) {
					const queryStartTime = lastEndTime || prodItem.twoDimDate;
				    const datalists = await PlanSubApi.getOwnderPlanSub(formatDate(queryStartTime, 'YYYY-MM-DD'), prod.value.projectPlanSubs[b].twoDimNum);
					prod.value.projectPlanSubs[b].startTwoDimDate = datalists[0].dates;
				    prod.value.projectPlanSubs[b].twoDimDate = datalists[1].dates;
					
					existingItem.startTwoDimDates = existingItem.startTwoDimDate;
					existingItem.twoDimDates = existingItem.twoDimDate;
					
				    existingItem.startTwoDimDate = datalists[0].dates;
				    existingItem.twoDimDate = datalists[1].dates;
					
					lastEndTime = datalists[1].dates;
				    existingItem.changeEndTime = formData.value.changeEndTime;
				    existingItem.projectPlanId = formData.value.id;
				    existingItem.type = 2;
				    currentTime.value = datalists[1].dates;
				    dateThree.value = datalists[1].dates;
				    dataListShuju.value.push(existingItem);
				    dataListShujus.value.push(existingItem); 
				}	
			}
	        
	    }
	}
	
	 // 显示对话框
	 if (dataList.value.projectOrderSubs.length > 0) {
	     dialogVisible.value = true;
	 }
};
/* const getOwnderLists = async (index: number) => {

	  
	const currentRow = prod.value.projectPlanSubs[index];
	//获取到负责人ID
	const blankOwner = currentRow.twoDimOwner;
	for (let i = 0; i < prod.value.projectPlanSubs.length; i++) {
		const datas = {...prod.value.projectPlanSubs[i] }
		if (i!== index && prod.value.projectPlanSubs[i].twoDimOwner === blankOwner) {
			if (isInRange(currentRow.startTwoDimDate,currentRow.twoDimDate, prod.value.projectPlanSubs[i].startTwoDimDate,prod.value.projectPlanSubs[i].twoDimDate)) {
				const datalists  = await PlanSubApi.getOwnderPlanSub(formatDate(currentRow.twoDimDate,'YYYY-MM-DD'),prod.value.projectPlanSubs[i].twoDimNum)
				prod.value.projectPlanSubs[i].startTwoDimDate = datalists[0].dates;
				prod.value.projectPlanSubs[i].twoDimDate = datalists[1].dates;
				datas.startTwoDimDate = datalists[0].dates;
				datas.twoDimDate	    = datalists[1].dates;
				datas.changeEndTime  = formData.value.changeEndTime;
				currentTime.value = datalists[1].dates;
				//赋值给集合
				 dataListShuju.value.push(datas);
				getOwnderLists(i);
			}
		}
	}
	for(let a=0;a<dataListShuju.value.length;a++){
		
		 for(let b=a+1;b<dataListShuju.value.length;b++){
			if (dataListShuju.value[a] && dataListShuju.value[a].id && dataListShuju.value[b] && dataListShuju.value[b].id &&dataListShuju.value[a].id === dataListShuju.value[b].id) {
				dataListShuju.value[a].startTwoDimDate = dataListShuju.value[b].startTwoDimDate;
				dataListShuju.value[a].twoDimDate = dataListShuju.value[b].twoDimDate;
				 // 删除下标为b的数据
				dataListShuju.value.splice(b, 1);
				// 由于删除了一个元素，需要调整内层循环的索引
				b--;
			}
		} 
	}
	
	 dataList.value.projectOrderSubs  = dataListShuju.value
	ownerId.value = blankOwner
	dateOne.value = formatDate(currentRow.startBlankDate,'YYYY-MM-DD')
	dateTwo.value = formatDate(currentRow.blankDate,'YYYY-MM-DD')
	id.value = currentRow.id
	diffDays.value = '1'
	typeNames.value = '1'
	
	if(dataList.value.projectOrderSubs.length>0){
		dialogVisible.value = true;
	} 
} */


// 选择毛坯 ,ownder: number,newdateOne: number,newdateTwo: number,newid:number   
const getOwnderList = async (index: number) => {
	prod.value.projectPlanSubs[index].projectPlanId = formData.value.id;
	prod.value.projectPlanSubs[index].type = 1;
	dataListShujus.value = [];
	
    const currentRow = prod.value.projectPlanSubs[index];
    dateThree.value = currentRow.blankDate;
    const blankOwner = currentRow.blankOwner;
	dataListShujus.value.push(prod.value.projectPlanSubs[index]);
    // 递归处理函数
    const processRecursive = async (i: number) => {
        const datas = { ...prod.value.projectPlanSubs[i] };

        if (i !== index && prod.value.projectPlanSubs[i].blankOwner === blankOwner) {
			
             if (isInRange(currentRow.startBlankDate, currentRow.blankDate, prod.value.projectPlanSubs[i].startBlankDate, prod.value.projectPlanSubs[i].blankDate)) {
                const datalists = await PlanSubApi.getOwnderPlanSub(formatDate(currentRow.blankDate, 'YYYY-MM-DD'), prod.value.projectPlanSubs[i].blankNum);
                prod.value.projectPlanSubs[i].startBlankDate = datalists[0].dates;
                prod.value.projectPlanSubs[i].blankDate = datalists[1].dates;
				datas.startBlankDates = datas.startBlankDate;
				datas.blankDates = datas.blankDate;
				
                datas.startBlankDate = datalists[0].dates;
                datas.blankDate = datalists[1].dates;
				
                datas.changeEndTime = formData.value.changeEndTime;
				datas.projectPlanId = formData.value.id
                currentTime.value = datalists[1].dates;
                dateThree.value = datalists[1].dates;
				datas.type = 1;
                dataListShuju.value.push(datas);
				dataListShujus.value.push(datas);
				
				
				
                await processRecursive(i); // 递归调用
            } 
        }
    };

    // 处理所有相关行
    for (let i = 0; i < prod.value.projectPlanSubs.length; i++) {
        await processRecursive(i);
    }

    // 去重逻辑
    for (let a = 0; a < dataListShuju.value.length; a++) {
        for (let b = a + 1; b < dataListShuju.value.length; b++) {
            if (dataListShuju.value[a] && dataListShuju.value[a].id && dataListShuju.value[b] && dataListShuju.value[b].id && dataListShuju.value[a].id === dataListShuju.value[b].id) {
                dataListShuju.value[a].startBlankDate = dataListShuju.value[b].startBlankDate;
                dataListShuju.value[a].blankDate = dataListShuju.value[b].blankDate;
                dataListShuju.value.splice(b, 1);
                b--;
            }
        }
    }

    // 更新数据
    dataList.value.projectOrderSubs = dataListShuju.value;
    ownerId.value = blankOwner;
    dateOne.value = formatDate(currentRow.startBlankDate, 'YYYY-MM-DD');
    dateTwo.value = formatDate(currentRow.blankDate, 'YYYY-MM-DD');
    id.value = currentRow.id;
    diffDays.value = '1';
    typeNames.value = '1';

    

    // 递归执行完毕后，执行以下代码
    const datalistss = await PlanSubApi.getOwnderPlanChaHuo(dataListShujus.value)//(formData.value.id, fuzerenId.value, startTimeOne.value, endTimeTwo.value, "", 0, 1, formatDate(dateThree.value, 'YYYY-MM-DD'));
    prods.value.projectPlanSubs = [];
	for (let a = 0; a < datalistss.length; a++) {
        dataListShuju.value.push(datalistss[a]);
		prods.value.projectPlanSubs.push(datalistss[a]);

    }
	 
	let lastEndTime = null;
	for (let a = 0; a < prods.value.projectPlanSubs.length; a++) {
	    const prodItem =  { ...prods.value.projectPlanSubs[a]};
	    for (let b = 0; b < prod.value.projectPlanSubs.length; b++) {
	        const existingItem = { ...prod.value.projectPlanSubs[b]};
			if (existingItem.blankOwner === prodItem.blankOwner) {
					if (isInRange(prodItem.startBlankDate, prodItem.blankDate, existingItem.startBlankDate, existingItem.blankDate)) {
						const queryStartTime = lastEndTime || prodItem.blankDate;
					    const datalists = await PlanSubApi.getOwnderPlanSub(formatDate(queryStartTime, 'YYYY-MM-DD'), prod.value.projectPlanSubs[b].blankNum);
						prod.value.projectPlanSubs[b].startBlankDate = datalists[0].dates;
					    prod.value.projectPlanSubs[b].blankDate = datalists[1].dates;
						
						existingItem.startBlankDates = existingItem.startBlankDate;
						existingItem.blankDates = existingItem.blankDate;
						
					    existingItem.startBlankDate = datalists[0].dates;
					    existingItem.blankDate = datalists[1].dates;
						
						lastEndTime = datalists[1].dates;
					    existingItem.changeEndTime = formData.value.changeEndTime;
					    existingItem.projectPlanId = formData.value.id;
					    existingItem.type = 2;
					    currentTime.value = datalists[1].dates;
					    dateThree.value = datalists[1].dates;
					    dataListShuju.value.push(existingItem);
					    dataListShujus.value.push(existingItem); 
					}
			}
	        
	    }
	} 
	 
	  // 显示对话框
	  if (dataList.value.projectOrderSubs.length > 0) {
	      dialogVisible.value = true;
	  }
};


//选择毛坯 ,ownder: number,newdateOne: number,newdateTwo: number,newid:number
/* const getOwnderList = async (index: number) => {	
	
	//根据行索引获取到编辑行
	const currentRow = prod.value.projectPlanSubs[index];
	dateThree.value = prod.value.projectPlanSubs[index].blankDate;
	//获取到负责人ID
	const blankOwner = currentRow.blankOwner;
	for (let i = 0; i < prod.value.projectPlanSubs.length; i++) {
		const datas = {...prod.value.projectPlanSubs[i] }
		
		if (i!== index && prod.value.projectPlanSubs[i].blankOwner === blankOwner) {
			
			if (isInRange(currentRow.startBlankDate,currentRow.blankDate, prod.value.projectPlanSubs[i].startBlankDate,prod.value.projectPlanSubs[i].blankDate)) {
				const datalists  = await PlanSubApi.getOwnderPlanSub(formatDate(currentRow.blankDate,'YYYY-MM-DD'),prod.value.projectPlanSubs[i].blankNum)
				prod.value.projectPlanSubs[i].startBlankDate = datalists[0].dates;
				prod.value.projectPlanSubs[i].blankDate = datalists[1].dates;
				datas.startBlankDate = datalists[0].dates;
				datas.blankDate	    = datalists[1].dates;
				datas.changeEndTime  = formData.value.changeEndTime;
				currentTime.value = datalists[1].dates;
				dateThree.value = datalists[1].dates;
				//赋值给集合
				 dataListShuju.value.push(datas);
				getOwnderList(i);
			}
		}
	}

	
	for(let a=0;a<dataListShuju.value.length;a++){
		
		 for(let b=a+1;b<dataListShuju.value.length;b++){
			if (dataListShuju.value[a] && dataListShuju.value[a].id && dataListShuju.value[b] && dataListShuju.value[b].id &&dataListShuju.value[a].id === dataListShuju.value[b].id) {
				dataListShuju.value[a].startBlankDate = dataListShuju.value[b].startBlankDate;
				dataListShuju.value[a].blankDate = dataListShuju.value[b].blankDate;
				 // 删除下标为b的数据
				dataListShuju.value.splice(b, 1);
				// 由于删除了一个元素，需要调整内层循环的索引
				b--;
			}
		} 
	}
		//完成后检查其他项目是否存在日期冲突
	console.log('调用了');
	const datalistss  = await PlanSubApi.getOwnderPlanChaHuo(formData.value.id,fuzerenId.value,startTimeOne.value,endTimeTwo.value,"",0,1,formatDate(dateThree.value,'YYYY-MM-DD'))
	for(var a=0;a<datalistss.length;a++){
		dataListShuju.value.push(datalistss[a]);
	}
	
	 dataList.value.projectOrderSubs  = dataListShuju.value
	ownerId.value = blankOwner
	dateOne.value = formatDate(currentRow.startBlankDate,'YYYY-MM-DD')
	dateTwo.value = formatDate(currentRow.blankDate,'YYYY-MM-DD')
	id.value = currentRow.id
	diffDays.value = '1'
	typeNames.value = '1'
  



	if(dataList.value.projectOrderSubs.length>0){
		dialogVisible.value = true;
	} 


	 // 通知子组件数据已经更新
	  //emit('update');
} */

const isInRange = (start, end, target1, target2) => {
    const startDate = new Date(start);
    const endDate = new Date(end);
    const targetDate1 = new Date(target1);
    const targetDate2 = new Date(target2);
    const isTarget1InRange = targetDate1 >= startDate && targetDate1 <= endDate;
    const isTarget2InRange = targetDate2 >= startDate && targetDate2 <= endDate;
    return isTarget1InRange || isTarget2InRange;
};

const handleUpdate = () => {
  // 处理子组件的更新通知
  console.log("子组件已更新");
};

const handleCraftInfo = (val) =>{
  if(val == 0){
    formData.value.craftOwner = undefined
    formData.value.craftStartDate = undefined
    formData.value.craftEndDate = undefined
  }
}
const handleSubCode = (row, name) => {
  row.projectSubCode = name.length==0?"" : (formData.value.projectCode + '-' + customerInit.value.brief + '-' + name)
}

const handleMouldType = async (scope, mid) => {
  // 获得设备信息下拉列表
  //scope.row.equipList = equipInit.value.filter(rg => rg.id == mid)
}

const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  await subFormRef.value.validate()

  let isRepeat= false
  formData.value.projectPlanSubs.forEach(item => {
    if(formData.value.projectPlanSubs.filter(record =>{ return  record.projectSubShortName == item.projectSubShortName }).length>1)
    isRepeat = true
  })
  if(isRepeat){
    await message.alert("子项目简称不能重复！")
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PlanApi.PlanVO
    data.craftContent = JSON.stringify(data.craftInfos)

    await PlanApi.updatePlan(data)
    formData.value.projectPlanSubs.forEach(item => {
      var subData = item as unknown as PlanSubApid.PlanSubVo
      // subData.projectId = item.projectOrderId
      // subData.projectPlanId = formData.value.id
      // subData.projectSubShortName = item.projectSubShortName
      // subData.projectSubCode = item.projectSubCode
      // subData.projectSubId = item.projectSubId
      if (subData.id == undefined) {
        subData.id = 0
        subData.id = PlanSubApi.createPlanSub(subData)
      } else {
        //subData.id = item.planSubId
        PlanSubApi.updatePlanSub(subData)
      }
      //subData.id = subData.projectSubId
    })
	//更新其余项目
	prods.value.projectPlanSubs.forEach(item => {
	  var subData = item as unknown as PlanSubApid.PlanSubVo
	  if (subData.id == undefined) {
	    subData.id = 0
	    subData.id = PlanSubApi.createPlanSub(subData)
	  } else {
	    //subData.id = item.planSubId
	    PlanSubApi.updatePlanSub(subData)
	  }
	  //subData.id = subData.projectSubId
	})
    message.success(t('common.updateSuccess'))
    // 发送操作成功的事件
   // emit('success')
  } finally {
    formLoading.value = false
  }
}

const handleInitPlanSub = async () => {
  // 项目子项列表
  formData.value.projectOrderSubs =
    await ProjectOrderApi.getProjectOrderSubListByProjectOrderId(formData.value.projectId)

  // 生产计划子项列表
  const queryParams = reactive({
    pageNo: 1,
    pageSize: 99,
    projectPlanId: query.id
  })

  formData.value.projectPlanSubs =
    (await PlanSubApi.getPlanSubPage(queryParams)).list

  formData.value.projectPlanSubs.forEach(item => {
    if (formData.value.projectOrderSubs.filter(sub => item.projectSubId == sub.id).length > 0) {
      var subTemp = formData.value.projectOrderSubs.find(sub => item.projectSubId == sub.id)
      item.planSubId = item.id
      item.projectPlanId = subTemp.projectPlanId
      item.projectId = subTemp.projectOrderId
      item.projectSubId = subTemp.id
      item.name = subTemp.name
      item.compositionName = subTemp.compositionName
      item.unit= subTemp.unit
      item.amount = subTemp.amount

      if(item.equip!= undefined &&  item.equip.length>0){
        item.mouldId = equipInit.value.filter(rg => rg.id == item.equipId)[0].mould_type_id
      }
      // item.projectSubCode = subTemp.projectSubCode
      // item.mouldId = subTemp.mouldId

      // item.blankDate = subTemp.blankDate
      // item.blankOwner = subTemp.blankOwner
      // item.twoDimDate = subTemp.twoDimDate
      // item.twoDimOwner = subTemp.twoDimOwner
      // item.threeDimDate = subTemp.threeDimDate
      // item.threeDimOwner = subTemp.threeDimOwner

      // if(item.equipId != undefined && item.equipId.length>0){
      // item.equipList = equipInit.value.filter(rg => rg.id == item.equipId)
      // }
      item.equipList = equipInit.value.filter(rg => rg.id == item.equipId)
    }

  })
}
const userInit = ref()
const userInit1 = ref()
const userInit2= ref()
const equipInit = ref()
const mouldTypeList = ref()
const customerInit = ref()
onMounted(async () => {

  //用户列表数据
  userInit.value = await UserApi.getDeptName("设计部")
  userInit1.value = await UserApi.getDeptName("生产部")
  userInit2.value = await UserApi.getDeptName("检验部")
  console.log(userInit2.value)
  // 模具类型下拉列表数据
  mouldTypeList.value = await MouldTypeApi.getSimpList()
  // 设备信息下拉列表数据
  equipInit.value = await EquipApi.getSimpList()
  // 获取库存信息
  formData.value = await PlanApi.getPlan(query.id)
  formData.value.hasCraft = 1

  await handleInitPlanSub()

  var projectInit = await ProjectOrderApi.getProjectOrder(formData.value.projectId)
  customerInit.value = await CustomerApi.getCustomer(projectInit.customerId)
  var businessManInit = await UserApi.getUser(projectInit.businessMan)

  formData.value.projectCode = projectInit.code
  formData.value.projectStatus = projectInit.orderStatus
  formData.value.customerName = customerInit?.value.name
  formData.value.projectName = projectInit.projectName
  formData.value.businessMan = businessManInit?.nickname
  formData.value.projectStartTime = projectInit.projectStartTime
  formData.value.projectEndTime = projectInit.projectEndTime
  formData.value.businessLine = projectInit.businessLine
  formData.value.property = projectInit.property
  formData.value.isUrgency = projectInit.isUrgency

  // 操作日志
  let logParams = {
    pageNo: 1,
    pageSize: 99,
    businessId: formData.value.projectId,
    businessType: 'PROJECT_ORDER'
  }
  formData.value.operateLogs = (await getOperateLogPage(logParams)).list

  if (formData.value.craftContent == null) {
    formData.value.craftInfos = []

    getIntDictOptions(DICT_TYPE.HELI_CRAFT).forEach(dict => {
      formData.value.craftInfos.push({ id: dict.value, name: dict.label, startDate: '', endDate: '', owner: '', description: '' })
    })
  } else {
    formData.value.craftInfos = eval(formData.value.craftContent)
  }
})

//项目负责人
const handleSelectedUser1 = (newValue: any) => {
  formData.value.projectOwner = newValue?.id
}
//工艺负责人
const handleSelectedUser2 = (newValue: any) => {
  formData.value.craftOwner = newValue?.id
}
// 计划编制人
const handleSelectedUser3 = (newValue: any) => {
  formData.value.editor = newValue?.id
}
// 计划审核人
const handleSelectedUser4 = (newValue: any) => {
  formData.value.auditor = newValue?.id
}
// 计划批准人
const handleSelectedUser5 = (newValue: any) => {

  formData.value.approver = newValue?.id
}
// 毛坯负责人
const handleSelectedUser6 = (currentIndex,newValue: any) => {
  console.log("111"+currentIndex)
   formData.value.projectPlanSubs[currentIndex].blankOwner = newValue?.id
}
// 设备型号
const handleSelectedequip = (scope, newValue: any) => {

  if(newValue !=null && newValue!= undefined && newValue.id>0){
    scope.row.equipId = newValue?.id
    scope.row.mouldId = equipInit.value.filter(ep => ep.id == newValue?.id)[0].mould_type_id
  }else{
    scope.row.equipId = null
    scope.row.mouldId = null
  }
}
// 2D负责人
const handleSelectedUser7 = (currentIndex,newValue: any) => {

   formData.value.projectPlanSubs[currentIndex].twoDimOwner = newValue?.id
}
// 3D负责人
const handleSelectedUser8 = (currentIndex,newValue: any) => {

   formData.value.projectPlanSubs[currentIndex].threeDimOwner = newValue?.id
}
// 责任人
const handleSelectedUser9 = (currentIndex,newValue: any) => {

   formData.value.craftInfos[currentIndex].owner = newValue?.id
}
</script>
<style>
a {
  color: #409eff;
  text-decoration: none;
}

.upload-file-uploader {
  margin-bottom: 10px;
  display: inline-block;
  margin-right: 20px;
}

.hl-card .alter-class {
  position: relative;
  border: solid 1px orange;
  outline: solid 1px orange;
}
.el-form-item__content{
  margin-left: 0px !important;
}
</style>
