<template>
	<el-card class="hl-card">
		<template #header>
			<span><span v-html="dialogTitle"></span>页</span>
		</template>
		<el-form ref="formRef" label-width="140px" :rules="formRules" :model="formData" v-loading="formLoading">
			<!-- 基础信息  横向布局 -->
			<el-card class="hl-card-info" v-if="dispatchType == 'PRODUCTION'">
				<template #header>
					<div class="hl-card-info-icona"></div><span class="hl-card-info-text">基础信息</span>
				</template>
				<el-row>
					<el-col :span="6">
						<el-form-item label="生产派工单号" prop="code">
							<el-input class="!w-260px" v-model="formData.code" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="生产任务单号" prop="code">
							<el-input class="!w-260px" v-model="formData.taskCode" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="项目编号" prop="projectCode">
							<el-input class="!w-260px" v-model="formData.projectCode" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="客户名称" prop="customerName">
							<el-input class="!w-260px" v-model="formData.customerName" :disabled="true" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="6">
						<el-form-item label="项目名称" prop="projectName">
							<el-input class="!w-260px" v-model="formData.projectName" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="项目结束日期" prop="projectEndTime">
							<el-date-picker
class="!w-260px" v-model="formData.projectEndTime" type="date" value-format="x"
								placeholder="项目结束日期" disabled />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="子项目名称" prop="projectSubName">
							<el-input class="!w-260px" v-model="formData.projectSubName" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="子项目编号" prop="projectSubCode">
							<el-input class="!w-260px" v-model="formData.projectSubCode" :disabled="true" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="6">
						<el-form-item label="零件名称" prop="materialName">
							<el-input class="!w-260px" v-model="formData.materialName" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="材质" prop="compositionName">
							<el-input class="!w-260px" v-model="formData.compositionName" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="规格型号" prop="spec">
							<el-input class="!w-260px" v-model="formData.spec" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="图号" prop="blueprintNo">
							<el-input class="!w-260px" v-model="formData.blueprintNo" :disabled="true" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="6">
						<el-form-item label="零件数量" prop="amount">
							<el-input class="!w-260px" v-model="formData.amount" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="系统单位" prop="unit">
							<el-select disabled v-model="formData.unit" clearable placeholder="请选择系统单位" class="!w-260px">
								<el-option
v-for="dict in getStrDictOptions(DICT_TYPE.HELI_MATERIAL_UNIT)" :key="dict.value"
									:label="dict.label" :value="dict.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="任务负责人" prop="ownerName">
							<el-input class="!w-260px" v-model="formData.ownerName" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="要求完成时间" prop="requiredCompletedDate">
							<el-date-picker
class="!w-260px" v-model="formData.requiredCompletedDate" type="date" value-format="x"
								placeholder="要求完成时间" disabled />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="备注" prop="remark">
							<el-input type="textarea" v-model="formData.remark" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="创建时间" prop="createTime">
							<el-date-picker
class="!w-260px" v-model="formData.createTime" type="date" value-format="x"
								placeholder="创建时间" disabled />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="单据状态" prop="dispatchStatus">
							<el-select v-model="formData.dispatchStatus" placeholder="请选择单据状态" clearable class="!w-260px" disabled>
								<el-option
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_DISPATCH_STATUS)" :key="dict.value"
									:label="dict.label" :value="dict.value" />
							</el-select>
						</el-form-item>

					</el-col>
				</el-row>
			</el-card>
			<el-card class="hl-card-info" v-if="dispatchType == 'ASSEMBLE'">
				<template #header>
					<div class="hl-card-info-icona"></div><span class="hl-card-info-text">基础信息</span>
				</template>
				<el-row>
					<el-col :span="6">
						<el-form-item label="装配派工单号" prop="code">
							<el-input class="!w-260px" v-model="formData.code" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="生产计划单号" prop="code">
							<el-input class="!w-260px" v-model="formData.planCode" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="项目编号" prop="projectCode">
							<el-input class="!w-260px" v-model="formData.projectCode" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="客户名称" prop="customerName">
							<el-input class="!w-260px" v-model="formData.customerName" :disabled="true" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="6">
						<el-form-item label="项目名称" prop="projectName">
							<el-input class="!w-260px" v-model="formData.projectName" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="子项目名称" prop="projectSubName">
							<el-input class="!w-260px" v-model="formData.projectSubName" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="子项目编号" prop="projectSubCode">
							<el-input class="!w-260px" v-model="formData.projectSubCode" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="BOM清单号" prop="bomCode">
							<el-input class="!w-260px" v-model="formData.bomCode" :disabled="true" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="6">
						<el-form-item label="数量" prop="amount">
							<el-input class="!w-260px" v-model="formData.projectSubAmount" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="单位" prop="unit">
							<el-select disabled v-model="formData.unit" clearable placeholder="请选择单位" class="!w-260px">
								<el-option
