<template>
	<el-dialog
		v-model="state.dialogVisible"
		draggable
		title="延期批量审批"
		ref="dialogRef"
		@mouseup="mouseup"
		:style="'transform: ' + state.transform + ';'"
		destroy-on-close
		:close-on-click-modal="false"
		@close="close"
		append-to-body
	>
		<el-form :model="state.ruleForm" label-width="110px" ref="ruleFormRef" v-loading="state.loading" :disabled="state.loading">
			<slot name="header"></slot>
			<el-row :gutter="10">
				<!-- 审批流程 -->
				<template v-if="canReject">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="审批结果" prop="isPass" :rules="[{ required: true, message: '请选择审批结果', trigger: 'change' }]">
							<el-radio-group v-model="state.ruleForm.isPass">
								<el-radio :value="true">同意</el-radio>
								<el-radio :value="false">不同意</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<!-- 审批通过 -->
					<template v-if="state.ruleForm.isPass">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="下一环节" prop="nextStepCode" :rules="[{ required: true, message: '请选择下一环节', trigger: 'change' }]">
								<el-select v-model="state.ruleForm.nextStepCode" placeholder="请选择下一环节" class="w100" @change="selectNextStep">
									<el-option v-for="item in state.nextStepOptions" :key="item.key" :label="item.value" :value="item.key" />
								</el-select>
								<!--								<p class="flex-center-align color-danger" v-if="showFastSendOrder">
                                  当前推荐派单办理对象：{{ fastStepName }} <el-button type="primary" link class="ml4" @click="fastSendOrder">快捷派单</el-button>
                                </p>-->
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="showHandlers">
							<el-form-item
								label="办理对象"
								prop="nextHandlers"
								:rules="[{ required: nextHandlersRequired, message: '请选择办理对象', trigger: 'change' }]"
								v-if="showHandlers"
							>
								<el-select-v2
									v-model="state.ruleForm.nextHandlers"
									:options="state.handlerOptions"
									placeholder="请选择办理对象"
									class="w100"
									multiple
									clearable
									collapse-tags
									collapse-tags-tooltip
									filterable
									value-key="key"
									@change="selectHandlers"
									:multiple-limit="multipleLimit"
								/>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="showMainHandler">
							<el-form-item label="主办" prop="nextMainHandler" :rules="[{ required: false, message: '请选择主办', trigger: 'change' }]">
								<el-select v-model="state.ruleForm.nextMainHandler" placeholder="请选择主办" class="w100" filterable>
									<el-option v-for="item in state.handlerMainOptions" :key="item.key" :label="item.value" :value="item.key" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="countersignAble">
							<el-form-item label="发起会签" prop="isStartCountersign" :rules="[{ required: false, message: '请选择发起会签', trigger: 'change' }]">
								<el-switch
									v-model="state.ruleForm.isStartCountersign"
									inline-prompt
									active-text="是"
									inactive-text="否"
									@change="changeStartCountersign"
									:disabled="countersignDisabled"
								/>
							</el-form-item>
						</el-col>
					</template>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="" prop="isSms">
							<el-checkbox v-model="state.ruleForm.isSms" label="短信通知" />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item
							:label="state.inputPlaceholder"
							prop="opinion"
							:rules="[{ required: true, message: `请填写${state.inputPlaceholder}`, trigger: 'blur' }]"
						>
							<common-advice
								@chooseAdvice="chooseAdvice"
								v-model="state.ruleForm.opinion"
								:placeholder="'请填写' + state.inputPlaceholder"
								:loading="state.loading"
								:commonEnum="commonEnum.Delay"
								:maxlength="AppConfigInfo.handleOpinionWordLimit"
							/>
						</el-form-item>
					</el-col>
					<!--					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="附件" :rules="[{ required: false, message: '请填写诉求内容', trigger: 'change' }]">
							<annex-list name="延期附件" :businessId="state.orderDetail.id" classify="延期上传" v-model:format="handleFiles" />
						</el-form-item>
					</el-col>-->
				</template>
				<!-- 办理流程 -->
				<template v-else>
					<el-col v-if="orderContent">
						<el-form-item label="受理内容">
							<text-ellipsis :content="orderContent" :rows="1"> </text-ellipsis>
						</el-form-item>
					</el-col>
					<!-- 非退回流程都需要选择 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="下一环节" prop="nextStepCode" :rules="[{ required: true, message: '请选择下一环节', trigger: 'change' }]">
							<el-select v-model="state.ruleForm.nextStepCode" placeholder="请选择下一环节" class="w100" @change="selectNextStep">
								<el-option v-for="item in state.nextStepOptions" :key="item.key" :label="item.value" :value="item.key" />
							</el-select>
							<!--							<p class="flex-center-align color-danger" v-if="showFastSendOrder">
                              当前推荐派单办理对象：{{ fastStepName }} <el-button type="primary" link class="ml4" @click="fastSendOrder">快捷派单</el-button>
                            </p>-->
						</el-form-item>
					</el-col>
					<!-- 非退回流程都需要选择并且如果选择了结束节点就不需要选择办理对象 -->
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="showHandlers">
						<el-form-item
							label="办理对象"
							prop="nextHandlers"
							:rules="[{ required: nextHandlersRequired, message: '请选择办理对象', trigger: 'change' }]"
						>
							<el-select-v2
								v-model="state.ruleForm.nextHandlers"
								:options="state.handlerOptions"
								placeholder="请选择办理对象"
								class="w100"
								multiple
								clearable
								collapse-tags
								collapse-tags-tooltip
								filterable
								value-key="key"
								@change="selectHandlers"
								:multiple-limit="multipleLimit"
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="showMainHandler">
						<el-form-item label="主办" prop="nextMainHandler" :rules="[{ required: false, message: '请选择主办', trigger: 'change' }]">
							<el-select v-model="state.ruleForm.nextMainHandler" placeholder="请选择主办" class="w100" filterable>
								<el-option v-for="item in state.handlerMainOptions" :key="item.key" :label="item.value" :value="item.key" />
							</el-select>
						</el-form-item>
					</el-col>
					<!-- 工单办理专有参数 -->
					<template v-if="flowDirection">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="办理时限" prop="timeLimit" :rules="[{ required: true, message: '请填写办理时限', trigger: 'blur' }]">
								<el-row :gutter="10">
									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
										<el-input-number
											placeholder="办理时限"
											v-model="state.ruleForm.timeLimit"
											controls-position="right"
											class="w100"
											:min="1"
											:max="99"
											disabled
										></el-input-number>
									</el-col>
									<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-loading="state.loading">
										<el-form-item
											label=""
											label-width="0"
											prop="timeLimitUnit"
											:rules="[{ required: true, message: '请选择办理时限单位', trigger: 'change' }]"
										>
											<el-select v-model="state.ruleForm.timeLimitUnit" placeholder="办理时限单位" disabled style="width: 240px">
												<el-option v-for="item in timeTypeOptions" :value="item.key" :key="item.key" :label="item.value" />
											</el-select>
										</el-form-item>
									</el-col>
								</el-row>
							</el-form-item>
						</el-col>
					</template>
					<!-- 话务部到一级部门  派单组到一级部门	-->
					<template v-if="seatToOrgOne || paidanToOrgOne">
						<el-col :span="24">
							<el-form-item label="派单类型" prop="orderAssignMode" :rules="[{ required: true, message: '请选择派单类型', trigger: 'change' }]">
								<el-radio-group v-model="state.ruleForm.orderAssignMode" @change="selectDispatchType">
									<el-radio :value="0">逐级派单</el-radio>
									<el-radio :value="1">跨级派单</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="state.ruleForm.orderAssignMode === 0">
							<el-form-item label="接办部门" prop="nextHandlers" :rules="[{ required: true, message: '请选择接办部门', trigger: 'change' }]">
								<!--										<el-select v-model="state.ruleForm.paidanObj" placeholder="请选择接办部门" class="w100" filterable multiple>
                  <el-option v-for="item in state.paidanObjOptions" :key="item.key" :label="item.value" :value="item.key" />
                </el-select>-->
								<el-select-v2
									v-model="state.ruleForm.nextHandlers"
									:options="state.handlerOptions"
									placeholder="请选择接办部门"
									class="w100"
									multiple
									clearable
									collapse-tags
									collapse-tags-tooltip
									filterable
									value-key="key"
									@change="selectHandlers"
									:multiple-limit="multipleLimit"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="state.ruleForm.orderAssignMode === 1">
							<el-row class="w100" :gutter="10">
								<el-col>
									<el-form-item label="接办部门" prop="nextHandler" :rules="[{ required: true, message: '请选择接办部门', trigger: 'change' }]">
										<el-select-v2
											v-model="state.ruleForm.nextHandler"
											:options="state.handlerOptions"
											placeholder="请选择接办部门"
											class="w100"
											clearable
											filterable
											value-key="key"
											@change="selectHandlers"
										/>
									</el-form-item>
								</el-col>
								<!-- 二级部门 -->
								<template v-if="showOrgLevelTwo">
									<el-col :span="12">
										<el-form-item label="下一环节" prop="levelTwoStep" :rules="[{ required: false, message: '请选择下一环节', trigger: 'change' }]">
											<el-select-v2
												v-model="state.ruleForm.levelTwoStep"
												:options="levelTwoStepOptions"
												placeholder="请选择下一环节"
												class="w100"
												filterable
												value-key="key"
												clearable
												@change="selectOrgLevelTwo"
											/>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item
											label="办理对象"
											prop="levelTwoHandlers"
											:rules="[{ required: false, message: '请选择办理对象', trigger: 'change' }]"
										>
											<el-select-v2
												v-model="state.ruleForm.levelTwoHandlers"
												:options="levelTwoHandleOptions"
												placeholder="请选择办理对象"
												class="w100"
												clearable
												filterable
												value-key="key"
												multiple
												collapse-tags
												collapse-tags-tooltip
												:max-collapse-tags="1"
												@change="selectOrgLevelTwoHandler"
											/>
										</el-form-item>
									</el-col>
								</template>
								<!-- 三级部门 -->
								<template v-if="showOrgLevelThree">
									<el-col :span="12">
										<el-form-item label="下一环节" prop="levelThreeStep" :rules="[{ required: false, message: '请选择下一环节', trigger: 'change' }]">
											<el-select-v2
												v-model="state.ruleForm.levelThreeStep"
												:options="levelThreeStepOptions"
												placeholder="请选择下一环节"
												class="w100"
												filterable
												value-key="key"
												clearable
												@change="selectOrgLevelThree"
											/>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item
											label="办理对象"
											prop="levelTwoHandlers"
											:rules="[{ required: false, message: '请选择办理对象', trigger: 'change' }]"
										>
											<el-select-v2
												v-model="state.ruleForm.levelThreeHandlers"
												:options="levelThreeHandleOptions"
												placeholder="请选择办理对象"
												class="w100"
												clearable
												filterable
												value-key="key"
												multiple
												collapse-tags
												collapse-tags-tooltip
												:max-collapse-tags="1"
												@change="selectOrgLevelThreeHandler"
											/>
										</el-form-item>
									</el-col>
								</template>
							</el-row>
						</el-col>
					</template>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="countersignAble">
						<el-form-item label="发起会签" prop="isStartCountersign" :rules="[{ required: false, message: '请选择发起会签', trigger: 'change' }]">
							<el-switch
								v-model="state.ruleForm.isStartCountersign"
								inline-prompt
								active-text="是"
								inactive-text="否"
								@change="changeStartCountersign"
								:disabled="countersignDisabled"
							/>
						</el-form-item>
					</el-col>
					<!--  汇总节点需要填写 并且是工单办理 -->
					<template v-if="inputRealHandler">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="经办人" prop="realHandlerName" :rules="[{ required: false, message: '请填写经办人', trigger: 'blur' }]">
								<el-input v-model="state.ruleForm.realHandlerName" placeholder="请填写经办人" clearable> </el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="经办人电话" prop="realHandlerPhone" :rules="[{ required: false, message: '请填写经办人电话', trigger: 'blur' }]">
								<el-input v-model="state.ruleForm.realHandlerPhone" placeholder="请填写办理人电话" 请填写经办人电话> </el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="是否与市民沟通" prop="realIsContacted">
								<el-switch v-model="state.ruleForm.realIsContacted" inline-prompt active-text="是" inactive-text="否" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="是否与市民现场沟通" prop="realContactLocale" label-width="150">
								<el-switch v-model="state.ruleForm.realContactLocale" inline-prompt active-text="是" inactive-text="否" />
							</el-form-item>
						</el-col>
					</template>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="isSmsSelectShow">
						<el-form-item label="" prop="isSms">
							<el-checkbox v-model="state.ruleForm.isSms" label="短信通知" />
						</el-form-item>
					</el-col>
					<!--  选择结束节点时并且是工单办理并且不是中心，显示部门处理结果 -->
					<template v-if="showResult">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="处理结果" prop="isResolved" :rules="[{ required: true, message: '请选择处理结果', trigger: 'change' }]">
								<el-radio-group v-model="state.ruleForm.isResolved">
									<el-radio :value="true">已得到解决</el-radio>
									<el-radio :value="false">未得到解决</el-radio>
								</el-radio-group>
							</el-form-item>
						</el-col>
					</template>
					<!--  选择结束节点时并且是工单办理并且工单来源是110时，显示警情退回 -->
					<template v-if="showPoliceReturn">
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
							<el-form-item label="" prop="isPoliceReturn">
								<el-checkbox v-model="state.ruleForm.isPoliceReturn" label="警情退回" />
							</el-form-item>
						</el-col>
					</template>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item
							:label="state.inputPlaceholder"
							prop="opinion"
							:rules="[{ required: true, message: `请填写${state.inputPlaceholder}`, trigger: 'blur' }]"
						>
							<common-advice
								@chooseAdvice="chooseAdvice"
								v-model="state.ruleForm.opinion"
								:placeholder="'请填写' + state.inputPlaceholder"
								:loading="state.loading"
								:commonEnum="commonEnum.Delay"
								:maxlength="AppConfigInfo.handleOpinionWordLimit"
							/>
						</el-form-item>
					</el-col>
				</template>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="state.loading">办理</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts" name="processApproval">
