<template>
	<div class="order-add-container layout-padding">
		<el-row :gutter="15" class="h100">
			<!-- 左边工单信息 -->
			<el-col :span="12" class="left-content mb20 h100" v-loading="state.formLoading">
				<el-scrollbar class="h100" noresize>
					<el-card shadow="never">
						<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="110px" label-position="right" scroll-to-error>
							<p class="border-title mb10">来电信息</p>
							<el-row :gutter="0">
								<!-- 来源渠道 -->
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<!-- 手动创建 -->
									<template v-if="state.createBy === 'manual'">
										<el-form-item label="来源渠道" prop="channel" :rules="[{ required: true, message: '请选择来源渠道', trigger: 'change' }]">
											<el-select
												v-model="state.ruleForm.channel"
												placeholder="请选择来源渠道"
												class="w100"
												clearable
												value-key="dicDataValue"
												@change="
													(val) => {
														ruleFormRef.resetFields('fromPhone');
														state.ruleForm.fromPhone = null;
														state.ruleForm.sourceChannel = val.dicDataName;
														state.ruleForm.sourceChannelCode = val.dicDataValue;
													}
												"
											>
												<el-option v-for="item in state.channelOptions" :value="item" :key="item.dicDataValue" :label="item.dicDataName" />
											</el-select>
										</el-form-item>
									</template>
									<!-- 来电弹单 -->
									<template v-if="state.createBy === 'tel'">
										<el-form-item label="来源渠道" prop="channel">
											<el-select v-model="state.ruleForm.channel" placeholder="请选择来源渠道" class="w100" value-key="dicDataValue" disabled>
												<el-option v-for="item in state.channelOptions" :value="item" :key="item.dicDataValue" :label="item.dicDataName" />
											</el-select>
										</el-form-item>
									</template>
									<!-- 互联网来信 -->
									<template v-if="state.createBy === 'letter'">
										<el-form-item label="来源渠道" prop="channel">
											互联网来信
											<span>[{{ state.ruleForm.channel }}]</span>
										</el-form-item>
									</template>
								</el-col>
								<!-- 转接来源 -->
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<!-- 手动创建 -->
									<template v-if="state.createBy === 'manual'">
										<el-form-item label="转接来源" prop="transferPhone"> 暂无 </el-form-item>
									</template>
									<!-- 来电弹单 -->
									<template v-if="state.createBy === 'tel'">
										<el-form-item label="转接来源" prop="transferPhone">
											<span>[{{ state.ruleForm.transferPhone }}]</span>
										</el-form-item>
									</template>
									<!-- 互联网来信 -->
									<template v-if="state.createBy === 'letter'">
										<el-form-item label="转接来源" prop="transferPhone">
											<span>[{{ state.ruleForm.transferPhone }}]</span>
										</el-form-item>
									</template>
								</el-col>
								<!-- 来电号码 -->
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="state.ruleForm.sourceChannelCode === 'RGDH'">
									<!-- 手动创建 -->
									<template v-if="state.createBy === 'manual'">
										<el-form-item
											label="来电号码"
											prop="fromPhone"
											:rules="[
												{ required: true, message: '请填写来电号码', trigger: 'blur' },
												{
													pattern: /^((0\d{2,3}(-)?\d{7,8})|(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8})$/,
													message: '来电号码格式错误',
													trigger: 'blur',
												},
											]"
										>
											<el-input v-model="state.ruleForm.fromPhone" placeholder="请填写来电号码" clearable> </el-input>
										</el-form-item>
									</template>
									<!-- 来电弹单 -->
									<template v-if="state.createBy === 'tel'">
										<el-form-item label="来电号码" prop="fromPhone">
											<el-input v-model="state.ruleForm.fromPhone" placeholder="请填写来电号码"> </el-input>
										</el-form-item>
									</template>
									<!-- 互联网来信 -->
									<template v-if="state.createBy === 'letter'">
										<el-form-item label="来电号码">
											<span>[{{ state.ruleForm.fromPhone }}]</span>
										</el-form-item>
									</template>
								</el-col>
								<!-- 服务坐席 -->
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item label="服务坐席">
										<!-- 手动创建 -->
										<template v-if="state.createBy === 'manual'">
											<span
												>{{ state.ruleForm.acceptorName }}
												<span v-if="state.ruleForm.acceptorStaffNo">[{{ state.ruleForm.acceptorStaffNo }}]</span></span
											>
										</template>
										<!-- 来电弹单 -->
										<template v-if="state.createBy === 'tel'">
											<span
												>{{ state.ruleForm.acceptorName }}
												<span v-if="state.ruleForm.acceptorStaffNo">[{{ state.ruleForm.acceptorStaffNo }}]</span></span
											>
										</template>
										<!-- 互联网来信 -->
										<template v-if="state.createBy === 'letter'">
											<span>[{{ telStatusInfo.telsNo }}]</span>
										</template>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item label="来电人姓名" prop="fromName" :rules="[{ required: true, message: '请填写来电人姓名', trigger: 'blur' }]">
										<el-row :gutter="10">
											<el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
												<el-input v-model="state.ruleForm.fromName" placeholder="请填写来电人姓名" clearable> </el-input>
											</el-col>
											<el-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
												<el-checkbox v-model="state.ruleForm.isSecret" label="保密" />
											</el-col>
										</el-row>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item label="来电人性别" prop="fromGender" :rules="[{ required: true, message: '请选择来电人性别', trigger: 'change' }]">
										<el-radio-group v-model="state.ruleForm.fromGender">
											<el-radio :label="item.key" v-for="item in state.genderOptions" :key="item.key">{{ item.value }}</el-radio>
										</el-radio-group>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item label="来电人身份" prop="identityType" :rules="[{ required: true, message: '请选择来电人身份', trigger: 'change' }]">
										<el-radio-group v-model="state.ruleForm.identityType" @change="selectIdentity">
											<el-radio :label="item.key" v-for="item in state.identityTypeOptions" :key="item.key">{{ item.value }}</el-radio>
										</el-radio-group>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item label="证件类型" prop="licenceTypeObj" :rules="[{ required: false, message: '请选择证件类型', trigger: 'change' }]">
										<el-select
											v-model="state.ruleForm.licenceTypeObj"
											placeholder="请选择证件类型"
											class="w100"
											clearable
											value-key="dicDataValue"
											@change="(val:any) => {
											state.ruleForm.licenceType = val.dicDataName;
											state.ruleForm.licenceTypeCode = val.dicDataValue
										}"
										>
											<el-option v-for="item in state.licenceTypeOptions" :key="item.dicDataValue" :label="item.dicDataName" :value="item" />
										</el-select>
									</el-form-item>
								</el-col>
								<!-- 若“证件类型”有值，则证件号码必填 -->
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item
										label="证件号码"
										prop="licenceNo"
										:rules="[
											{ required: state.ruleForm.licenceTypeCode, message: '请填写证件号码', trigger: 'blur' },
											{
												pattern: licenceNoPattern,
												message: '证件号码格式错误',
												trigger: 'blur',
											},
										]"
									>
										<el-input v-model="state.ruleForm.licenceNo" placeholder="请填写证件号码" clearable> </el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item label="年龄段" prop="ageRangeObj" :rules="[{ required: false, message: '请选择年龄段', trigger: 'change' }]">
										<el-select
											v-model="state.ruleForm.ageRangeObj"
											placeholder="请选择年龄段"
											class="w100"
											clearable
											value-key="dicDataValue"
											@change="(val:any) => {
											state.ruleForm.ageRange = val.dicDataName;
											state.ruleForm.ageRangeCode = val.dicDataValue
										}"
										>
											<el-option v-for="item in state.ageRangeOptions" :key="item.dicDataValue" :label="item.dicDataName" :value="item" />
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item
										label="联系电话"
										prop="contact"
										:rules="[
											{ required: true, message: '请填写联系电话', trigger: 'blur' },
											{
												pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
												message: '联系电话格式错误',
												trigger: 'blur',
											},
										]"
									>
										<el-row :gutter="9">
											<el-col :xs="24" :sm="24" :md="24" :lg="16" :xl="16">
												<el-input v-model="state.ruleForm.contact" placeholder="请填写联系电话" @blur="searchHistory" clearable> </el-input>
											</el-col>
											<el-col :xs="24" :sm="24" :md="24" :lg="8" :xl="8">
												<el-checkbox v-model="state.ruleForm.acceptSms" label="受理短信" />
											</el-col>
										</el-row>
									</el-form-item>
								</el-col>
								<!-- 当“来电/信人身份”为“企业”时必填 -->
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item
										label="企业名称"
										prop="enterpriseName"
										:rules="[{ required: state.ruleForm.identityType === 2, message: '请填写企业名称', trigger: 'blur' }]"
									>
										<el-input v-model="state.ruleForm.enterpriseName" placeholder="请输入企业名称" clearable> </el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item
										label="专班名称"
										prop="zhuanBanMingCheng"
										:rules="[{ required: state.ruleForm.identityType === 2, message: '请填写专班名称', trigger: 'blur' }]"
									>
										<el-input v-model="state.ruleForm.zhuanBanMingCheng" placeholder="请填写专班名称" clearable>
											<template #append>
												<el-button type="primary" @click="handleSelect"><SvgIcon name="ele-Search" class="mr4" /> 查询企业</el-button>
											</template>
										</el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<p class="border-title mb10">诉求信息</p>
							<el-row>
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="state.ruleForm.no">
									<el-form-item label="工单编码">
										{{ state.ruleForm.no }} <span v-if="state.ruleForm?.password">【{{ state.ruleForm.password }}】</span>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item label="拓展信息">
										<el-button @click="showExpandForm" :loading="extraLoading">
											<SvgIcon name="ele-CirclePlus" class="mr3" size="16px" /> 拓展信息
										</el-button>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item label="受理类型" prop="acceptTypeObj" :rules="[{ required: true, message: '请选择受理类型', trigger: 'change' }]">
										<el-select
											v-model="state.ruleForm.acceptTypeObj"
											placeholder="请选择受理类型"
											class="w100"
											value-key="dicDataValue"
											@change="
												(val) => {
													state.ruleForm.acceptType = val.dicDataName;
													state.ruleForm.acceptTypeCode = val.dicDataValue;
												}
											"
										>
											<el-option
												v-for="item in state.acceptTypeOptions"
												:key="item.dicDataValue"
												:disabled="item.disabled"
												:label="item.dicDataName"
												:value="item"
											/>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item label="紧急程度" prop="emergencyLevel" :rules="[{ required: true, message: '请选择紧急程度', trigger: 'change' }]">
										<el-select v-model="state.ruleForm.emergencyLevel" placeholder="请选择紧急程度" class="w100">
											<el-option v-for="item in state.emergencyLevelOptions" :key="item.key" :label="item.value" :value="item.key" />
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item label="推送分类" prop="pushTypeObj" :rules="[{ required: false, message: '请选择推送分类', trigger: 'change' }]">
										<el-select
											v-model="state.ruleForm.pushTypeObj"
											placeholder="请选择推送分类"
											class="w100"
											clearable
											value-key="dicDataValue"
											@change="(val:any) => {
											state.ruleForm.pushType = val.dicDataName;
											state.ruleForm.pushTypeCode = val.dicDataValue
										}"
										>
											<el-option v-for="item in state.pushTypeOptions" :key="item.dicDataValue" :label="item.dicDataName" :value="item" />
										</el-select>
									</el-form-item>
								</el-col>
								<!-- 宜宾特殊需求，新增一个事件分类可以自行维护（辅助功能-事件分类管理） -->
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="AppConfigInfo.isCustomEvent">
									<el-form-item label="事件分类" prop="eventCategoryId" :rules="[{ required: true, message: '请选择事件分类', trigger: 'change' }]">
										<hot-spot-select
											v-model="state.ruleForm.eventCategoryId"
											class="w100"
											:externalArr="state.eventCategoryExternal"
											@choose="chooseEvent"
											type="event"
											placeholder="请选择事件分类"
											clearable
										/>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
									<el-form-item label="热点分类" prop="hotspotId" :rules="[{ required: true, message: '请选择热点分类', trigger: 'change' }]">
										<hot-spot-select
											v-model="state.ruleForm.hotspotId"
											class="w100"
											:externalArr="state.hotspotExternal"
											@choose="chooseHotSpot"
											placeholder="请选择热点分类"
											clearable
										/>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item label="事发时间" prop="incidentTime" :rules="[{ required: false, message: '请选择事发时间', trigger: 'change' }]">
										<el-date-picker
											v-model="state.ruleForm.incidentTime"
											type="datetime"
											placeholder="请选择事发时间"
											value-format="YYYY-MM-DD[T]HH:mm:ss"
											class="w100"
										/>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item label="事件目的" prop="incidentPurpose" :rules="[{ required: false, message: '请填写事件目的', trigger: 'blur' }]">
										<el-input v-model="state.ruleForm.incidentPurpose" placeholder="请填写事件目的" clearable> </el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
									<el-row :gutter="0">
										<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
											<el-form-item
												label="事发地址"
												prop="areaCode"
												:rules="[{ required: true, message: '请选择事发地址', trigger: 'change' }]"
												v-loading="addressLoading"
											>
												<el-cascader
													:options="state.areaOptions"
													filterable
													:props="{ value: 'id', label: 'areaName', emitPath: false, checkStrictly: true }"
													placeholder="请选择事发地址"
													class="w100"
													v-model="state.ruleForm.areaCode"
													ref="areaRef"
													@change="changeArea"
												>
												</el-cascader>
											</el-form-item>
										</el-col>
										<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
											<el-form-item
												label=""
												prop="street"
												:rules="[{ required: false, message: '请填写详细地址', trigger: 'blur' }]"
												label-width="10px"
												class="w100 flex"
											>
												<el-col :xs="24" :sm="24" :md="24" :lg="16" :xl="16">
													<el-input v-model="state.ruleForm.street" placeholder="请填写详细地址" clearable> </el-input>
												</el-col>
												<el-col :xs="24" :sm="24" :md="24" :lg="7" :xl="7" :offset="1">
													<el-button type="primary" link @click="selectLocation"><SvgIcon name="ele-Location" size="16px" /> 地图定位</el-button>
												</el-col>
											</el-form-item>
										</el-col>
										<div v-if="showRepeatEvent" class="color-danger mb10" style="margin-left: 110px">
											【{{ state.ruleForm.address }}】下存在多起【{{ state.ruleForm.hotspotSpliceName }}】事件，点击前往查看或右侧添加重复性事件
											<el-button type="primary" link style="padding: 0 0 3px" @click="onRepeatEvent"> 查看详情</el-button>
										</div>
									</el-row>
								</el-col>

								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
									<el-row :gutter="0">
										<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
											<el-form-item label="是否重复" prop="isRepeat" :rules="[{ required: true, message: '请选择是否重复', trigger: 'change' }]">
												<el-select v-model="state.ruleForm.isRepeat" placeholder="请选择是否重复" class="w100" @change="isRepeatChange">
													<el-option v-for="item in state.repeatOptions" :key="item.key" :label="item.value" :value="item.key" />
												</el-select>
											</el-form-item>
										</el-col>
										<!-- 必填，若“是否重复”为“是”，则展示重复件选择框 -->
										<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="state.ruleForm.isRepeat === 'true'">
											<el-form-item
												label=""
												prop="duplicateTitle"
												label-width="10px"
												:rules="[{ required: true, message: '请选择重复件', trigger: 'change' }]"
											>
												<el-input v-model="state.ruleForm.duplicateTitle" placeholder="请选择重复件" readonly>
													<template #suffix>
														<el-button link type="danger" v-if="state.ruleForm.duplicateTitle" @click="clearRepeat" title="清除历史工单">
															<SvgIcon name="ele-Delete" size="16px" />
														</el-button>
														<el-button link type="primary" class="ml1" @click="selectRepeat" title="选择历史工单">
															<SvgIcon name="iconfont icon-tianjiatuozhanxinxi" size="18px" />
														</el-button>
													</template>
												</el-input>
											</el-form-item>
										</el-col>
									</el-row>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
									<el-form-item label="工单标题" prop="title" :rules="[{ required: true, message: '请填写工单标题', trigger: 'blur' }]">
										<el-input v-model="state.ruleForm.title" placeholder="请填写工单标题" clearable @input="inputTitle"> </el-input>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
									<el-form-item label="诉求详情" prop="content" :rules="[{ required: true, message: '请填写诉求详情', trigger: 'blur' }]">
										<common-advice
											@chooseAdvice="chooseAdvice"
											v-model="state.ruleForm.content"
											placeholder="请填写诉求详情"
											:loading="state.formLoading"
											:commonEnum="commonEnum.Seat"
											modal
										/>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
									<el-form-item label="附件" prop="files" :rules="[{ required: false, message: '请填写诉求内容', trigger: 'change' }]">
										<annex-list :businessId="state.orderId" classify="办理上传" v-model="state.ruleForm.files" v-model:format="filesFormat" />
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="12" :md="24" :lg="24" :xl="24">
									<el-form-item>
										<el-button class="default-button" @click="onCancel"> 取消 </el-button>
										<el-button class="default-button" @click="save(ruleFormRef)" :loading="buttonLoading"> 保存 </el-button>
										<el-button type="primary" @click="submit(ruleFormRef)" :loading="buttonLoading" v-if="canHandle"> 办理 </el-button>
									</el-form-item>
								</el-col>
							</el-row>
						</el-form>
					</el-card>
				</el-scrollbar>
			</el-col>
			<!-- 右侧内容 -->
			<el-col :span="12" class="right-content h100">
				<el-scrollbar class="h100">
					<el-card shadow="never">
						<el-tabs v-model="rightActive" @tab-change="handleRight">
							<el-tab-pane label="历史工单" name="history">
								<history-order
									:ruleForm="state.ruleForm"
									:orderId="state.orderId"
									@handleSelectionChange="handleSelectionChange"
									ref="historyOrderRef"
								/>
							</el-tab-pane>
							<el-tab-pane label="重复性事件" name="repeat">
								<repeat-event ref="repeatEventRef" @orderAddRepeat="orderAddRepeat" :repeatIds="state.ruleForm.repeatableEventDetails" />
							</el-tab-pane>
							<el-tab-pane label="知识库" name="knowledge">
								<Knowledge />
							</el-tab-pane>
						</el-tabs>
					</el-card>
					<el-card shadow="never">
						<el-tabs v-model="rightBottomActive" @tab-change="handleRightBottom">
							<el-tab-pane label="语音助手" name="voice">
								<voice-assistant @orderOverwrite="orderOverwrite" />
							</el-tab-pane>
							<el-tab-pane label="市民画像" name="draw">
								<citizen-portrait :orderInfo="state.ruleForm" ref="citizenPortraitRef" />
							</el-tab-pane>
						</el-tabs>
					</el-card>
				</el-scrollbar>
			</el-col>
		</el-row>
		<!-- 拓展表单 -->
		<expand-form ref="ExpandFormRef" @saveExpandForm="saveExpandForm" :orderDetail="state.ruleForm" :extra="extra" />
		<!-- 历史工单 -->
		<order-history ref="HistoryOrderRef" @saveSelect="saveSelect" />
		<!--  流程审批  -->
		<process-audit ref="processAuditRef" @orderProcessSuccess="orderProcessSuccess" />
		<!-- 地图选点 -->
		<map-dialog ref="mapDialogRef" @confirm="selectMap" />
		<!-- 企业搜索 -->
		<company-search ref="companySearchRef" />
	</div>
