<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 = '';
														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" 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="请填写来电号码" disabled> </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: /^((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-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 }} </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="orderType" :rules="[{ required: true, message: '请选择工单类型', trigger: 'change' }]">
												<el-select v-model="state.ruleForm.orderType" placeholder="请选择工单类型" class="w100" @change="selectOrderType">
													<el-option v-for="item in state.orderTypeOptions" :key="item.key" :label="item.value" :value="item.key" />
												</el-select>
											</el-form-item>
										</el-col>
										<!-- 当“工单类型”为非通用工单时，展示【拓展信息】按钮 -->
										<el-col :xs="6" :sm="6" :md="6" :lg="6" :xl="6" :offset="1" v-if="state.ruleForm.orderType === 1 && state.ruleForm.acceptTypeObj">
											<el-form-item label="" label-width="0px">
												<el-button @click="showExpandForm"> <SvgIcon name="ele-CirclePlus" class="mr3" size="16px" /> 拓展信息 </el-button>
											</el-form-item>
										</el-col>
									</el-row>
								</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="24" :xl="24">
									<el-form-item label="热点分类" prop="hotspotId" :rules="[{ required: true, message: '请选择热点分类', trigger: 'change' }]">
										<el-tree-select
											class="w100"
											v-model="state.ruleForm.hotspotId"
											filterable
											placeholder="请选择热点分类"
											:props="HotspotProps"
											lazy
											:load="load"
											node-key="id"
											check-strictly
											:render-after-expand="false"
											@node-click="hotSpotChange"
											:default-expanded-keys="state.hotspotExternal"
										/>
									</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="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' }]">
												<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="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">
									<el-form-item label="工单标题" prop="title" :rules="[{ required: true, message: '请填写工单标题', trigger: 'blur' }]">
										<el-input v-model="state.ruleForm.title" placeholder="请填写工单标题" clearable> </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="remark" :rules="[{ required: false, message: '请填写诉求内容', trigger: 'change' }]">
										<annex-list ref="annexListRef" :businessId="state.orderId" classify="受理上传" />
									</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="save(ruleFormRef)" v-auth="'business:order:add'"> 保存 </el-button>
										<el-button type="primary" v-waves @click="submit(ruleFormRef)" v-auth="'business:order:startWorkflow'"> 提交 </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="knowledge">
								<el-tabs v-model="knowledgeActive" @tab-change="handleKnowledge">
									<el-tab-pane label="中心知识库" name="center"> </el-tab-pane>
									<el-tab-pane label="部门知识库" name="org"> </el-tab-pane>
									<Knowledge :type="knowledgeActive" :formData="state.ruleForm" ref="knowledgeActiveRef" v-if="knowledgeActive === 'center'" />
									<Knowledge :type="knowledgeActive" :formData="state.ruleForm" ref="knowledgeActiveRef" v-if="knowledgeActive === 'org'" />
								</el-tabs>
							</el-tab-pane>
							<el-tab-pane label="重复性事件" name="repeat">
								<repeat-event ref="repeatEventRef"/>
							</el-tab-pane>
							<el-tab-pane label="历史工单" name="history">
								<history-order
									:formData="state.ruleForm"
									:orderId="state.orderId"
									@handleSelectionChange="handleSelectionChange"
									ref="historyOrderRef"
								/>
							</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 />
							</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>
		<!-- 拓展表单 -->
		<order-expand-form ref="ExpandFormRef" @saveExpandForm="saveExpandForm" :orderDetail="orderDetailInfo" :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 { defineAsyncComponent, ref, reactive, computed, onBeforeMount, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useRoute, useRouter } from 'vue-router';
import { useTelStatus } from '/@/stores/telStatus';
import { throttle } from '/@/utils/tools';
import { commonEnum } from '/@/utils/constants';
import { orderBaseDataAdd, orderAdd, hotSpotType, orderEdit, orderDetail, orderBaseExt } 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';