v-for="dict in getStrDictOptions(DICT_TYPE.HELI_MATERIAL_UNIT)" :key="dict.value"
									:label="dict.label" :value="dict.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="任务负责人" prop="ownerName">
							<el-input class="!w-260px" v-model="formData.ownerName" :disabled="true" />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="单据状态" prop="dispatchStatus">
							<el-select v-model="formData.dispatchStatus" placeholder="请选择单据状态" clearable class="!w-260px" disabled>
								<el-option
v-for="dict in getIntDictOptions(DICT_TYPE.HELI_DISPATCH_STATUS)" :key="dict.value"
									:label="dict.label" :value="dict.value" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="6">
						<el-form-item label="要求开始日期" prop="requiredStartDate">
							<el-date-picker
class="!w-260px" v-model="formData.requiredStartDate" type="date" value-format="x"
								placeholder="要求开始日期" disabled />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="要求完成日期" prop="requiredStartDate">
							<el-date-picker
class="!w-260px" v-model="formData.requiredEndDate" type="date" value-format="x"
								placeholder="要求完成日期" disabled />
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="创建时间" prop="createTime">
							<el-date-picker
class="!w-260px" v-model="formData.createTime" type="date" value-format="x"
								placeholder="创建时间" disabled />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="备注" prop="remark">
							<el-input type="textarea" v-model="formData.remark" :disabled="true" />
						</el-form-item>
					</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 v-if=" (formData.dispatchStatus != 2 && active != 'detail')  || !detailDisabled">
						<el-button class="hl-addbutton" type="primary" size="large" @click="onAddItem">新增</el-button>
					</el-col>
					<el-col>
						<el-card class="hl-incard">
							<el-form
ref="subFormRef" :model="formData.taskDispatchDetails" :rules="subFormRules"
								v-loading="subFormLoading" label-width="0">
								<el-table :data="formData.taskDispatchDetails" class="hl-table">
									<el-table-column fixed label="序号" align="center" type="index" width="80" />
									<el-table-column fixed label="工序名称" align="center" prop="procedureId" width="180">
										<template #header> <span class="hl-table_header">*</span>工序名称</template>
										<template #default="{ row, $index }">
											<el-form-item :prop="`${$index}.procedureId`" :rules="subFormRules.procedureId" class="mb-0px!">
<!--												<ProcedureSelect-->
<!--:disabled="detailDisabled  || row.procedureStatus != 0"-->
<!--													v-model="row.procedureId"-->
<!--													@update:new-value="(val) => { handleSelectedProcedure(row, val); }" />-->
                        <el-select v-model="row.procedureId" :disabled="detailDisabled  || row.procedureStatus != 0"  @update:new-value="(val) => { handleSelectedProcedure(row, val); }">
                          <el-option
                            v-for="dict in procedureList" :key="dict.id"
                            :label="dict.name" :value="dict.id" />
                        </el-select>
											</el-form-item>

										</template>
									</el-table-column>
									<el-table-column label="是否报工" prop="isReport" width="100">
										<template #default="scope">
											{{ getDictLabel(DICT_TYPE.HELI_COMMON_IS_OR_NOT, scope.row.isReport) }}
										</template>
									</el-table-column>
									<el-table-column label="顺序号" align="center" prop="sort" width="160">
                    <template #header> 顺序号</template>
                    <template #default="{ row, $index }">
											<el-form-item :prop="`${$index}.sort`"  class="mb-0px!">
												<el-input-number
min="0" :precision="0" class="!w-240px"
													:disabled="detailDisabled || (row.beginProduce != 0  && row.procedureStatus != 0)" v-model="row.sort"
													placeholder="请输入顺序号" />
											</el-form-item>
										</template>
									</el-table-column>
				<!--				<el-table-column label="负责人" align="center" prop="owner" width="180">
										<template #header> <span class="hl-table_header">*</span>负责人</template>
										<template #default="{ row, $index }">
											<el-form-item :prop="`${$index}.owner`" :rules="subFormRules.owner" class="mb-0px!">-->