import { computed, defineAsyncComponent, nextTick, reactive, ref, watch } from 'vue';
import { ElMessage, ElNotification, FormInstance } from 'element-plus';
import other from '@/utils/other';
import { useUserInfo } from '@/stores/userInfo';
import { storeToRefs } from 'pinia';
import { commonEnum } from '@/utils/constants';
import { orderAssignParams, orderTimeConfig } from '@/api/business/order';
import { delayApproveParams } from '@/api/business/delay';
import { useAppConfig } from '@/stores/appConfig';
import { delayApprovalBatch } from '@/api/todo/delay';

// 引入组件
const CommonAdvice = defineAsyncComponent(() => import('@/components/CommonAdvice/index.vue')); // 常用意见
const TextEllipsis = defineAsyncComponent(() => import('@/components/TextEllipsis/index.vue'));
// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 弹窗显示隐藏
	ruleForm: {
		isPass: true, // 审批结果
		//流程表单
		opinion: '', // 意见
		nextStepCode: '', // 下一节点
		nextStepName: '', // 下一节点名称
		backToCountersignEnd: false, // 是否回到会签结束节点
		nextHandlers: [], // 下一节点办理对象
		nextMainHandler: '', // 主办人
		isSms: false, // 是否短信通知
		isStartCountersign: false, // 是否发起会签
		stepId: null, // 步骤id
		// isTransferHandle:false, // 是否转办
		orderAssignMode: 0, // 派单类型默认逐级派单
	},
	delayForm: {
		//延期申请表单
		timeLimitCount: null, // 延期申请数量
		content: '', // 延期申请理由
		timeLimitUnit: 2, // 延期申请单位 默认工作日
	},
	discernForm: {
		// 甄别表单
		content: '', // 甄别理由
	},
	redoForm: {
		// 重办表单
		content: '', // 重办理由
	},
	terminateForm: {
		//终止表单
		content: '', // 终止理由
	},
	nextStepOptions: [], // 下一节点
	handlerOptions: [], // 办理对象
	transform: 'translate(0px, 0px)', // 滚动条位置
	loading: false, // 提交按钮loading
	workflowId: '', // 流程id
	handlerClassifies: [], //撤回办理对象
	handlerMainOptions: [], // 主办人
	handleId: '', // 流程处理ID
	inputPlaceholder: '办理意见', // 意见提示
	orderDetail: {}, // 工单详情
});
const ruleFormRef = ref<RefType>(); //表单组件
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo); // 用户信息
const appConfigStore = useAppConfig();
const { AppConfigInfo } = storeToRefs(appConfigStore); // 系统配置信息