// 引入组件
const Knowledge = defineAsyncComponent(() => import('/@/views/business/order/accept/Knowledge.vue')); // 知识库
const HistoryOrder = defineAsyncComponent(() => import('/@/views/business/order/accept/History.vue')); // 历史工单
const RepeatEvent = defineAsyncComponent(() => import('/@/views/business/order/accept/Repeat-event.vue')); // 重复事件
const VoiceAssistant = defineAsyncComponent(() => import('/@/views/business/order/accept/Voice-assistant.vue')); // 重复事件
const CitizenPortrait = defineAsyncComponent(() => import('/@/views/business/order/accept/Citizen-portrait.vue')); // 市民坏画像
const OrderExpandForm = defineAsyncComponent(() => import('/@/views/business/order/components/Order-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/business/order/components/Map-Dialog.vue')); // 地图定位
const CompanySearch = defineAsyncComponent(() => import('/@/views/business/order/accept/Company-search.vue')); // 企业搜索
// 定义变量内容
const state = reactive<any>({
	createBy: 'manual', // 工单创建方式 默认手动创建  tel:来电弹单  letter:互联网来信 默认表示手动创建
	activeName: 'first', // tabs
	ruleForm: {
		sourceChannel: '', // 来源频道
		sourceChannelCode: '', //来源频道code
		transferPhone: '', // 转接来源
		fromPhone: '', // 来电号码
		acceptorName: '', // 员工姓名
		acceptorStaffNo: '', // 员工工号
		fromName: '', // 来电人姓名
		fromGender: 1, // 来电人性别 默认先生
		identityType: 1, // 来电/信人身份 默认市民
		licenceType: '', // 证件类型
		licenceTypeCode: '', // 证件类型code
		licenceNo: '', // 证件号码
		ageRange: '', // 年龄段
		ageRangeCode: '', // 年龄段code
		contact: '', // 联系电话
		acceptSms: false, // 是否接收短信 默认false
		isSecret: false, // 是否保密 默认false
		enterpriseName: '', // 企业名称
		zhuanBanMingCheng: '', // 专班名称
		no: '', // 工单编码
		title: '', // 工单标题
		orderType: 0, // 工单类型 默认通用工单
		acceptType: '', // 受理类型
		acceptTypeCode: '', // 受理类型code
		emergencyLevel: 1, // 紧急程度 默认一般
		hotspotId: '', // 热点问题
		areaCode: '', // 区域编码
		street: '', // 街道
		isRepeat: 'false', // 是否重复工单 默认否
		pushType: '', // 推送类型
		pushTypeCode: '', // 推送类型code
		content: '', // 工单内容
		duplicateIds: [], //重复工单id
		duplicateTitle: '', // 重复工单标题
		callAddress: '', // 来电归属地
	},
	formLoading: false, // 表单加载状态
	hotspotExternal: [], // 热点分类外部数据
	acceptTypeOptions: [], // 受理类型
	channelOptions: [], // 来源频道
	emergencyLevelOptions: [], // 紧急程度
	genderOptions: [], // 性别
	identityTypeOptions: [], //来电人身份
	licenceTypeOptions: [], // 证件类型
	ageRangeOptions: [], // 年龄段
	orderTypeOptions: [], // 工单类型
	pushTypeOptions: [], //推送分类
	areaOptions: [], //省市区
	repeatOptions: [
		//是否重复
		{
			value: '是',
			key: 'true',
		},
		{
			value: '否',
			key: 'false',
		},
	],
	orgData: [], // 机构数据
	orderId: '', // 工单id
});
const useTelStatusStore = useTelStatus(); // 来电弹屏
const { telStatusInfo } = storeToRefs(useTelStatusStore); // 来电弹屏信息
const storesUserInfo = useUserInfo(); // 用户信息
const { userInfos } = storeToRefs(storesUserInfo); // 用户信息
state.ruleForm.acceptorName = userInfos.value.name; // 员工姓名
state.ruleForm.acceptorStaffNo = userInfos.value.staffNo; // 员工工号
const route = useRoute(); // 路由
const router = useRouter(); // 路由
const historyParams = history.state;