<!--												<UserSelect-->
<!--v-model="row.owner" :disabled="detailDisabled || row.procedureStatus != 0"-->
<!--													@update:new-value="handleSelectedUser($index, $event)" />-->
                      <!--  <el-select v-model="row.owner" filterable :disabled="detailDisabled || (row.beginProduce != 0 && row.procedureStatus != 0)"  @update:new-value="handleSelectedUser($index, $event)">
                          <el-option
v-for="dict in userInit" :key="dict.id"
                                     :label="dict.username+' '+dict.nickname" :value="dict.id" />
                        </el-select>
											</el-form-item>
										</template>
									</el-table-column>-->
									<el-table-column label="负责人" align="center" prop="owner" width="180">
										<template #header> <span class="hl-table_header">*</span>负责人</template>
										<template #default="{ row, $index }">
											<el-form-item :prop="`${$index}.ownerNames`" :rules="subFormRules.owner" class="mb-0px!">
												 <el-input
                          class="!w-265px"
                          placeholder="负责人"
                          v-model="row.ownerNames"
                          readonly
                          :disabled="detailDisabled || row.beginProduce != 0 "
                          @click.prevent="handleClick(row.owners,$index)"
													 :title="row.ownerNames"
                        >
                          <template #append
                            ><el-button
                              :icon="Search"
                              :disabled="detailDisabled"
                              @click="openuserDialog(row.owners,$index)"
                          /></template>
                        </el-input>
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column label="预计开始时间" min-width="180">
										<template #header> <span class="hl-table_header">*</span>预计开始时间</template>
										<template #default="{ row, $index }">
											<el-form-item :prop="`${$index}.startTime`" :rules="subFormRules.startTime" class="mb-0px!">
												<el-date-picker
:disabled="detailDisabled || row.beginProduce != 0 " v-model="row.startTime"
													type="date" value-format="x" placeholder="选择预计开始日期" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column label="预计结束时间" min-width="180">
										<template #header> <span class="hl-table_header">*</span>预计结束时间</template>
										<template #default="{ row, $index }">
											<el-form-item :prop="`${$index}.endTime`" :rules="subFormRules.endTime" class="mb-0px!">
												<el-date-picker
:disabled="detailDisabled || row.beginProduce != 0 " v-model="row.endTime"
													type="date" value-format="x" placeholder="选择预计结束日期" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column label="预计工时" align="center" prop="workTime" width="180">
										<template #header> <span class="hl-table_header">*</span>预计工时</template>
										<template #default="{ row, $index }">
											<el-form-item :prop="`${$index}.workTime`" :rules="subFormRules.workTime" class="mb-0px!">
												<el-input-number
min="0" :precision="2" class="!w-240px"
													:disabled="detailDisabled || row.beginProduce != 0 " v-model="row.workTime"
													placeholder="请输入预计工时" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column label="派工数量" align="center" prop="amount" width="180">
										<template #header> <span class="hl-table_header">*</span>派工数量</template>
										<template #default="{ row, $index }">
											<el-form-item :prop="`${$index}.amount`" :rules="subFormRules.amount" class="mb-0px!">
												<el-input-number
						min="0" :max="formData.amount" :precision="0" class="!w-240px"
																			:disabled="detailDisabled  || row.beginProduce != 0 " v-model="row.amount"
													placeholder="请输入派工数量" />
											</el-form-item>
										</template>
									</el-table-column>
                  <el-table-column label="制造设备" min-width="180" align="center">
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.deviceModel`" :rules="subFormRules.deviceModel" class="mb-0px!">
                        <EquipmentSelect
                          v-model="row.deviceModel"
                          @update:new-value="handleSelectedequip($index, $event)"
                          :disabled="(detailDisabled || (row.beginProduce != 0 && row.procedureStatus != 0))" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="工序要点" prop="summary" min-width="160">
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.summary`" class="mb-0px!">
                        <el-input
                          :disabled="(detailDisabled ||(row.beginProduce != 0 && row.procedureStatus != 0))" v-model="row.summary"
                          placeholder="请输入工序要点" />
                      </el-form-item>
                    </template>
                  </el-table-column>
									<el-table-column label="系统单位" align="center" prop="unit" width="120">
										<template #default>
											{{ getDictLabel(DICT_TYPE.HELI_MATERIAL_UNIT, formData.unit) }}
										</template>
									</el-table-column>
                  <el-table-column label="工序编号" prop="procedureCode" width="140" />
									<el-table-column fixed="right" label="操作" align="center" min-width="100">
										<template #default="scope">
											<el-button
