<template>
  <Dialog v-model="dialogVisible" :before-close="handleClose" title="编辑页" style="width: 70%">
	<el-card class="hl-card">
		<el-form ref="formRef" label-width="140px" :rules="formRules" :model="formData" v-loading="formLoading">
			<!-- 基础信息  横向布局 -->
			<el-card class="hl-card-info" v-if="formData.dispatchType == 'PRODUCTION'">
				<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="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-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="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="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="blueprintNo">
							<el-input class="!w-260px" v-model="formData.blueprintNo" :disabled="true" />
						</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" 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.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="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>
            <el-checkbox-group  v-if="active != 'detail' && formData.dispatchStatus == 1 " v-model="checkList" @change="onAddItem()">
          <el-checkbox label="下料" size="large" border  />
          <el-checkbox label="铣床" size="large" border />
          <el-checkbox label="车床" size="large" border />
          <el-checkbox label="热处理"  size="large" border />
          <el-checkbox label="磨床" size="large" border  />
          <el-checkbox label="线切割"  size="large" border />
          <el-checkbox label="数控" size="large" border />
          <el-checkbox label="电火花" size="large" border />
          <el-checkbox label="刻字"  size="large" border />
          <el-checkbox label="电焊" size="large" border />
          <el-checkbox label="钻孔" size="large" border />
          <el-checkbox label="装配" size="large" border  />
        </el-checkbox-group>
						<!-- <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" height="250"  >

                  <el-table-column  fixed label="顺序号" align="center" prop="sort" width="145px"  >
										<template #default="{ row, $index }">
											<el-form-item :prop="`${$index}.sort`" :rules="subFormRules.sort" class="mb-0px!">
												<el-input-number
					min="0" :precision="0" class="!w-240px"
													:disabled="true" v-model="row.sort"
													placeholder="请输入顺序号" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column fixed label="工序名称" align="center" prop="procedureId" width="130">
										<template #header> <span class="hl-table_header">*</span>工序名称</template>
										<template #default="{ row }">
                      <!-- <el-select :disabled="detailDisabled || row.procedureStatus != 0" v-model="row.procedureId" placeholder="请选择工序" style="width: 115px"> -->
												<el-select :disabled="true" v-model="row.procedureId" placeholder="请选择工序" style="width: 115px">

												<el-option
                          v-for="item in procedureList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                          @change="() =>{ { handleSelectedProcedure(row); }}"
                        />
                    </el-select>
											<!-- <el-form-item prop="row.procedureId :rules="subFormRules.procedureId" class="mb-0px!">
                        <el-option
                          v-for="item in procedureList"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id"
                          @change="() =>{ { handleSelectedProcedure(row); }}"
                        /> -->
												<!-- <ProcedureSelect
                      :disabled="detailDisabled || row.procedureStatus != 0"
													v-model="row.procedureId"
													@update:new-value="(val) => { handleSelectedProcedure(row, val); }" /> -->
											<!-- </el-form-item> -->
										</template>
									</el-table-column>
                  <el-table-column fixed label="派工类型" align="center" prop="dispatchType" width="145px">
										<template #header> <span class="hl-table_header">*</span>派工类型</template>
										<template #default="{ row }">
                      <el-radio-group size="small"  :disabled="detailDisabled||row.beginProduce != 0 || row.procedureStatus != 0" v-model="row.dispatchType" @change="()=>dispatchTypeHasChange(row)">
                        <el-radio-button :label="1">人员</el-radio-button>
                        <el-radio-button :label="2">岗位</el-radio-button>
                      </el-radio-group>
											<!-- <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-form-item> -->
										</template>
									</el-table-column>
									<el-table-column  label="负责人" align="center" prop="owner"  width="135px">
										<template #header> <span class="hl-table_header">*</span>负责人</template>
										<template #default="{ row , $index}">
											<el-form-item :prop="`${$index}.owner`"  class="mb-0px!">
                      <el-select :disabled="detailDisabled||row.beginProduce != 0 || row.procedureStatus != 0"  clearable filterable v-if="row.dispatchType==1 " v-model="row.owner" placeholder="请选择负责人" style="max-width: 110px">
                      <el-option
                          v-for="item in ownerList1"
                          :key="item.index"
                          :label="item.label"
                          :value="item.id"
                        />
                      </el-select>
											<el-select :disabled="detailDisabled ||row.beginProduce != 0|| row.procedureStatus != 0"  clearable filterable v-if="row.dispatchType==2 && (row.owner != '' && row.owner != null )" v-model="row.owner" placeholder="请选择岗位" style="max-width: 110px">
                      <el-option
                          v-for="item in ownerList1"
                          :key="item.index"
                          :label="item.label"
                          :value="item.id"
                        />
                      </el-select>
                      <el-select :disabled="detailDisabled||row.beginProduce != 0 || row.procedureStatus != 0"  clearable filterable v-if="row.dispatchType==2 && (row.owner == '' || row.owner == null)" v-model="row.postId" placeholder="请选择岗位" style="width: 110px">
                      <el-option
                          v-for="item in ownerList2"
                          :key="item.index"
                          :label="item.label"
                          :value="item.id"
                        />
                      </el-select>
											</el-form-item>
											<!-- <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-form-item> -->
										</template>
									</el-table-column>
                  <el-table-column label="预计开始日期" min-width="170px">
										<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 " v-model="row.startTime"
													type="date" value-format="x" placeholder="选择预计开始日期" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column label="预计结束日期" min-width="170px">
										<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" 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="145px">
										<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 " v-model="row.workTime"
													placeholder="请输入预计工时" />
											</el-form-item>
										</template>
									</el-table-column>
									<el-table-column label="派工数量" align="center" prop="amount" width="145px">
										<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" 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="130px">
										<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="70px">
										<template #default>
											{{ getDictLabel(DICT_TYPE.HELI_MATERIAL_UNIT, formData.unit) }}
										</template>
									</el-table-column>
									<el-table-column label="是否报工" prop="isReport" width="70px">
										<template #default="scope">
											{{ getDictLabel(DICT_TYPE.HELI_COMMON_IS_OR_NOT, scope.row.isReport) }}
										</template>
									</el-table-column>
									<el-table-column label="工序编号" prop="procedureCode" width="140" />

									<el-table-column fixed="right" label="操作" align="center" min-width="90">
										<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.row,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>
				</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">

			<el-button @click="handleClose" size="large">取 消</el-button>
      <el-button v-if="showBefore == 0" @click="nextItem(1)" size="large" type="info">上一页</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>
      <el-button v-if="showNext == 0" @click="nextItem(2)" size="large" type="info">下一页</el-button>
		</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" />
  </Dialog>