// 选择企业
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 HotspotProps = {
	label: 'hotSpotFullName',
	children: 'children',
	isLeaf: 'isLeaf',
};
// 热点分类懒加载
const load = async (node: any, resolve: any) => {
	if (node.isLeaf) return resolve([]);
	const res: any = await hotSpotType({ id: node.data.id ? node.data.id : '' });
	resolve(res.result);
};
// 选择热点分类
const knowledgeActiveRef = ref<RefType>();
const hotSpotChange = (val: any, e: any) => {
	state.hotspotExternal = [];
	state.external = [];
	state.hotspotExternal = getParentId(e, state.external);
	state.ruleForm.hotspotSpliceName = val.hotSpotFullName;
	state.ruleForm.hotspotName = val.hotSpotName;
	knowledgeActiveRef.value.knowledgeRetrievalPaged(val.hotSpotName);
  searchRepeatEvent(val.hotSpotFullName,state.ruleForm.address);
};
// 递归查找父级Id
const getParentId = (val: any, arr: string[]) => {
	if (val.data.parentId) {
		arr.push(val.data.parentId);
		getParentId(val.parent, arr);
	}
	return arr;
};
// 选择工单类型 处理受理类型选择数据
const ruleFormRef = ref<RefType>();
const selectOrderType = (val: any) => {
	ruleFormRef.value.resetFields('acceptTypeObj');
	state.ruleForm.acceptType = '';
	state.ruleForm.acceptTypeCode = '';
	state.acceptTypeOptions = state.acceptTypeOptions.map((item: any) => {
		let isDisabled = val === 1 && !['30', '35'].includes(item.dicDataValue); // 选择了12315 市场监管受理单 举报:30 投诉:35
		return {
			...item,
			disabled: isDisabled,
		};
	});
};
const areaRef = ref<RefType>();
const showRepeatEvent = ref<boolean>(false); //是否展示重复性事件
// 获取事发地址
const changeArea = () => {
	const currentNode = areaRef.value.getCheckedNodes();
	state.ruleForm.address = currentNode[0].pathLabels.join(''); // 事发地址
	searchRepeatEvent(state.ruleForm.hotspotSpliceName,state.ruleForm.address);
};
// 根据热点和事发地址去查询重复性事件
const repeatEventRef = ref<RefType>();
const searchRepeatEvent = async (hotspotSpliceName:string,address:string) => {
	if (hotspotSpliceName && address) {
		const {result} = await orderRepeatEvent({hotspotSpliceName,address});
    if(result){
      showRepeatEvent.value = true;
      repeatEventRef.value.queryList();
    }else{
      showRepeatEvent.value = false;
    }
	}
};
// 地图选点
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 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;
  searchRepeatEvent(state.ruleForm.hotspotSpliceName,location.formattedAddress);
};
// 查看重复事件
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 = '';
          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 = '';
  }
};
const historyOrderRef = ref<RefType>(); // 历史工单组件
const citizenPortraitRef = ref<RefType>(); // 市民画像组件
// 查询历史工单 和市民画像
const searchHistory = (val?: any) => {
  historyOrderRef.value.searchHistory(val);
  rightActive.value = 'history';
  citizenPortraitRef.value.getCitizen(state.ruleForm);
};
const rightActive = ref<string>('knowledge'); // 右侧顶部Tab
const handleRight = (val: string) => {};
const knowledgeActive = ref<string>('center'); // 知识库顶部Tab
const handleKnowledge = (val: string) => {};
const rightBottomActive = ref<string>('voice'); // 右侧底部Tab
const handleRightBottom = (val: string) => {};