v-if="'detail' != active && (scope.row.beginProduce == 0 && scope.row.procedureStatus == 0) " link type="danger"
												size="small" @click.prevent="onDeleteItem(scope.$index)">
												删除
											</el-button>
										</template>
									</el-table-column>
								</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>
          <el-button @click="goback" size="large">取 消</el-button>
          <el-button
            v-if="active != 'detail' && formData.dispatchStatus == 1" @click="submitForm('SAVE')" type="primary"
            :disabled="formLoading" size="large">保 存</el-button>
          <el-button
            v-if="active != 'detail' && formData.dispatchStatus == 1" @click="submitForm('SUBMIT')" type="success"
            :disabled="formLoading" size="large">提 交</el-button>
          <el-button
            v-if="active != 'detail' && formData.dispatchStatus == 2" @click="submitForm('CANCEL_SUBMIT')"
            type="danger" :disabled="formLoading" size="large">取消提交</el-button>
          <el-button
            v-if="formData.dispatchStatus == 2" @click="printHandle(formData.id)" :disabled="formLoading"
            size="large" type="primary">打印流程卡</el-button>
				</template>
				<el-row>
					<el-col>
						<el-card class="hl-incard">
							<el-table
:data="formData.operateLogs" class="hl-table"
								:style="{ height: formData.operateLogs && formData.operateLogs.length > 10 ? '450px' : '' }">
								<el-table-column prop="type" label="操作" align="center">
									<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" :formatter="dateFormatter" />
							</el-table>
						</el-card>
					</el-col>
				</el-row>
			</el-card>
		</el-form>
<!--		<div class="hl-footer text-center">-->
<!--		-->
<!--		</div>-->
		<div>
			<!-- 排产弹框 -->
			<el-dialog v-model="dialogTableVisible" title="dialogTitle" width="1000">
				<template #title>
					<div class="dialog-title">
						提示
					</div>
					<!-- 介绍文本 -->
					<p class="introduction-text">
						当前选择设备经过计算，无法满足当前填写预计日期范围的预计工时，请修改！
					</p>
				</template>
				<span v-if="taskDD">如下为当前设备的历史预计日期范围,含有在{{ formatDateT(taskDD) }}前后七天的排产日历如下：</span>
				<el-table :data="dataList">
					<el-table-column property="projectName" label="项目名称" width="150" />
					<el-table-column property="projectSubName" label="子项目名称" width="150" />
					<el-table-column label="预计开始日期" width="150">
						<template #default="scope">
							{{ formatDateT(scope.row.startTime) }}
						</template>
					</el-table-column>
					<el-table-column label="预计结束日期">
						<template #default="scope">
							{{ formatDateT(scope.row.endTime) }}
						</template>
					</el-table-column>
					<el-table-column property="workTime" label="预计工时" width="150" />
					<el-table-column property="maxLongTime" label="每日最大运行时长" width="200" />
				</el-table>
			</el-dialog>
						<!-------------取消提交弹框---------------->
						<el-dialog v-model="centerDialogVisible" title="提示" width="30%" center>
						<span>
							该派工单，存在报工完数据，是否继续？
						</span>
						<template #footer>
							<span class="dialog-footer">
								<el-button type="primary" @click="sureToCancle()">
									确认
								</el-button>
								<el-button @click="centerDialogVisible = false">取消</el-button>
							</span>
						</template>
					</el-dialog>
		</div>
	</el-card>

	<!-- 【打印发货单】 - 弹框-->
	<ProductProcessPrint ref="ProductProcessPrintRef" :info="dialogInfo" />
	<!--派工人员选择弹框-->
	<UserDialog ref="userDialogref" @success="handleuserClick" />
</template>
<script setup lang="ts">
import {
	getIntDictOptions,
	getStrDictOptions,
	DICT_TYPE,
	getDictLabel
} from '@/utils/dict'
import {
	dateFormatter,
	formatDate
} from "@/utils/formatTime";
import UserDialog from './userselect.vue'
import { Search } from '@element-plus/icons-vue'
import {
	ref,
	watch
} from "vue";
import * as TaskDispatchApi from '@/api/heli/taskdispatch'
import {
	inject
} from 'vue'
import {
	useUserStore
} from "@/store/modules/user";
import {
	useCommonStore
} from "@/store/modules/common";
import {
	getOperateLogPage
} from "@/api/system/operatelog";
import ProcedureSelect from "@/views/heli/hlvuestyle/procedureSelect.vue";
import UserSelect from '@/views/heli/hlvuestyle/userSelect.vue'
import EquipSelect from "@/views/heli/hlvuestyle/equipSelect.vue";
import EquipmentSelect from "@/views/heli/hlvuestyle/equipmentSelect.vue";
import ProductProcessPrint from "./ProductProcessPrint.vue";
import * as EquipManufactureApi from '@/api/heli/equipmanufacture';
import {
	ElDialog,
	ElTable,
	ElTableColumn,
	ElButton
} from 'element-plus';
import * as UserApi from "@/api/system/user";
import * as ProcedureApi from "@/api/heli/procedure";