// 打开弹窗
const delayWithStepIds = ref<EmptyArrayType>([]);
const openDialog = async (val: any) => {
	selectNext.value = {};
	currentParams.value = {};
	state.ruleForm.nextHandlers = [];
	state.ruleForm.nextHandler = {};
	isSmsSelectShow.value = false;
	state.ruleForm.isSms = false;
	state.loading = true;
	state.dialogVisible = true;
	try {
		delayWithStepIds.value = val.map((item: any) => {
			return {
				stepId: item.stepId,
				delayId: item.id,
			};
		});
		state.ruleForm.workflowId = state.workflowId = val[0].workflowId ?? ''; // 流程id 默认取第一个
		state.orderDetail = val[0].order ?? {}; // 工单详情

		// 延期审批
		const [nextResponseDelayAudit] = await Promise.all([delayApproveParams(state.workflowId)]); //获取延期审批流程参数
		handleResult(nextResponseDelayAudit);

		await nextTick(() => {
			restForm(ruleFormRef.value);
		});
	} finally {
		state.loading = false;
	}
};
const canReject = ref<boolean>(false); // 是否可以驳回
const timeTypeOptions = ref<EmptyArrayType>([]); // 办理时限单位
const canStartCountersign = ref<boolean>(false); // 是否可以发起会签
const isMainHandlerShow = ref<boolean>(false); // 是否展示主办人
const currentParams = ref<EmptyObjectType>({}); // 当前获取到的参数（当前节点信息）
const orderContent = ref<string>(''); // 受理内容
const handleResult = (res: any) => {
	currentParams.value = res.result; // 当前获取到的参数（当前节点信息）
	state.nextStepOptions = res.result.steps; //办理对象选择内容
	canReject.value = res.result.canReject ?? false; // 是否可以驳回
	timeTypeOptions.value = res.result.timeTypeOptions ?? []; // 办理时限申请单位
	canStartCountersign.value = res.result.canStartCountersign ?? false; // 是否可以发起会签
	isMainHandlerShow.value = res.result.isMainHandlerShow ?? false; // 是否展示主办人
	orderContent.value = res.result.content ?? ''; // 受理内容
	if (state.nextStepOptions.length === 1) {
		// 下一节点是否只有一个 默认选中第一个
		setTimeout(() => {
			state.ruleForm.nextStepCode = state.nextStepOptions[0].key; // 下一节点code
			state.ruleForm.nextStepName = state.nextStepOptions[0].value; // 下一节点name
			state.ruleForm.backToCountersignEnd = state.nextStepOptions[0].backToCountersignEnd ?? false; // 是否回到会签结束节点
		}, 100);
		selectNextStep(state.nextStepOptions[0].key); // 查询流程下一节点参数
	} else {
		state.ruleForm.nextStepCode = '';
		state.ruleForm.nextStepName = '';
	}
	if (res.result.opinion) {
		// 如果有汇总意见没有临时保存 取汇总意见 临时保存会覆盖汇总意见
		setTimeout(() => {
			state.ruleForm.opinion = res.result.opinion;
		}, 100);
	}
	state.ruleForm.stepId = res.result.stepId;
	state.loading = false;
};
// 流程选择下一环节
// 先确定当前环节是那一步
/*
 * currentParams.value.currentStepBusinessType 表示当前节点到哪一步 0坐席 1派单 2部门节点 3部门领导节点
 * */