</template>

<script setup lang="ts" name="orderAccept">
import { computed, defineAsyncComponent, onBeforeMount, onMounted, reactive, ref, watch } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useRoute, useRouter } from 'vue-router';
import { useTelStatus } from '@/stores/telStatus';
import { useAppConfig } from '@/stores/appConfig';
import { throttle, transformFile } from '@/utils/tools';
import { commonEnum } from '@/utils/constants';
import { orderAdd, orderBaseDataAdd, orderBaseExt, orderDetail, orderEdit } from '@/api/business/order';
import { useUserInfo } from '@/stores/userInfo';
import { treeArea } from '@/api/auxiliary/area';
import mittBus from '@/utils/mitt';
import { orderRepeatEvent } from '@/api/business/repeatEvent';
import { removeDuplicate } from '@/utils/arrayOperation';

// 引入组件
const VoiceAssistant = defineAsyncComponent(() => import('@/views/todo/seats/accept/Voice-assistant.vue')); // 语音助手
const Knowledge = defineAsyncComponent(() => import('@/views/todo/seats/accept/Knowledge.vue')); // 知识库
const HistoryOrder = defineAsyncComponent(() => import('@/views/todo/seats/accept/History.vue')); // 历史工单
const RepeatEvent = defineAsyncComponent(() => import('@/views/todo/seats/accept/Repeat-event.vue')); // 重复事件
const CitizenPortrait = defineAsyncComponent(() => import('@/views/todo/seats/accept/Citizen-portrait.vue')); // 市民坏画像
const ExpandForm = defineAsyncComponent(() => import('@/views/todo/seats/accept/Expand-form.vue')); // 拓展表单
const OrderHistory = defineAsyncComponent(() => import('@/views/business/order/components/Order-history.vue')); // 历史工单弹窗列表
const CommonAdvice = defineAsyncComponent(() => import('@/components/CommonAdvice/index.vue')); // 常用意见
const AnnexList = defineAsyncComponent(() => import('@/components/AnnexList/index.vue')); // 附件列表
const ProcessAudit = defineAsyncComponent(() => import('@/components/ProcessAudit/index.vue')); // 流程审批
const MapDialog = defineAsyncComponent(() => import('@/views/todo/seats/accept/Map-Dialog.vue')); // 地图定位
const CompanySearch = defineAsyncComponent(() => import('@/views/todo/seats/accept/Company-search.vue')); // 企业搜索
const HotSpotSelect = defineAsyncComponent(() => import('@/components/Hotspot/index.vue')); // 选择热点
// 定义变量内容
const state = reactive<any>({
	createBy: 'manual', // 工单创建方式 默认手动创建  tel:来电弹单  letter:互联网来信 默认表示手动创建
	ruleForm: {
		sourceChannel: null, // 来源频道
		sourceChannelCode: null, //来源频道code
		transferPhone: null, // 转接来源
		fromPhone: null, // 来电号码
		acceptorName: null, // 员工姓名
		acceptorStaffNo: null, // 员工工号
		fromName: null, // 来电人姓名
		fromGender: 1, // 来电人性别 默认先生
		identityType: 1, // 来电/信人身份 默认市民
		licenceType: null, // 证件类型
		licenceTypeCode: null, // 证件类型code
		licenceNo: null, // 证件号码
		ageRange: null, // 年龄段
		ageRangeCode: null, // 年龄段code
		contact: null, // 联系电话
		isSecret: false, // 是否保密 默认false
		acceptSms: false, // 是否接收短信 默认false
		enterpriseName: null, // 企业名称
		zhuanBanMingCheng: null, // 专班名称
		no: null, // 工单编码
		title: null, // 工单标题
		acceptType: null, // 受理类型
		acceptTypeCode: null, // 受理类型code
		emergencyLevel: 1, // 紧急程度 默认一般
		hotspotId: '', // 热点分类
		eventCategoryId: '', // 事件分类
		incidentTime: null, // 事发时间
		incidentPurpose: null, // 事件目的
		areaCode: null, // 区域编码
		street: null, // 街道
		isRepeat: 'false', // 是否重复工单 默认否
		pushType: null, // 推送类型
		pushTypeCode: null, // 推送类型code
		content: '', // 工单内容
		duplicateIds: [], //重复工单id
		duplicateTitle: null, // 重复工单标题
		callAddress: null, // 来电归属地
		repeatableEventDetails: [], //重复性事件
		orderExtension: null, // 拓展信息
	},
	formLoading: false, // 表单加载状态
	hotspotExternal: [], // 热点分类外部数据
	eventCategoryExternal: [], // 事件分类外部数据
	acceptTypeOptions: [], // 受理类型
	channelOptions: [], // 来源频道
	emergencyLevelOptions: [], // 紧急程度
	genderOptions: [], // 性别
	identityTypeOptions: [], //来电人身份
	licenceTypeOptions: [], // 证件类型
	ageRangeOptions: [], // 年龄段
	pushTypeOptions: [], //推送分类
	areaOptions: [], //省市区
	repeatOptions: [
		//是否重复
		{
			value: '是',
			key: 'true',
		},
		{
			value: '否',
			key: 'false',
		},
	],
	orderId: null, // 工单id
	orgData: [],
});
const useTelStatusStore = useTelStatus(); // 来电弹屏
const { telStatusInfo } = storeToRefs(useTelStatusStore); // 来电弹屏信息
const storesUserInfo = useUserInfo(); // 用户信息
const { userInfos } = storeToRefs(storesUserInfo); // 用户信息
const appConfigStore = useAppConfig();
const { AppConfigInfo } = storeToRefs(appConfigStore); // 系统配置信息
state.ruleForm.acceptorName = userInfos.value.name; // 员工姓名
state.ruleForm.acceptorStaffNo = userInfos.value.staffNo; // 员工工号
const route = useRoute(); // 路由
const router = useRouter(); // 路由