defineOptions({
	name: 'TaskDispatchDetail'
})
const userDialogref = ref()
const reload = inject('reload')
const {
	t
} = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const commonStore = useCommonStore()
const userStore = useUserStore()
const router = useRouter()

const active = toRef(commonStore.getStore('active'))
const currentId = toRef(commonStore.getStore('id'))
const dispatchType = toRef(commonStore.getStore("dispatchType"));


const formLoading = ref(false)
const dialogTitle = ref('')
const detailDisabled = ref(false)


const formatDateT = (timestamp) => {
	const date = new Date(timestamp);
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	return `${year}-${month}-${day}`; // 返回 YYYY-MM-DD 格式
}
const handleClick = (owners,index) => {
  openuserDialog(owners,index)
}
const openuserDialog = (owners,index) => {
  userDialogref.value.open(owners,index)
}
const handleuserClick = (val, index) => {
  // 确保逻辑正确无误，例如避免直接修改reactive引用的原始数组
  formData.value.taskDispatchDetails[index].owners = val.map((item) => item.id)
  formData.value.taskDispatchDetails[index].ownerNames = val.map((item) => item.nickname)

  // console.log(formData.value.taskDispatchDetails[index].owners);
  // console.log(formData.value.taskDispatchDetails[index].ownerNames);
}
const formData = ref({
	id: undefined,
	code: undefined,
	amount: undefined,
	projectSubAmount:undefined,
	dispatchType: undefined,
	taskId: undefined,
	planId: undefined,
	projectId: undefined,
	projectSubId: undefined,
	bomDetailId: undefined,
	dispatchStatus: undefined,
	remark: undefined,
	status: 1,
	taskDispatchDetails: [],
	taskDispatchDetailOwnerDOList:[],
	operateLogs: [],
	active: undefined,
	activeOpinion: '',
	craftInfos:[],
	craftContent:''
})

const formRef = ref() // 表单 Ref
const subFormRef = ref()
const formRules = reactive({
	code: [{
		required: true,
		message: '单号不能为空',
		trigger: 'blur'
	}],
	planCode: [{
		required: true,
		message: '生产计划单号不能为空',
		trigger: 'blur'
	}],
	taskCode: [{
		required: true,
		message: '生产任务单号不能为空',
		trigger: 'blur'
	}],
	customerName: [{
		required: true,
		message: '客户名称不能为空',
		trigger: 'blur'
	}],
	projectCode: [{
		required: true,
		message: '项目编号不能为空',
		trigger: 'blur'
	}],
	projectName: [{
		required: true,
		message: '项目名称不能为空',
		trigger: 'blur'
	}],
	projectSubCode: [{
		required: true,
		message: '子项目编号不能为空',
		trigger: 'blur'
	}],
	projectSubName: [{
		required: true,
		message: '子项目名称不能为空',
		trigger: 'blur'
	}],
	projectEndTime: [{
		required: true,
		message: '项目结束日期不能为空',
		trigger: 'blur'
	}],
	materialName: [{
		required: true,
		message: '零件名称不能为空',
		trigger: 'blur'
	}],
	compositionName: [{
		required: true,
		message: '材质不能为空',
		trigger: 'blur'
	}],
	blueprintNo: [{
		required: true,
		message: '图号不能为空',
		trigger: 'blur'
	}],
	bomCode: [{
		required: true,
		message: 'BOM清单号不能为空',
		trigger: 'blur'
	}],
	amount: [{
		required: true,
		message: '数量不能为空',
		trigger: 'blur'
	}],
	unit: [{
		required: true,
		message: '单位不能为空',
		trigger: 'blur'
	}],
	ownerName: [{
		required: true,
		message: '任务负责人不能为空',
		trigger: 'blur'
	}],
	requiredCompletedDate: [{
		required: true,
		message: '要求完成时间不能为空',
		trigger: 'blur'
	}],
	requiredStartDate: [{
		required: true,
		message: '要求开始日期不能为空',
		trigger: 'blur'
	}],
	requiredEndDate: [{
		required: true,
		message: '要求完成日期不能为空',
		trigger: 'blur'
	}],
	dispatchStatus: [{
		required: true,
		message: '单据状态不能为空',
		trigger: 'blur'
	}],
	status: [{
		required: true,
		message: '状态,1表示正常，2表示禁用不能为空',
		trigger: 'blur'
	}],
})