// 打开拓展表单
const ExpandFormRef = ref<RefType>();
const showExpandForm = () => {
	ExpandFormRef.value.openDialog(state.ruleForm.acceptTypeCode);
};
// 拓展表单保存
const saveExpandForm = (val: any) => {
	const acceptTypeMap: any = {
		'30': 'orderReport',
		'35': 'orderComplain',
	};
	const property = acceptTypeMap[state.ruleForm.acceptTypeCode];
	if (property) {
		state.ruleForm[property] = val;
	}
};
// 删除不必要的属性
const deleteUnnecessaryProperties = (obj: any) => {
	const propertiesToDelete = ['ageRangeObj', 'pushTypeObj', 'licenceTypeObj', 'channel', 'acceptTypeObj'];
	propertiesToDelete.forEach((prop) => Reflect.deleteProperty(obj, prop));
	if (obj.acceptType === '30') Reflect.deleteProperty(obj, 'orderComplain');
	if (obj.acceptType === '35') Reflect.deleteProperty(obj, 'orderReport');
	if (state.orderId) Reflect.deleteProperty(obj, 'files');
};
// 是否打开拓展表单
const shouldOpenDialog = (obj: any) => obj.orderType === 1 && obj.acceptType && !ExpandFormRef.value.state.validated;
const annexListRef = ref<RefType>(); // 附件列表
// 保存
const save = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		let orderDetail = {
			...state.ruleForm,
			hotspotExternal: state.hotspotExternal.join(','),
			files: annexListRef.value?.fileList,
		};
		deleteUnnecessaryProperties(orderDetail);
		const operation = state.orderId ? orderEdit : orderAdd;
		const addOrderAndNavigate = () => {
			operation(orderDetail).then(() => {
				ElMessage.success('操作成功');
				mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
				mittBus.emit('clearCache', 'order');
				router.push({
					path: '/business/order/index',
				});
			});
		};
		if (shouldOpenDialog(orderDetail)) {
			ExpandFormRef.value.openDialog(orderDetail.acceptTypeCode, 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;
	}
};
// 流程审批
const processAuditRef = ref<RefType>();
const processOrder = (orderDetail: any) => {
	const params = {
		id: state.orderId,
		processType: '工单发起',
		extra: {
			dialogTitle: '提交流程',
			inputPlaceholder: '办理意见',
			annexName: '办理附件',
		},
		orderDetail,
	};
	processAuditRef.value.openDialog(params);
};
const handleForm = (orderDetail: any) => {
	if (orderDetail.orderType === 1 && orderDetail.acceptTypeCode) {
		if (ExpandFormRef.value.state.validated) {
			processOrder(orderDetail);
		} else {
			ExpandFormRef.value.openDialog(orderDetail.acceptTypeCode, true);
		}
	} else {
		processOrder(orderDetail);
	}
};
// 提交
const submit = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		console.log(state.hotspotExternal);
		let orderDetail = {
			...state.ruleForm,
			hotspotExternal: state.hotspotExternal.join(','),
		};
		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.push({
		path: '/business/order/index',
	});
};

// 拓展信息
const extra = ref<any>({
	ext: {},
	area: {},
});
const orderDetailInfo = ref({});
onBeforeMount(async () => {
	state.formLoading = true;
	try {
		const [area, res] = await Promise.all([treeArea(), 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 ?? [];
		state.orderTypeOptions = 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.areaOptions = area.result ?? []; //省市区数据
		//  historyParams.createBy  createBy 代表来源  tel:来电弹单  letter:互联网来信 默认表示手动创建
		console.log(historyParams, route.params);
		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;
			orderDetailInfo.value = response.result;
			if (response.result.duplicateIds && response.result.duplicateIds.length) {
				// 是否重复
				state.ruleForm.isRepeat = 'true';
				state.ruleForm.duplicateTitle = '已选择';
			} else {
				state.ruleForm.isRepeat = 'false';
			}
			if (state.ruleForm.orderType === 1) {
				// 工单类型 选择了12315市场监管受理单
				state.acceptTypeOptions = state.acceptTypeOptions.map((item: any) => {
					if (['30', '35'].includes(item.dicDataValue)) {
						//直接投诉或者建议
						return {
							...item,
							disabled: false,
						};
					} else {
						return {
							...item,
							disabled: true,
						};
					}
				});
				state.expandFormMounted = true;
			}
			state.ruleForm.channel = {
				// 来源渠道
				dicDataValue: state.ruleForm.sourceChannelCode,
				dicDataName: state.ruleForm.sourceChannel,
			};

			if (state.ruleForm.duplicateIds && state.ruleForm.duplicateIds.length) {
				// 是否重复
				state.ruleForm.isRepeat = 'true';
			} else {
				state.ruleForm.isRepeat = 'false';
			}
			if (state.ruleForm.hotspotExternal) {
				//热点分类默认展开
				state.hotspotExternal = state.ruleForm.hotspotExternal.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,
			};
			knowledgeActiveRef.value.knowledgeRetrievalPaged(state.ruleForm.hotspotName);
			searchHistory(state.ruleForm.contact);
			state.formLoading = false;
		}
	} catch (error) {
		state.formLoading = false;
	} finally {
		state.formLoading = false;
	}
});
onMounted(async () => {
	const ext = await orderBaseExt(); // 扩展信息
	extra.value = { ext: ext.result, area: state.areaOptions }; //补充信息
});
</script>

<style scoped lang="scss">
:deep(.el-divider--horizontal) {
	margin-top: 0;
}

.order-add-container {
	color: var(--hotline-color-text-main);
}
</style>