/*selectNext.value.businessType 表示选择节点到哪一步  0 坐席 1派单  2部门节点  3部门领导节点
 * selectNext.value.orgLevel 表示部门等级 1 一级部门 2 二级部门 3 三级部门 4 四级部门
 * selectNext.value.stepType  0普通节点 3汇总节点
 * */
// 话务部到派单组
const seatTopaidan = computed(() => {
	return currentParams.value.currentStepBusinessType === 0 && selectNext.value.businessType === 1;
});
// 话务部到一级部门
const seatToOrgOne = computed(() => {
	return currentParams.value.currentStepBusinessType === 0 && selectNext.value.businessType === 2 && selectNext.value.orgLevel === 1;
});
// 派单组到一级部门
const paidanToOrgOne = computed(() => {
	return currentParams.value.currentStepBusinessType === 1 && selectNext.value.businessType === 2 && selectNext.value.orgLevel === 1;
});
// 是否展示短信通知选择
const isSmsSelectShow = ref(false);
// 办理对象是否必填  0-角色 1-部门类型 2-部门类型 3-指定用户 4-指定部门
const nextHandlersRequired = ref<Boolean>(false);
const selectNext = ref<EmptyObjectType>({}); // 选择的下一个节点
const selectNextStep = (val: any) => {
	ruleFormRef.value?.resetFields('nextHandlers');
	ruleFormRef.value?.resetFields('nextMainHandler');
	state.ruleForm.nextHandlers = [];
	const next = state.nextStepOptions.find((item: any) => item.key === val);
	selectNext.value = next;
	const items = next.items; //获取下一节点
	state.ruleForm.nextStepName = next.value; // 下一节点name
	state.ruleForm.handlerType = next.handlerType;
	state.ruleForm.businessType = next.businessType;
	state.ruleForm.flowDirection = next.flowDirection;
	state.ruleForm.backToCountersignEnd = next.backToCountersignEnd ?? false; // 是否回到会签结束节点
	state.handlerOptions = items ?? [];
	state.handlerOptions = state.handlerOptions.map((item: any) => {
		return {
			value: {
				...item,
			},
			label: item.value,
		};
	});
	if (items.length === 1) {
		// 如果办理对象只有一个默认选中
		state.ruleForm.nextHandlers = [items[0]];
	}
	// 办理对象是否必填
	nextHandlersRequired.value = ![0].includes(next.handlerType);

	// 以下是默认需要吧短信勾上的场景 话务部到一级部门 派单组到一级部门
	state.ruleForm.isSms = seatToOrgOne.value || paidanToOrgOne.value;
	// 是否展示短信通知 (取消坐席流转至“派单组”时的短信通知选项框  )
	isSmsSelectShow.value = !seatTopaidan.value;
};