const dataList = ref([]);
const dialogTableVisible = ref(false)
const taskDD = ref(null);
//let manufactuId = null;
//let maxLongtime = null;
const userInit = ref()
const procedureList = ref()
let watches = [];

// 清理所有监听器
const clearWatches = () => {
	watches.forEach(unwatch => unwatch());
	watches = []; // 重新初始化
};


watch(
	() => formData.value.taskDispatchDetails,
	(newDetails) => {
		// 检查 newDetails 是否为有效数组
		if (!Array.isArray(newDetails)) {
			return; // 直接返回，不继续执行
		}

		// 清除之前的监听器
		clearWatches()
		newDetails.forEach((detail, index) => {
			// 监听每个工序的预计工时
			const unwatch = watch(
				() => detail.workTime,
				(newWorkTime) => {
					if (typeof newWorkTime !== 'number') {
						console.warn(`第 ${index + 1} 行的预计工时不是有效数字: ${newWorkTime}`);
						return;
					}
					console.log(`第 ${index + 1} 行的预计工时变化为: ${newWorkTime}`);
					console.log("detail==", detail)
					if(detail.startTime){
						//设置派工类型
						detail.dispatchTypes = "ASSEMBLE";
						openDialogWT(detail);
					}
				}
			);
			watches.push(unwatch); // 存储当前的取消监听函数
			//制造设备监听
			const unwatchDeviceModel = watch(
			    () => detail.deviceModel,
			        (newDeviceModel) => {
			            console.log(`第 ${index + 1} 行的制造设备变化为: ${newDeviceModel}`);
			            console.log("detail==", detail);
			            if (detail.startTime) {
							//设置派工类型
							detail.dispatchTypes = "ASSEMBLE";
			                openDialogWT(detail);
			            }
			        }
			);
			watches.push(unwatchDeviceModel);
		});
	}, {
	deep: true
} // 深度监听
);
const openDialogWT = async (dataParam) => {
	taskDD.value = null;
	taskDD.value = dataParam.startTime;
	const data = await TaskDispatchApi.getTaskDispatchDetailListByWorkTime(dataParam);
	//debugger
	dataList.value = [];
	if (data.total !== 0) {
		dataList.value = data.list; // 将获取到的数据存储到 dataList
		for(var a=0;a<dataList.value.length;a++){
			//处理未保存当前派工明细的情况下项目名称和子项目名称显示为空
			if(dataList.value[a].projectName == null){
				dataList.value[a].projectName = formData.value.projectName;
				dataList.value[a].projectSubName = formData.value.projectSubName;
			}
		}
		console.log("dataList.value==", dataList.value)
		dialogTableVisible.value = true; // 打开弹框
	} else {
		console.warn("没有获取到数据");
	}
};

/** 查询计算提示 */
const calculationPrompt = async (dataParam) => {
	formLoading.value = true;
	try {
		//debugger
		const data = await TaskDispatchApi.getTaskDispatchDetailListByWorkTime(dataParam);
		if (data.total != 0) {
			//如果data.total!=0也就是当data.list有数据的时候，去做个弹框在弹框中用列表展示data.lidt的数据
			console.log("data==", data.list);
		} else {
			console.warn("获取的数据中没有 maxlongtime");
		}
	} catch (error) {
		console.error("获取设备制造信息失败:", error);
	} finally {
		formLoading.value = false;
	}
}

// /** 查询每日最大运行时长 */
// const getEquipMfMaxlt = async () => {
//   formLoading.value = true;
//   try {
//     console.log("manufactuId==", manufactuId);
//     const data = await EquipManufactureApi.getEquipManufacture(manufactuId);

//     // 确保 data 和 maxlongtime 存在
//     if (data && typeof data.maxlongtime !== 'undefined') {
//       maxLongtime = data.maxlongtime;
//       console.log("maxLongtime==", maxLongtime);
//     } else {
//       console.warn("获取的数据中没有 maxlongtime");
//     }
//   } catch (error) {
//     console.error("获取设备制造信息失败:", error);
//   } finally {
//     formLoading.value = false;
//   }
// }