// 选择企业
const companySearchRef = ref<RefType>();
const handleSelect = (item: Record<string, any>) => {
	companySearchRef.value.openDialog();
};
// 证件号码验证
const licenceNoPattern = computed(() => {
	switch (state.ruleForm.licenceTypeCode) {
		case '10': // 身份证
			return /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/;
		default: //默认只允许数字字母
			return /^[A-Za-z0-9]+$/;
	}
});
// 选择事件分类
const chooseEvent = (val: any) => {
	state.ruleForm.eventCategoryName = val?.eventName; // 事件分类名称
	state.ruleForm.eventCategorySpliceName = val?.eventFullName; // 事件分类拼接名称
	state.ruleForm.eventCategoryExternal = val?.externalArr?.join(',') ?? ''; // 事件分类id
};
// 选择热点分类
const chooseHotSpot = (val: any) => {
	state.ruleForm.hotspotSpliceName = val?.hotSpotFullName; // 热点分类拼接名称
	state.ruleForm.hotspotName = val?.hotSpotName; // 热点分类名称
	state.ruleForm.hotspotCode = val?.provinceCode; // 热点分类code
	state.ruleForm.hotspotExternal = val?.externalArr?.join(',') ?? ''; // 热点分类默认展开项
};
// 获取事发地址
const areaRef = ref<RefType>();
const changeArea = () => {
	const currentNode = areaRef.value.getCheckedNodes();
	// 判断数组长度
	if (currentNode[0].pathLabels.length <= 4) {
		state.ruleForm.province = currentNode[0].pathLabels[0]; // 省
		state.ruleForm.city = currentNode[0].pathLabels[1] ?? ''; // 市
		state.ruleForm.county = currentNode[0].pathLabels[2] ?? ''; // 区
		state.ruleForm.town = currentNode[0].pathLabels[3] ?? ''; // 地区
	} else {
		// 如果数组长度大于4
		state.ruleForm.province = currentNode[0].pathLabels[0]; // 省
		state.ruleForm.city = currentNode[0].pathLabels[1] ?? ''; // 市
		state.ruleForm.county = currentNode[0].pathLabels[2] ?? ''; // 区
		state.ruleForm.town = currentNode[0].pathLabels[3] ?? ''; // 地区
		state.ruleForm.areaText = currentNode[0].pathLabels.slice(4).join('') ?? ''; // 地区
		console.log(state.ruleForm.areaText);
	}
};
// 根据热点和事发地址去查询重复性事件 是否展示重复性事件
const repeatEventRef = ref<RefType>();
const showRepeatEvent = ref<boolean>(false);
const stopWatch = watch([() => state.ruleForm.hotspotSpliceName, () => state.ruleForm.address], (value) => {
	if (value[0] && value[1]) {
		orderRepeatEvent({ hotspotSpliceName: value[0], address: value[1] }).then((res: any) => {
			if (res.result) {
				showRepeatEvent.value = true;
				repeatEventRef.value.queryList();
			} else {
				showRepeatEvent.value = false;
			}
		});
	} else {
		showRepeatEvent.value = false;
	}
});
stopWatch();
// 地图选点
const mapDialogRef = ref<RefType>();
const selectLocation = () => {
	const location = {
		longitude: state.ruleForm.longitude,
		latitude: state.ruleForm.latitude,
		adcode: state.ruleForm.areaCode,
		formattedAddress: state.ruleForm.street,
	};
	mapDialogRef.value.openDialog(location);
};
// 地图选点
const ruleFormRef = ref<RefType>();
const selectMap = (location: any) => {
	ruleFormRef.value.resetFields('areaCode');
	state.ruleForm.longitude = location.longitude;
	state.ruleForm.latitude = location.latitude;
	state.ruleForm.areaCode = location.adcode;
	state.ruleForm.street = location.formattedAddress;
	state.ruleForm.address = location.formattedAddress;
};
// 将当前工单添加到重复性事件中
const repeatableEventDetails = ref<EmptyArrayType>([]);
const orderAddRepeat = (row: any) => {
	if (route.params.id) {
		//编辑
		if (row.isDeleted) {
			//如果是添加
			repeatableEventDetails.value.push({
				repeatableId: row.id,
				isDeleted: false,
			});
			repeatableEventDetails.value = removeDuplicate([...repeatableEventDetails.value, ...state.ruleForm.repeatableEventDetails], 'repeatableId');
		} else {
			// 移除
			repeatableEventDetails.value = removeDuplicate([...repeatableEventDetails.value, ...state.ruleForm.repeatableEventDetails], 'repeatableId');
			repeatableEventDetails.value = repeatableEventDetails.value.map((item: any) => {
				if (item.repeatableId === row.id) {
					return {
						...item,
						isDeleted: !item.isDeleted,
					};
				}
				return item;
			});
		}
	} else {
		// 添加
		if (row.isDeleted) {
			//如果是添加
			repeatableEventDetails.value.push({
				repeatableId: row.id,
			});
			repeatableEventDetails.value = removeDuplicate(repeatableEventDetails.value, 'repeatableId');
		} else {
			// 移除
			repeatableEventDetails.value = repeatableEventDetails.value.filter((item: any) => item.repeatableId !== row.id);
		}
	}
};
// 查看重复事件
const onRepeatEvent = () => {
	rightActive.value = 'repeat';
};