//  会签是否可用 (配置可以会签 并且选择的是逐级派单，并且是普通节点 并且选择是部门)
const countersignAble = computed(() => {
	return canStartCountersign.value && state.ruleForm.orderAssignMode === 0 && selectNext.value.stepType === 0 && selectNext.value.businessType === 2;
});
// 办理对象是否能够选择多个(可以发起会签可以选择多个，不能发起会签只能选择一个) 加个判断 选择的下一环节必须是部门（会签必须是选择的部门）
const multipleLimit = computed(() => {
	return canStartCountersign.value && selectNext.value.businessType === 2 ? 0 : 1;
});
watch(
	() => state.ruleForm.nextHandlers, // 监听办理对象 多个办理对象自动发起会签
	(val) => {
		state.ruleForm.isStartCountersign = val.length > 1;
	}
);
const countersignDisabled = computed(() => {
	// (选中的办理对象如果是一个) 因为是disabled 所以这里取反
	return !(state.ruleForm.nextHandlers.length === 1);
});
// 是否发起会签
const changeStartCountersign = () => {};

// 是否展示办理对象 (结束节点不展示: next.stepType===2 表示为结束节点,下一环节为派单组时 next.businessType === 1，办理对象下拉框隐藏:AppConfigInfo.value.isAverageSendOrder= true 表示开启了平均派单 )
const showHandlers = computed(() => {
	const next = state.nextStepOptions.find((item: any) => item.key === state.ruleForm.nextStepCode);
	// const isAverageSendOrder = AppConfigInfo.value.isAverageSendOrder && next?.businessType === 1; // 开启平均派单并且下一个环节是派单组  !isAverageSendOrder
	if (!next) return true;
	// 话务部到派单 派单组到一级部门 也不需要展示办理对象 如果下一环节是汇总节点与不需要展示办理
	return next?.stepType !== 2 && !(seatToOrgOne.value || paidanToOrgOne.value) && selectNext.value.stepType !== 3;
});
// 是否展示部门处理结果 （ 选择结束节点时并且当前操作人不是中心时，显示部门处理结果 ）
const showResult = computed(() => {
	const next = state.nextStepOptions.find((item: any) => item.key === state.ruleForm.nextStepCode);
	return next?.stepType === 2 && !userInfos.value.isCenter;
});
// 是否展示警情退回 (选择结束节点时并且工单来源是110时，显示警情退回)
const showPoliceReturn = computed(() => {
	const next = state.nextStepOptions.find((item: any) => item.key === state.ruleForm.nextStepCode);
	return next?.stepType === 2 && state.orderDetail?.source === 200;
});
// 是否是汇总节点（汇总需要填入其他参数）并且是工单办理
const inputRealHandler = computed(() => {
	const next = state.nextStepOptions.find((item: any) => item.key === state.ruleForm.nextStepCode);
	return next?.inputRealHandler;
});
// 是否展示办理时限 flowDirection 并且是工单办理
const flowDirection = computed(() => {
	const next = state.nextStepOptions.find((item: any) => item.key === state.ruleForm.nextStepCode);
	if (!next) return false;
	return [0, 1].includes(next.flowDirection);
});
// 计算期满时间
watch(
	() => flowDirection.value,
	(val) => {
		if (val) {
			const next = state.nextStepOptions.find((item: any) => item.key === state.ruleForm.nextStepCode);
			state.ruleForm.flowDirection = next.flowDirection;
			orderTimeConfig({ flowDirection: next.flowDirection, acceptTypeCode: state.orderDetail.acceptTypeCode }).then((res: any) => {
				state.ruleForm.timeLimit = res.result.count ?? null; // 办理时限
				state.ruleForm.timeLimitUnit = res.result.timeType ?? ''; // 办理时限单位
			});
		}
	}
);