/** 重置表单 */
const resetForm = () => {
	formData.value = {
		id: undefined,
		code: undefined,
		amount: undefined,
		projectSubAmount:undefined,
		dispatchType: undefined,
		taskId: undefined,
		planId: undefined,
		projectId: undefined,
		projectSubId: undefined,
		bomDetailId: undefined,
		dispatchStatus: undefined,
		remark: undefined,
		status: 1,
		taskDispatchDetails: [],
		taskDispatchDetailOwnerDOList:[],
		operateLogs: [],
		active: undefined,
		activeOpinion: '',
		craftInfos:[],
		craftContent:''
	}
	formRef.value?.resetFields()
}
const subFormLoading = ref(false) // 子表单的加载中
const subFormRules = reactive({
  sort: [{
    required: true,
    message: '工序不能为空',
    trigger: 'blur'
  }],
	procedureId: [{
		required: true,
		message: '工序不能为空',
		trigger: 'blur'
	}],
	owner: [{
		required: true,
		message: '负责人不能为空',
		trigger: 'blur'
	}],
	workTime: [{
		required: true,
		message: '预计工时不能为空',
		trigger: 'blur'
	}],
	amount: [{
		required: true,
		message: '派工数量不能为空',
		trigger: 'blur'
	}],
	startTime: [{
		required: true,
		message: '预计开始日期不能为空',
		trigger: 'blur'
	}],
	endTime: [{
		required: true,
		message: '预计结束日期不能为空',
		trigger: 'blur'
	}],
})
const arrayEmpty = (list : any[]) => {
	if(list != null && list.length > 0){
		return false;
	}else{

		return true;
	}
}
const strEmpty = (str : string) => {
	if(str != null && str !==  ''){
		return false;
	}else{

		return true;
	}
}
const queryData = async (id?: number) => {
	resetForm()
	// 修改时，设置数据
	if (id) {
		formLoading.value = true
		try {
			formData.value = await TaskDispatchApi.getTaskDispatch(id)
			if(formData.value.craftContent != null && formData.value.craftContent != ''){
				formData.value.craftInfos = JSON.parse(formData.value.craftContent)
			}

			formData.value.taskDispatchDetails = await TaskDispatchApi.getTaskDispatchDetailListByDispatchIdNew(id,'ASSEMBLE');
      formData.value.bomCode =  formData.value.projectSubCode
			if (formData.value.dispatchStatus == 2) {
				detailDisabled.value = true
			}

			// 操作日志
			let logParams = {
				pageNo: 1,
				pageSize: 99,
				businessId: id,
				businessType: 'TASK_DISPATCH'
			}
			formData.value.operateLogs = (await getOperateLogPage(logParams)).list
		} finally {
			formLoading.value = false
		}
	}
}
const centerDialogVisible = ref(false);
const isSureCancle = ref(false)
const sureToCancle = () =>{
	isSureCancle.value = true;
	centerDialogVisible.value = false;
	submitForm('CANCEL_SUBMIT');
}
const submitForm = async (operate) => {

	formData.value.active = operate
	// 校验子表单
	await subFormRef.value.validate()
	// 提交请求
	formLoading.value = true
	try {
		if(operate == 'CANCEL_SUBMIT'){
			//如果是取消提交
			 if(!isSureCancle.value){
				//如果没确认过//判断是否存在已报工完的派工
				 var hasOver =  await TaskDispatchApi.judgeHasOver(formData.value.id);
				 if(hasOver){
					centerDialogVisible.value = true;
					return;
				 }
			 }
		}
		isSureCancle.value  = false
		// 提交明细不能为空
		if (operate == 'SUBMIT') {
			if (!formData.value.taskDispatchDetails || formData.value.taskDispatchDetails.length == 0) {
				message.error('派工明细不能为空')
				return
			}
		}

    for (let i = 0; i < formData.value.taskDispatchDetails.length; i++) {
      let name
      if (formData.value.taskDispatchDetails[i].amount<formData.value.taskDispatchDetails[i].numAmount){
        for (let j = 0; j < procedureSelectList.value.list.length; j++) {
          if (procedureSelectList.value.list[j].id==formData.value.taskDispatchDetails[i].procedureId){
            name=procedureSelectList.value.list[j].name
            message.error("工序"+name+"")
            return
          }
        }
      }

    }
    //   for (let i = 0; i < formData.value.taskDispatchDetails.length-1; i++) {
    //   for (let j = i+1; j < formData.value.taskDispatchDetails.length; j++) {
    //     if (formData.value.taskDispatchDetails[i].sort==formData.value.taskDispatchDetails[j].sort){
    //       message.error("派工工序的顺序号重复,请确认！")
    //       return
    //     }
    //   }
    // }
    // for (let i = 0; i < formData.value.taskDispatchDetails.length; i++) {
    //     if (formData.value.taskDispatchDetails[i].sort!=i+1){
    //       message.error("派工工序的顺序号不允许跳数字,请确认！")
    //       return
    //     }
    // }
		formData.value.taskDispatchDetailOwnerDOList = formData.value.taskDispatchDetails;
		const data = formData.value as unknown as TaskDispatchApi.TaskDispatchVO
		let dataId = await TaskDispatchApi.operateTaskDispatch(data)
		message.success(t('common.operationSuccess'))

		let jumpActive = 'update'
		if (operate == 'SUBMIT') {
			jumpActive = 'detail'
		}
		commonStore.setStore('active', jumpActive)
		commonStore.setStore('id', dataId)
		reload()
	} finally {
		formLoading.value = false
	}
}
const procedureSelectList = ref<ProcedureApi.ProcedureVO[]>([])
const queryParams = {
  pageNo: 1,
  pageSize: 10,
  code: undefined,
  name: undefined,
  description: undefined,
  status: 1,
  creator: undefined,
  createTime: [],
  updater: undefined,
  updateTime: [],
  deleted: undefined,
  tenantId: undefined,
  isReport: undefined,
  wid: undefined
}
/** 新增按钮操作 */
const onAddItem = () => {
	const row = {
		id: undefined,
		procedureId: undefined,
		sort: undefined,
		owner: undefined,
		workTime: undefined,
		amount: undefined,
		summary: undefined,
		status: 1,
		procedureStatus: 0,
    beginProduce: 0,
		dispatchId: undefined,
	}
	if(!arrayEmpty(formData.value.craftInfos)){
			formData.value.craftInfos.forEach(item => {
				if(item.name == '装配'){
					row.startTime = item.startDate;
					row.endTime = item.endDate
				}
			})
	}
	row.amount = formData.value.projectSubAmount
	row.dispatchId = formData.value.id
	formData.value.taskDispatchDetails.push(row)
}