// 选择是否重复
const isRepeatChange = (val: string) => {
	if (val === 'false') clearRepeat();
};
// 清除重复件
const clearRepeat = () => {
	ElMessageBox.confirm(`确认要清除选择的重复工单?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			historyOrderRef.value.clearRepeat();
			setTimeout(() => {
				state.ruleForm.duplicateTitle = null;
				state.ruleForm.duplicateIds = [];
			}, 0);
		})
		.catch(() => {
			state.ruleForm.isRepeat = 'true';
		});
};
// 选择重复件
const HistoryOrderRef = ref<RefType>();
const selectRepeat = () => {
	HistoryOrderRef.value.openDialog(state.ruleForm);
};
// 弹窗确定选择重复件
const saveSelect = (row: any) => {
	historyOrderRef.value.clearRepeat();
	state.ruleForm.duplicateIds = row.map((item: any) => item.id);
	state.ruleForm.duplicateTitle = '已选择';
	historyOrderRef.value.dialogConfirmRepeat(row);
	HistoryOrderRef.value.closeDialog();
};
// 右侧选择历史工单
const handleSelectionChange = (row: any) => {
	if (row && row.length) {
		state.ruleForm.duplicateIds = row.map((item: any) => item.id);
		state.ruleForm.duplicateTitle = '已选择';
	} else {
		state.ruleForm.duplicateIds = [];
		state.ruleForm.duplicateTitle = null;
	}
};
const historyOrderRef = ref<RefType>(); // 历史工单组件
const citizenPortraitRef = ref<RefType>(); // 市民画像组件
// 查询历史工单 和市民画像
const searchHistory = () => {
	historyOrderRef.value.searchHistory();
	citizenPortraitRef.value.getCitizen();
	rightBottomActive.value = 'draw';
};
// 填写标题时根据填写内容自动选择受理类型
const inputTitle = (val: string) => {
	if (!state.ruleForm.acceptType) {
		const item = state.acceptTypeOptions.find((item: any) => item.dicDataName === val);
		if (item) {
			state.ruleForm.acceptTypeObj = item;
			state.ruleForm.acceptType = item.dicDataName;
			state.ruleForm.acceptTypeCode = item.dicDataValue;
		}
	}
};
const rightActive = ref<string>('history'); // 右侧顶部Tab
const handleRight = (val: string) => {};
const rightBottomActive = ref<string>('voice'); // 右侧底部Tab
const handleRightBottom = (val: string) => {};

// 打开拓展表单
const ExpandFormRef = ref<RefType>();
const showExpandForm = () => {
	ExpandFormRef.value.openDialog();
};
// 拓展表单保存
const saveExpandForm = (val: any) => {
	state.ruleForm.orderExtension = val;
};
// 删除不必要的属性
const deleteUnnecessaryProperties = (obj: any) => {
	const propertiesToDelete = ['ageRangeObj', 'pushTypeObj', 'licenceTypeObj', 'channel', 'acceptTypeObj'];
	propertiesToDelete.forEach((prop) => Reflect.deleteProperty(obj, prop));
};
const filesFormat = ref<EmptyArrayType>([]); // 附件列表格式化

// 是否打开拓展表单
const shouldOpenDialog = (obj: any) =>
	!ExpandFormRef.value.state.validated &&
	obj.orderExtension &&
	obj.orderExtension.orderTypeCode &&
	['scjgjts,scjgjjb'].includes(obj.orderExtension.orderTypeCode);

const buttonLoading = ref<boolean>(false);
// 保存
const save = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		buttonLoading.value = true;
		let orderDetail = {
			...state.ruleForm,
			repeatableEventDetails: repeatableEventDetails.value,
			files: filesFormat.value,
		};
		deleteUnnecessaryProperties(orderDetail);
		const operation = state.orderId ? orderEdit : orderAdd;
		const addOrderAndNavigate = () => {
			operation(orderDetail)
				.then(() => {
					buttonLoading.value = false;
					ElMessage.success('操作成功');
					mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
					mittBus.emit('clearCache', 'order');
					router.go(-1);
				})
				.catch(() => {
					buttonLoading.value = false;
				});
		};
		if (shouldOpenDialog(orderDetail)) {
			ExpandFormRef.value.openDialog(true);
		} else {
			addOrderAndNavigate();
		}
	});
}, 300);
// 选择来点人身份如果是企业 推送分类自动选择助企纾困
const selectIdentity = (val: number) => {
	if (val === 2) {
		state.ruleForm.pushTypeObj = state.pushTypeOptions.find((item: any) => item.dicDataValue === '8'); // 助企纾困
		state.ruleForm.pushType = state.ruleForm.pushTypeObj.dicDataName;
		state.ruleForm.pushTypeCode = state.ruleForm.pushTypeObj.dicDataValue;
	}
};
// 是否可以办理(如果有流程id 并且当前账号可以办理 则可以办理 没有流程ID都可以办理)
const canHandle = computed(() => {
	if (state.ruleForm?.workflowId) return state.ruleForm?.workflow?.canHandle;
	else return true;
});
// 流程审批
const processAuditRef = ref<RefType>();
const processOrder = (orderDetail: any) => {
	buttonLoading.value = false;
	if (orderDetail.workflowId) {
		// 如果已经有流程id 说明已经发起过流程  直接调用工单办理
		const params = {
			id: orderDetail.workflowId,
			processType: '工单办理',
			orderDetail,
			extra: {
				dialogTitle: '工单办理',
				inputPlaceholder: '办理意见',
				annexName: '办理附件',
			},
		};
		processAuditRef.value.openDialog(params);
	} else {
		// 如果没有流程id 说明没有发起过流程  调用工单受理
		const params = {
			id: state.orderId,
			processType: '工单受理',
			extra: {
				dialogTitle: '工单受理',
				inputPlaceholder: '办理意见',
				annexName: '办理附件',
			},
			orderDetail,
		};
		processAuditRef.value.openDialog(params);
	}
	console.log(orderDetail);
};
const handleForm = (orderDetail: any) => {
	if (orderDetail.orderExtension?.orderTypeCode) {
		if (ExpandFormRef.value.state.validated) {
			processOrder(orderDetail);
		} else {
			ExpandFormRef.value.openDialog(true);
		}
	} else {
		processOrder(orderDetail);
	}
};
// 提交
const submit = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		buttonLoading.value = true;
		const orderDetail = {
			...state.ruleForm,
			repeatableEventDetails: repeatableEventDetails.value,
			files: filesFormat.value,
		};
		deleteUnnecessaryProperties(orderDetail);
		handleForm(orderDetail);
	});
}, 300);
// 选中常用意见
const chooseAdvice = (item: any) => {
	state.ruleForm.content += item.content;
};
// 流程提交成功
const orderProcessSuccess = () => {
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'order');
	router.go(-1);
};
// 取消
const onCancel = () => {
	orderProcessSuccess();
};
// 一建填单
const orderOverwrite = (val: any) => {
	if (val.id_card) {
		// 身份证号
		state.ruleForm.licenceTypeCode = '10';
		state.ruleForm.licenceType = '身份证';
		state.ruleForm.licenceNo = val.id_card;
	}
	state.ruleForm.fromName = val.name ? val.name : state.ruleForm.fromName; // 来电人姓名
	state.ruleForm.street = val.address ? val.address : state.ruleForm.street; // 详细地址
	state.ruleForm.enterpriseName = val.company_name ? val.company_name : state.ruleForm.enterpriseName; // 企业名称
	state.ruleForm.incidentPurpose = val.event_purpose ? val.event_purpose : state.ruleForm.incidentPurpose; // 事件目的
	state.ruleForm.title = val.record_title ? val.record_title : state.ruleForm.title; // 工单标题
	state.ruleForm.content = val.appeal_detatls ? val.appeal_detatls : state.ruleForm.content; // 诉求详情
	ElNotification({
		title: '提示',
		message: '一键填单成功',
		type: 'success',
	});
	console.log(val, '工单重写');
};
// 加载基础数据
const loadBaseData = async () => {
	state.formLoading = true;
	try {
		const res = await orderBaseDataAdd();
		state.acceptTypeOptions = res.result?.acceptTypeOptions ?? [];
		state.channelOptions = res.result?.channelOptions ?? [];
		state.emergencyLevelOptions = res.result?.emergencyLevelOptions ?? [];
		state.genderOptions = res.result?.genderOptions ?? [];
		state.identityTypeOptions = res.result?.identityTypeOptions ?? [];
		orderTypeOptions.value = res.result?.orderTypeOptions ?? [];
		state.pushTypeOptions = res.result?.pushTypeOptions ?? [];
		state.licenceTypeOptions = res.result?.licenceTypeOptions ?? [];
		state.ageRangeOptions = res.result?.ageRangeOptions ?? [];
		state.ruleForm.seats = `${userInfos.value.name} [${userInfos.value.staffNo}]`;
		state.formLoading = false;
	} catch (error) {
		state.formLoading = false;
	} finally {
		state.formLoading = false;
	}
};
// 如果是修改加载表单内容
const historyParams = history.state;

const loadForm = async () => {
	//  historyParams.createBy  createBy 代表来源  tel:来电弹单  letter:互联网来信 默认表示手动创建
	if (historyParams.createBy) {
		state.createBy = historyParams.createBy;
		if (historyParams.createBy === 'tel') {
			//通话
			state.ruleForm.sourceChannel = '电话'; //电话
			state.ruleForm.sourceChannelCode = 'RGDH'; //电话
			state.ruleForm.fromPhone = historyParams.fromTel;
			state.ruleForm.callId = historyParams.telGuid;
			state.ruleForm.transferPhone = historyParams.transfer;
			state.ruleForm.callAddress = historyParams.telArea; // 来电归属地
			state.ruleForm.channel = {
				// 来源渠道
				dicDataValue: state.ruleForm.sourceChannelCode,
				dicDataName: state.ruleForm.sourceChannel,
			};
		}
	}
	if (route.params.id) {
		// 如果 有id
		state.orderId = route.params.id;
		const response = await orderDetail(route.params.id);
		// 如果获取到id 调用查询详情
		state.ruleForm = response.result;
		state.ruleForm.files = transformFile(response.result.files);
		if (response.result.duplicateIds && response.result.duplicateIds.length) {
			// 是否重复
			state.ruleForm.isRepeat = 'true';
			state.ruleForm.duplicateTitle = '已选择';
		} else {
			state.ruleForm.isRepeat = 'false';
		}
		state.ruleForm.channel = {
			// 来源渠道
			dicDataValue: state.ruleForm.sourceChannelCode,
			dicDataName: state.ruleForm.sourceChannel,
		};

		if (state.ruleForm.hotspotExternal) {
			//热点分类默认展开
			state.hotspotExternal = state.ruleForm.hotspotExternal.split(',');
		}
		if (state.ruleForm.eventCategoryExternal) {
			//热点分类默认展开
			state.eventCategoryExternal = state.ruleForm.eventCategoryExternal.split(',');
		}
		state.ruleForm.ageRangeObj = {
			// 年龄段
			dicDataValue: state.ruleForm.ageRangeCode,
			dicDataName: state.ruleForm.ageRange,
		};
		state.ruleForm.licenceTypeObj = {
			// 证件类型
			dicDataValue: state.ruleForm.licenceTypeCode,
			dicDataName: state.ruleForm.licenceType,
		};
		state.ruleForm.acceptTypeObj = {
			// 受理类型
			dicDataValue: state.ruleForm.acceptTypeCode,
			dicDataName: state.ruleForm.acceptType,
		};
		state.ruleForm.pushTypeObj = {
			// 推送分类
			dicDataValue: state.ruleForm.pushTypeCode,
			dicDataName: state.ruleForm.pushType,
		};
	}
};
// 加载省市区
const addressLoading = ref<boolean>(false);
const loadAddress = async () => {
	addressLoading.value = true;
	try {
		const area = await treeArea();
		state.areaOptions = area.result ?? []; //省市区数据
		addressLoading.value = false;
	} catch (error) {
		console.log(error);
	} finally {
		addressLoading.value = false;
	}
};
// 加载扩展信息
const orderTypeOptions = ref<EmptyObjectType>([]); // 工单类型
// 拓展信息
const extra = ref<any>({
	ext: {},
	area: {},
	orderTypeOptions: [],
});
const extraLoading = ref<boolean>(false);
const loadExtra = async () => {
	extraLoading.value = true;
	try {
		const ext = await orderBaseExt(); // 扩展信息
		extra.value = { ext: { ...ext.result, orderTypeOptions: orderTypeOptions.value, area: state.areaOptions } }; //补充信息
	} catch (error) {
		console.log(error);
	} finally {
		extraLoading.value = false;
	}
};
onBeforeMount(() => {
	loadBaseData();
	loadForm();
});
onMounted(async () => {
	await loadAddress();
	await loadExtra();
});
</script>