</template>
<script setup lang="ts">
import {
	getIntDictOptions,
	getStrDictOptions,
	DICT_TYPE,
	getDictLabel
} from '@/utils/dict'
import {
	dateFormatter,
	formatDate
} from "@/utils/formatTime";
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 * as ProcedureApi from '@/api/heli/procedure'
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 * as TaskdispatchApi from '@/api/heli/taskdispatch';
import {
	ElDialog,
	ElTable,
	ElTableColumn,
	ElButton
} from 'element-plus';
import { error } from 'console';
const centerDialogVisible = ref(false);
const queryParams = {
  pageNo: 1,
  pageSize: 99,
  code: undefined,
  name: undefined,
  description: undefined,
  status: 1,
  creator: undefined,
  createTime: [],
  updater: undefined,
  updateTime: [],
  deleted: undefined,
  tenantId: undefined,
  isReport: undefined,
  wid: undefined
}
defineOptions({
	name: 'TaskDispatchDetail'
})

// const reload = inject('reload')
const {
	t
} = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const commonStore = useCommonStore()
const userStore = useUserStore()
const router = useRouter()
const dialogVisible = ref(false) // 弹窗的是否展示
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 formData = ref({
	id: undefined,
	code: undefined,
	amount: undefined,
	dispatchType: undefined,
	taskId: undefined,
	planId: undefined,
	projectId: undefined,
	projectSubId: undefined,
	bomDetailId: undefined,
	dispatchStatus: undefined,
	remark: undefined,
	status: 1,
	taskDispatchDetails: [],
	operateLogs: [],
	active: undefined,
	activeOpinion: ''
})

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'
	}],
	dispatchType: [{
		required: true,
		message: '派工类型不能为空',
		trigger: 'blur'
	}],
	owner: [{
		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;

let watches = [];
// 清理所有监听器
const clearWatches = () => {
	watches.forEach(unwatch => unwatch());
	watches = []; // 重新初始化
};
const emit = defineEmits(['success'])
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('是否退出?')
    .then(() => {
			dialogVisible.value=false;
			emit('success');
    })
    .catch(() => {
    })
}
const dispatchTypeHasChange = (row) =>{
	if(row.dispatchType == 1){
		row.postId =''
	}	else{
		row.owner = ''
		row.postId = ownerList2.value[0].id;
	}
}
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.startTime)
					if(detail.startTime){
						//设置派工类型
						detail.dispatchTypes = "PRODUCTION";
						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 = "PRODUCTION";
			                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 procedureList = ref<ProcedureApi.ProcedureVO[]>([]) // 用户列表
const procedureSelectList = ref<ProcedureApi.ProcedureVO[]>([])
const tsk_id = ref(0);
const dispatchlist = ref([]);
//派工单查询参数
const dispatchParams = ref({})
const open = async (id ,actives,dispatchParamss,ownerId,taskCode) => {
	showBefore.value = 0;
	showNext.value = 0;
	tsk_id.value = id;
	dispatchParams.value = JSON.parse(JSON.stringify(dispatchParamss));
	dispatchParams.value.ownerId  = ownerId;
	dispatchParams.value.taskCode  = taskCode;
	dispatchParams.value.id = id;
	active.value = actives;
	if ('detail' == actives) {
		detailDisabled.value = true
	}
  queryData(id)
	fetchAllProcedurePages();
  dialogVisible.value = true;
};
const showNext = ref(0)
const showBefore = ref(0)
const nextItem = async (type) => {
	dispatchParams.value.pageType = type;
	try{
		const data = await getTaskDispatchList()
		  dispatchlist.value = data;
			if(dispatchlist.value != null){
				tsk_id.value = dispatchlist.value[0].id;
				dispatchParams.value.id = tsk_id.value;
				if(dispatchlist.value.length == 2){
							showBefore.value = 0;
							showNext.value = 0;
				}else{
					if(type == 1){
							showNext.value = 0;
							showBefore.value = 1;
					}else{
						showNext.value = 1;
						showBefore.value = 0;
					}

				}
			}
			queryData(tsk_id.value)
			fetchAllProcedurePages();
	}catch(error){
		console.log(error);
	}
	console.log(tsk_id.value)
  // tsk_id.value = id;
  // if(type == 1){
  //   for(var i = 0 ; i <dispatchlist.value.length;i++){
  //     if((dispatchlist.value[i] as { id: any }).id== tsk_id.value){
  //         if(i-1>=0){
  //           tsk_id.value = (dispatchlist.value[i-1] as { id: any }).id;
  //         }

  //         if(i-1 == 0){
  //           showBefore.value =1
  //         }else{
  //           showBefore.value = 0;
  //           showNext.value = 0;
  //         }
  //         break;
  //     }
  //   }
  // }else{
  //   for(var i = 0 ; i <dispatchlist.value.length;i++){
  //     if((dispatchlist.value[i] as { id: any }).id== tsk_id.value){
  //       if(i+1 < dispatchlist.value.length){
  //                   tsk_id.value = (dispatchlist.value[i+1] as { id: any }).id;
  //       }

  //         if(i+1 == dispatchlist.value.length){
  //           showNext.value =1;
  //         }else{
  //           showNext.value = 0;
  //           showBefore.value = 0;
  //         }
  //         break;
  //     }
  //   }
  // }
};
async function fetchAllProcedurePages() {
  let allData = [];

  let data = await ProcedureApi.getProcedurePage(queryParams);
	var total = data.total;
  allData.push(...data.list);
  for (var i = 2; i<=(total/99)+1; i++) {
    queryParams.pageNo = i;
    let pageData = await ProcedureApi.getProcedurePage(queryParams);
    allData.push(...pageData.list);
  }
  procedureList.value = allData;
  procedureSelectList.value = allData;
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
/** 查询计算提示 */
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,
		dispatchType: undefined,
		taskId: undefined,
		planId: undefined,
		projectId: undefined,
		projectSubId: undefined,
		bomDetailId: undefined,
		dispatchStatus: undefined,
		remark: undefined,
		status: 1,
		taskDispatchDetails: [],
		operateLogs: [],
		active: undefined,
		activeOpinion: ''
	}
	formRef.value?.resetFields()
}