// 是否展示主办
const showMainHandler = computed(() => {
	return state.ruleForm.nextHandlers.length > 1 && isMainHandlerShow.value;
});
// 主办从办理对象中选择
state.handlerMainOptions = computed(() => {
	return state.ruleForm.nextHandlers;
});

// 选择派单类型 需要清空选择的内容
const selectDispatchType = () => {
	ruleFormRef.value.resetFields('nextHandlers');
	ruleFormRef.value.resetFields('nextHandler');
	state.ruleForm.nextHandlers = [];
	state.ruleForm.nextHandler = null;
	state.ruleForm.isStartCountersign = false;
	showOrgLevelTwo.value = false;
	state.ruleForm.levelTwoStep = null;
	levelTwoStepOptions.value = [];
	levelTwoHandleOptions.value = [];
	state.ruleForm.levelTwoHandlers = [];
	showOrgLevelThree.value = false;
	state.ruleForm.levelThreeStep = null;
	state.ruleForm.levelThreeHandlers = [];
	levelThreeStepOptions.value = [];
	levelThreeHandleOptions.value = [];
};

// 选择办理对象
const showOrgLevelTwo = ref(false); // 是否展示二级部门选择
const levelTwoStepOptions = ref<EmptyArrayType>([]); // 二级部门节点
const levelTwoHandleOptions = ref<EmptyArrayType>([]); // 二级部门办理参数
const selectHandlers = () => {
	if (state.ruleForm.nextHandlers && state.ruleForm.nextHandlers.length > 1) {
		// AppConfigInfo.value.noSignOrgCode  对应的办理对象不能参与会签
		const isProvince12345 = state.ruleForm.nextHandlers.find((item: any) => AppConfigInfo.value.noSignOrgCode.includes(item.key));
		if (isProvince12345) {
			// 如果选择了省12345平台或者省12345交办就提示不能参与会签 并且从选择中移除
			ElMessage({
				message: '省12345平台和省12345交办不能参与会签',
				grouping: true,
			});
			state.ruleForm.nextHandlers = state.ruleForm.nextHandlers.filter((item: any) => !AppConfigInfo.value.noSignOrgCode.includes(item.key));
		}
	}
	if (state.ruleForm.nextHandlers && state.ruleForm.nextHandlers.length <= 1) {
		// 如果只有一个办理对象就不需要发起会签
		state.ruleForm.isStartCountersign = false;
	}
	if ((seatToOrgOne.value || paidanToOrgOne.value) && state.ruleForm.orderAssignMode === 1) {
		showOrgLevelTwo.value = false;
		state.ruleForm.levelTwoStep = null;
		levelTwoStepOptions.value = [];
		levelTwoHandleOptions.value = [];
		state.ruleForm.levelTwoHandlers = [];
		showOrgLevelThree.value = false;
		state.ruleForm.levelThreeStep = null;
		state.ruleForm.levelThreeHandlers = [];
		levelThreeStepOptions.value = [];
		levelThreeHandleOptions.value = [];
		state.ruleForm.nextHandlers = [state.ruleForm.nextHandler];
		// 话务部到一级部门 派单组到一级部门 并且是跨级派单 需要查询下一级部门
		const request = {
			WorkflowId: state.ruleForm.workflowId,
			StepCode: selectNext.value.key,
			StepType: selectNext.value.stepType,
			BusinessType: selectNext.value.businessType,
			HandlerType: selectNext.value.handlerType,
			OrgIds: state.ruleForm.nextHandler ? [state.ruleForm.nextHandler.key] : [],
		};
		orderAssignParams(request).then((res: any) => {
			showOrgLevelTwo.value = true;
			levelTwoStepOptions.value = res.result.steps.map((item: any) => {
				return {
					value: {
						...item,
					},
					label: item.value,
				};
			});
			if (res.result.steps.length === 1) {
				state.ruleForm.levelTwoStep = res.result.steps[0];
				levelTwoHandleOptions.value = state.ruleForm.levelTwoStep.items.map((item: any) => {
					return {
						value: {
							...item,
						},
						label: item.value,
					};
				});
			}
		});
	} else {
		showOrgLevelTwo.value = false;
	}
};
// 选择二级部门节点
const selectOrgLevelTwo = (val: any) => {
	if (val) {
		levelTwoHandleOptions.value = state.ruleForm.levelTwoStep.items.map((item: any) => {
			return {
				value: {
					...item,
				},
				label: item.value,
			};
		});
	} else {
		levelTwoHandleOptions.value = [];
		state.ruleForm.levelTwoHandlers = [];
		state.ruleForm.levelThreeHandlers = [];
		levelThreeStepOptions.value = [];
		levelThreeHandleOptions.value = [];
		showOrgLevelThree.value = false;
	}
};
const showOrgLevelThree = ref(false);
const levelThreeStepOptions = ref<EmptyArrayType>([]); // 三级部门节点
const levelThreeHandleOptions = ref<EmptyArrayType>([]); // 三级部门办理参数
// 选择二级部门办理对象 展示三级办理对象和节点
const selectOrgLevelTwoHandler = (val: any) => {
	const ids = val.map((item: any) => item.key);
	if (val && val.length) {
		const request = {
			WorkflowId: state.ruleForm.workflowId,
			StepCode: state.ruleForm.levelTwoStep.key,
			StepType: state.ruleForm.levelTwoStep.stepType,
			BusinessType: state.ruleForm.levelTwoStep.businessType,
			HandlerType: state.ruleForm.levelTwoStep.handlerType,
			OrgIds: ids,
		};
		orderAssignParams(request).then((res: any) => {
			showOrgLevelThree.value = true;
			levelThreeStepOptions.value = res.result.steps.map((item: any) => {
				return {
					value: {
						...item,
					},
					label: item.value,
				};
			});
			if (res.result.steps.length === 1) {
				state.ruleForm.levelThreeStep = res.result.steps[0];
				levelThreeHandleOptions.value = state.ruleForm.levelThreeStep.items.map((item: any) => {
					return {
						value: {
							...item,
						},
						label: item.value,
					};
				});
			}
		});
	} else {
		state.ruleForm.levelThreeHandlers = [];
		levelThreeStepOptions.value = [];
		levelThreeHandleOptions.value = [];
		showOrgLevelThree.value = false;
	}
};
// 选择三级部门节点
const selectOrgLevelThree = (val: any) => {
	if (val) {
		levelThreeHandleOptions.value = state.ruleForm.levelThreeStep.items.map((item: any) => {
			return {
				value: {
					...item,
				},
				label: item.value,
			};
		});
	} else {
		state.ruleForm.levelThreeHandlers = [];
		levelThreeHandleOptions.value = [];
	}
};
const selectOrgLevelThreeHandler = () => {};