const goback = () => {
	router.back()
}

/** 删除子项操作 */
const onDeleteItem = async (index) => {
	let deletedItems = formData.value.taskDispatchDetails.splice(index, 1)
	let id = deletedItems[0].id
	if (id) await TaskDispatchApi.deleteTaskDispatchDetailNew(id,'ASSEMBLE')
	message.success(t('common.delSuccess'))
}

const handleSelectedProcedure = async (row: any, newValue: any) => {
	if (newValue) {
		row.procedureId = newValue.id
		row.procedureCode = newValue.code
		row.isReport = newValue.isReport
	} else {
		row.procedureId = undefined
		row.procedureCode = undefined
		row.isReport = undefined
	}
}

const handleSelectedUser = (currentIndex, newValue: any) => {
	formData.value.taskDispatchDetails[currentIndex].owner = newValue?.id
}

const handleSelectedequip = (currentIndex: number, newValue: any) => {
	formData.value.taskDispatchDetails[currentIndex].deviceModel = newValue?.id
}
const ProductProcessPrintRef = ref() // 打印弹框
const printHandle = (id) => {
	ProductProcessPrintRef.value.open(id)
}

onMounted(async () => {
	dialogTitle.value = t('action.' + active.value)
	if ('detail' == active.value) {
		detailDisabled.value = true
	}
  userInit.value = await UserApi.getDeptName("生产部")
  procedureList.value = await ProcedureApi.getProcedureZPage()
	queryData(currentId.value)
  const data = await ProcedureApi.getProcedurePage(queryParams)
  procedureSelectList.value=data

})
</script>
<style scoped lang="less">
.dialog-title {
	font-size: 40px;
	/* 调整字体大小 */
	font-weight: bold;
	/* 加粗 */
	text-align: center;
	/* 居中对齐 */
	margin: 0;
	/* 去掉默认外边距 */
	margin-bottom: 5px;
	/* 如果需要，可以设置标题底部的间距 */
}

.introduction-text {
	margin: 0;
	/* 去掉默认的外边距 */
	padding: 0;
	/* 去掉内边距，如果有的话 */
}

.el-dialog {
	padding: 10px;
	/* 调整为合适的值 */
}
</style>