const subFormLoading = ref(false) // 子表单的加载中
const subFormRules = reactive({
	procedureName: [{
		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 postList = ref([])
const personList = ref([])

const ownerList1 = ref<OwnerListType[]>([]);
  const ownerList2 = ref<OwnerListPostType[]>([]);
const queryData = async (id?: number) => {
	resetForm()
	// 修改时，设置数据
	if (id) {
		formLoading.value = true
		try {
			formData.value = await TaskDispatchApi.getTaskDispatch(id)
			formData.value.taskDispatchDetails = await TaskDispatchApi.getTaskDispatchDetailListByDispatchId(
				id)
        checkList.value = [];
      if(formData.value.taskDispatchDetails!=null){
        formData.value.taskDispatchDetails.forEach(item=>{
          procedureList.value.forEach(items =>{
          if(items.id == item.procedureId){
            checkList.value.push(items.name)
          }
      })
        })
      }
			checkListTemp.value = checkList.value;
      personList.value  = await TaskDispatchApi.getOwnerList(formData.value.ownerId,1);

      postList.value = await TaskDispatchApi.getOwnerList(formData.value.ownerId,2);
      ownerList1.value = await getOwnerListThis ();
      ownerList2.value = await getOwnerPostListThis ();
			formData.value.bomCode = 'BOM-' + formData.value.projectSubCode
			if (formData.value.dispatchStatus == 2 ) {
				detailDisabled.value = true
			}else{
				detailDisabled.value = false
			}

			// 操作日志
			let logParams = {
				pageNo: 1,
				pageSize: 99,
				businessId: id,
				businessType: 'TASK_DISPATCH'
			}
			formData.value.operateLogs = (await getOperateLogPage(logParams)).list
		} finally {
			formLoading.value = 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 == 'SUBMIT') {
		// 	if (!formData.value.taskDispatchDetails || formData.value.taskDispatchDetails.length == 0) {
		// 		message.error('派工明细不能为空')
		// 		return
		// 	}
		// }
		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'||operate == 'SAVE'){
			if (!formData.value.taskDispatchDetails || formData.value.taskDispatchDetails.length == 0) {
				message.error('派工明细不能为空')
				return
			}
			var ownerIsNull = false;
			for(var i = 0 ; i < formData.value.taskDispatchDetails.length ; i++){
				if(formData.value.taskDispatchDetails[i].dispatchType ==2){
					if( formData.value.taskDispatchDetails[i].postId == undefined || formData.value.taskDispatchDetails[i].postId == null ||formData.value.taskDispatchDetails[i].postId == ''){
							message.error('请选择岗位！')
							ownerIsNull = true;
							break;
					}
				}else{
					if( formData.value.taskDispatchDetails[i].owner == undefined || formData.value.taskDispatchDetails[i].owner == null ||formData.value.taskDispatchDetails[i].owner == ''){
							message.error('请选择责任人！')
							ownerIsNull = true;
							break;
					}
				}

			}
			if(ownerIsNull){
				return;
			}
		}
		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)
		queryData(tsk_id.value);

	} finally {
		formLoading.value = false
	}
}
const checkList = ref([])
const checkListTemp = ref([])
/** 新增按钮操作 */
const onAddItem = () => {

		//取消勾选删除逻辑
		//添加时，保留现有的
  if(checkList.value!=null&&checkList.value.length>0){
		checkList.value.forEach(item=>{
			var hasProcedure = false ;
			procedureList.value.forEach(items =>{
          if(items.name == item){
						hasProcedure = true;
          }
      })
			if(hasProcedure == false){
				checkList.value = checkListTemp.value;
				message.error('工序基表中不含或已禁用'+item+'工序,请在工序基表中维护该工序')
				return
			}
		})
		checkListTemp.value = checkList.value;
    var list  = [];
    var i = 1;
		if(formData.value.taskDispatchDetails!=null){
			formData.value.taskDispatchDetails.forEach(item=>{
				if(item.id !=null){
					i ++
					list.push(item);
				}
			})
		}
    checkList.value.forEach(element => {
      const row = {
        id: undefined,
        procedureId: 0 ,
        dispatchType: ref(1),
        sort: 0,
        owner: undefined,
        workTime: undefined,
        amount: undefined,
        summary: undefined,
        status: 1,
        procedureStatus: 0,
				beginProduce:0,
        dispatchId: undefined,
        procedureCode:'' ,
        isReport:0 ,
      }
      // 遍历对象的键
      // Object.keys(procedureList.value).forEach((key) => {
      //   con
      //   if(key == element){
      //     row.procedureId =  procedureList.value[key];
      //   }
      // });
      procedureList.value.forEach(items =>{
          if(items.name == element){
            row.procedureId =  items.id;
            row.procedureCode = items.code
            console.log(items);
            if(items.isReport!= null){
            row.isReport = items.isReport;
            }
          }
      })
			var add = true;
			if(list != null){
				for(var j = 0 ; j < list.length ; j ++){
					if(list[j].id != null &&list[j].procedureId == row.procedureId){
						add = false;
						break;
					}
				}
			}
			if(add){
			row.amount = formData.value.amount
      row.dispatchId = formData.value.id
      list.push(row)
      row.sort = i;
      i++;
			}

    });
    formData.value.taskDispatchDetails = list;
  }else{
    formData.value.taskDispatchDetails = []
  }

}
type OwnerListType = {
  index: number;
  id: number;
  label: string;
};
type OwnerListPostType = {
  index: number;
  id: string;
  label: string;
};
const getOwnerListThis = async (): Promise<OwnerListType[]> => {
  let ownerList: OwnerListType[] = [];
    if(personList.value!=null && personList.value.length >0){
			personList.value.forEach((item, index) => {
      let key = Object.keys(item)[0];
      let value = item[key] as string;
      ownerList.push({ index: index + 1, id: Number(key), label: value });
    });
		}
		return ownerList
}

	const getOwnerPostListThis = async (): Promise<OwnerListPostType[]> => {
  let ownerList1: OwnerListPostType[] = [];
		if(postList.value!=null &&postList.value.length>0){
			postList.value.forEach((item, index) => {
      let key = Object.keys(item)[0];
      let value = item[key] as string;
      ownerList1.push({ index: index + 1, id: key, label: value });
    });
		}

  return ownerList1;
};

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

	// let deletedItems = formData.value.taskDispatchDetails.splice(index, 1)
  var listdetail = ref([]);
/** 删除子项操作 */
const onDeleteItem = async (row,index) => {
  var list = [];
  listdetail.value = [];
  var indexs = 1;
  for(var i = 0 ; i < formData.value.taskDispatchDetails.length ; i++){
      if(i != index){

        formData.value.taskDispatchDetails[i].sort = indexs;
        indexs++;
        listdetail.value.push(formData.value.taskDispatchDetails[i]);
      }
  }

  formData.value.taskDispatchDetails = listdetail.value;
  for(var i = 0 ; i < checkList.value.length ; i++){
      if(i != index){
        list.push(checkList.value[i]);
      }
  }
  checkList.value = list;
	checkListTemp.value = checkList.value;
	let id = row.id
	if (id) await TaskDispatchApi.deleteTaskDispatchDetail(id)
	message.success(t('common.delSuccess'))
}
const handleSelectedProcedure = async (row: any) => {
  console.log(row);
	if (row) {
    procedureList.value.forEach(element => {
      if(row.procedureId == element.id){
        row.procedureCode = element.code
        row.isReport = element.isReport
      }
    });
		// row.procedureId = newValue.id
		// row.procedureCode = newValue.code
		// row.isReport = newValue.isReport
	} else {
		row.procedureId = undefined
		row.procedureCode = undefined
		row.isReport = undefined
	}
}

const totalTaskDispatch = ref(0) // 派工列表的总页数
const getTaskDispatchList = async () => {
  try {
    const data = await TaskDispatchApi.getTaskDispatchPage(dispatchParams.value)
		return data.list;
    // list.value = data.list
    // total.value = data.total
  } finally {
  }
}
// const handleSelectedProcedure = async (row: any, newValue: any) => {
//   console.log(newValue);
// 	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(() => {
// 	dialogTitle.value = t('action.' + active.value)
// 	if ('detail' == active.value) {
// 		detailDisabled.value = true
// 	}

// 	queryData(currentId.value)
// })
</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>