// 设置抽屉
const dialogRef = ref<RefType>();
const mouseup = () => {
	state.transform = dialogRef.value.dialogContentRef.$el.style.transform;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
// 重置表单方法
const restForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	state.ruleForm.opinion = '';
	state.delayForm.endTime = '';
	formEl.resetFields();
	formEl.clearValidate();
};
// 选择常用意见 填入填写框 办理
const chooseAdvice = (item: any) => {
	state.ruleForm.opinion += item.content;
};
const close = () => {
	restForm(ruleFormRef.value);
	orderContent.value = '';
};
// 办理
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		let submitObj = other.deepClone(state.ruleForm);
		if (submitObj.nextHandlers && submitObj.nextHandlers.length) {
			if (submitObj.nextHandlers.length === 1) {
				submitObj.nextMainHandler = submitObj.nextHandlers[0].key;
			}
		}
		const request = {
			nextWorkflow: submitObj,
			delayWithStepIds: delayWithStepIds.value,
			isPass: state.ruleForm.isPass,
		};
		delayApprovalBatch(request)
			.then((res: any) => {
				emit('updateList');
				state.loading = false;
				closeDialog();
			})
			.catch((err: any) => {
				console.log(err, 'err');
				emit('updateList');
				closeDialog();
			});
	});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
<style lang="scss">
.modal_class {
	pointer-events: none;
	height: 100%;
}
.dialog_class {
	pointer-events: auto;
	flex-direction: column;
	margin: 0 !important;
	position: absolute;
	top: 20%;
	left: 25%;
}
</style>
