<template>
	<el-drawer v-model="state.dialogVisible" title="修改工单信息" destroy-on-close size="50%" append-to-body>
		<el-form label-width="110px" ref="ruleFormRef" :model="state.ruleForm" v-loading="state.loading" scroll-to-error>
			<el-row :gutter="10">
				<el-col>
					<p class="border-title mb10">来电信息</p>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
					<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="changeChannel"
						>
							<el-option v-for="item in state.channelOptions" :value="item" :key="item.dicDataValue" :label="item.dicDataName" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
					<el-form-item label="转接来源" prop="transferPhone">
						<span v-if="state.ruleForm.transferPhone">{{ state.ruleForm.transferPhone }}</span>
						<template v-else>暂无</template>
						<span class="ml5" v-if="state.ruleForm.startTime">（{{ formatDate(state.ruleForm.startTime, 'YYYY-mm-dd HH:MM:SS') }}）</span>
					</el-form-item>
				</el-col>
				<!-- 行业类型 来源渠道是随手拍才有这个字段 -->
				<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="state.ruleForm.sourceChannelCode === 'ZGSSP'">
					<el-form-item label="行业类型" prop="industryObj" :rules="[{ required: true, message: '请选择行业类型', trigger: 'change' }]">
						<el-select
							v-model="state.ruleForm.industryObj"
							placeholder="请选择行业类型"
							class="w100"
							value-key="id"
							clearable
							@change="changeIndustry"
						>
							<el-option v-for="item in state.industryOptions" :key="item.id" :disabled="item.disabled" :label="item.name" :value="item" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="state.ruleForm.sourceChannelCode === 'RGDH'">
					<el-form-item label="来电号码" prop="fromPhone" :rules="[{ required: true, message: '请填写来电号码', trigger: 'blur' }]">
						<el-input v-model.trim="state.ruleForm.fromPhone" 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="受理人">
						<span>{{ state.ruleForm.acceptorName }}</span>
						<el-button
							plain
							title="录音文件"
							size="small"
							type="primary"
							class="ml8"
							@click="recordFile(state.ruleForm)"
							v-if="
								['ZiGong', 'LuZhou'].includes(themeConfig.appScope)
									? state.ruleForm?.recordingAbsolutePath && userInfos.isCenter
									: state.ruleForm?.recordingAbsolutePath
							"
							>录音文件</el-button
						>
					</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-input v-model="state.ruleForm.fromName" placeholder="请填写来电人姓名" clearable @input="inputName"> </el-input>
					</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 :value="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 :value="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="contact" :rules="[{ required: true, message: '请填写联系电话', trigger: 'blur' }]">
						<el-input v-model.trim="state.ruleForm.contact" placeholder="请填写联系电话" clearable> </el-input>
					</el-form-item>
				</el-col>
				<!--		宜宾特殊字段		-->
				<template v-if="['YiBin'].includes(themeConfig.appScope)">
					<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="changeLicenceType"
							>
								<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: false, 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="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: false, 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>
				</template>
				<el-col>
					<p class="border-title mb10">诉求信息</p>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" 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="受理类型" prop="acceptTypeObj" :rules="[{ required: true, message: '请选择受理类型', trigger: 'change' }]">
						<el-select
							v-model="state.ruleForm.acceptTypeObj"
							placeholder="请选择受理类型"
							class="w100"
							value-key="dicDataValue"
							clearable
							@change="changeAcceptType"
						>
							<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>
				<template v-if="['YiBin'].includes(themeConfig.appScope)">
					<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
						<el-form-item
							label="重点关注事件"
							prop="focusOnEventsArr"
							:rules="[{ required: false, message: '请选择重点关注事件', trigger: 'change' }]"
						>
							<el-select v-model="state.ruleForm.focusOnEventsArr" placeholder="请选择重点关注事件" class="w100" multiple @change="changeFocusEvent">
								<el-option v-for="item in state.focusOnEvents" :key="item.dicDataValue" :label="item.dicDataName" :value="item.dicDataValue" />
							</el-select>
						</el-form-item>
					</el-col>
				</template>
				<template v-if="['ZiGong', 'LuZhou'].includes(themeConfig.appScope)">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<el-form-item label="重点标签" prop="focusOnEventsArr" :rules="[{ required: false, message: '请选择重点标签', trigger: 'change' }]">
							<el-checkbox-group v-model="state.ruleForm.focusOnEventsArr" @change="changeFocusEvent">
								<el-checkbox :label="item.dicDataName" :value="item.dicDataValue" v-for="item in state.focusOnEvents" :key="item.dicDataValue" />
							</el-checkbox-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
						<el-form-item label="工单标签" prop="orderTagObj" :rules="[{ required: false, message: '请选择工单标签', trigger: 'change' }]">
							<el-select
								v-model="state.ruleForm.orderTagObj"
								placeholder="请选择工单标签"
								class="w100"
								clearable
								value-key="dicDataValue"
								@change="changeOrderTag"
							>
								<el-option v-for="item in state.orderTags" :key="item.dicDataValue" :label="item.dicDataName" :value="item" />
							</el-select>
						</el-form-item>
					</el-col>
				</template>
				<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
					<el-form-item label="推送分类" prop="orderPushTypes" :rules="[{ required: false, message: '请选择推送分类', trigger: 'change' }]">
						<el-select v-model="state.ruleForm.orderPushTypes" placeholder="请选择推送分类" class="w100" clearable value-key="pushTypeCode" multiple>
							<el-option v-for="item in state.pushTypeOptions" :key="item.pushTypeCode" :label="item.pushType" :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' }]">
						<event-select
							@change="chooseEvent"
							v-model="state.ruleForm.eventCategoryId"
							v-model:externalArr="state.eventCategoryExternal"
							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"
							v-model:externalArr="state.hotspotExternal"
							@change="chooseHotSpot"
							placeholder="请选择热点分类"
							clearable
							@getCurrentData="getCurrentData"
							:isYB="isProvinceOrder"
						/>
					</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-form-item>
						</el-col>
						<div v-if="showRepeatEvent" class="color-danger mb10" style="margin-left: 110px">
							【{{ state.ruleForm.address }}】下存在多起【{{ state.ruleForm.hotspotSpliceName }}】事件，点击前往查看或右侧添加重复性事件
						</div>
					</el-row>
				</el-col>
				<!-- 系统配置 可以配置是否开启重复工单 -->
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="AppConfigInfo.isOpenRepeatedWorkOrders">
					<el-row>
						<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" v-if="AppConfigInfo.isTranspondCity">
					<el-row>
						<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
							<el-form-item label="是否市州互转" prop="transpond" :rules="[{ required: true, message: '请选择是否市州互转', trigger: 'change' }]">
								<el-select v-model="state.ruleForm.transpond" placeholder="请选择是否市州互转" class="w100" @change="changeTransPond">
									<el-option :key="true" label="是" :value="true" />
									<el-option :key="false" label="否" :value="false" />
								</el-select>
							</el-form-item>
						</el-col>
						<!-- 必填，若“是否市州互转”为“是”，则展示选择市州选择框 -->
						<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="state.ruleForm.transpond">
							<el-form-item
								label=""
								prop="transpondCityObj"
								label-width="10px"
								:rules="[{ required: true, message: '请选择互转市州', trigger: 'change' }]"
							>
								<el-select
									v-model="state.ruleForm.transpondCityObj"
									placeholder="请选择互转市州"
									class="w100"
									value-key="dicDataValue"
									@change="changeTranspondCity"
								>
									<el-option v-for="item in state.transpondCity" :key="item.dicDataValue" :label="item.dicDataName" :value="item" />
								</el-select>
							</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">
					<!--									showTextCheck-->
					<el-form-item
						label="受理内容"
						prop="content"
						:rules="[
							{ required: true, message: '请填写受理内容', trigger: 'blur' },
							{ required: true, pattern: '[^ \x20]+', trigger: 'blur', message: '受理内容不能为空' },
						]"
					>
						<common-advice
							@chooseAdvice="chooseAdvice"
							v-model="state.ruleForm.content"
							placeholder="请填写受理内容"
							:loading="state.formLoading"
							:commonEnum="commonEnum.Seat"
						/>
					</el-form-item>
				</el-col>
				<!-- 有state.ruleForm.centerOpinion才展示  如果填了就不用隐藏 -->

				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="state.ruleForm.centerOpinion || state.ruleForm.centerOpinion === ''">
					<el-form-item
						label="中心意见"
						prop="centerOpinion"
						:rules="[
							{ required: true, message: '请填写中心意见', trigger: 'blur' },
							{ required: true, pattern: '[^ \x20]+', trigger: 'blur', message: '中心意见不能为空' },
						]"
					>
						<el-input
							v-model="state.ruleForm.centerOpinion"
							placeholder="请填写中心意见"
							type="textarea"
							:autosize="{ minRows: 4, maxRows: 8 }"
						></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="state.ruleForm.fileOpinion || state.ruleForm.fileOpinion === ''">
					<el-form-item
						label="承办意见"
						prop="fileOpinion"
						:rules="[
							{ required: true, message: '请填写承办意见', trigger: 'blur' },
							{ required: true, pattern: '[^ \x20]+', trigger: 'blur', message: '承办意见不能为空' },
						]"
					>
						<el-input
							v-model="state.ruleForm.fileOpinion"
							placeholder="请填写承办意见"
							type="textarea"
							:autosize="{ minRows: 4, maxRows: 8 }"
						></el-input>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" v-if="state.ruleForm.orderRemarks?.length">
					<el-form-item label="备注信息">
						<el-row v-for="(item, index) in state.ruleForm.orderRemarks" class="w100 mb10" :key="index">
							<el-col class="formatted-text">备注信息：{{ item.remark }} </el-col>
							<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">备注人：{{ item.remarkUser }} </el-col>
							<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">备注日期：{{ formatDate(item.remarkTime, 'YYYY-mm-dd HH:MM:SS') }}</el-col>
						</el-row>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDrawer" class="default-button" :loading="state.loading">取消</el-button>
				<el-button type="primary" @click="save(ruleFormRef)" :loading="state.loading"> 保存 </el-button>
			</span>
		</template>
	</el-drawer>
	<!-- 企业搜索 -->
	<company-search ref="companySearchRef" @selectCompany="selectCompany" />
	<!-- 重复工单选择 -->
	<order-repeat-select ref="orderRepeatSelectRef" @orderRepeatSuccess="orderRepeatSuccess" />
	<!-- 播放录音 -->
	<play-record ref="playRecordRef" />
</template>
<script setup lang="ts">
import { defineAsyncComponent, onMounted, reactive, ref, watch } from 'vue';
import { formatDate } from '@/utils/formatTime';
import { FormInstance, ElMessageBox, ElMessage } from 'element-plus';
import { orderBaseDataAdd, orderDetail, orderEdit } from '@/api/business/order';
import { transformFile } from '@/utils/tools';
import { commonEnum } from '@/utils/constants';
import { treeArea } from '@/api/auxiliary/area';
import { useAppConfig } from '@/stores/appConfig';
import { storeToRefs } from 'pinia';
import { orderRepeatEvent } from '@/api/business/repeatEvent';
import { useThemeConfig } from '@/stores/themeConfig';
import { useUserInfo } from '@/stores/userInfo';
import { removeDuplicate } from '@/utils/arrayOperation';

const OrderRepeatSelect = defineAsyncComponent(() => import('@/views/todo/seats/accept/Order-repeat-select.vue')); // 选择重复工单
const CommonAdvice = defineAsyncComponent(() => import('@/components/CommonAdvice/index.vue')); // 常用意见
const EventSelect = defineAsyncComponent(() => import('@/components/Hotspot/event.vue')); // 选择事件
const HotSpotSelect = defineAsyncComponent(() => import('@/components/Hotspot/index.vue')); // 选择热点
const CompanySearch = defineAsyncComponent(() => import('@/views/todo/seats/accept/Company-search.vue')); // 企业搜索
const PlayRecord = defineAsyncComponent(() => import('@/components/PlayRecord/index.vue')); // 播放录音
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 是否显示弹窗
	loading: false, // 是否显示加载
	ruleForm: {},
	formLoading: false, // 表单加载状态
	hotspotExternal: [], // 热点分类外部数据
	eventCategoryExternal: [], // 事件分类外部数据
	acceptTypeOptions: [], // 受理类型
	channelOptions: [], // 来源频道
	genderOptions: [], // 性别
	identityTypeOptions: [], //来电主体
	licenceTypeOptions: [], // 证件类型
	ageRangeOptions: [], // 年龄段
	pushTypeOptions: [], //推送分类
	areaOptions: [], //省市区
	transpondCity: [],
	repeatOptions: [
		//是否重复
		{
			value: '是',
			key: 'true',
		},
		{
			value: '否',
			key: 'false',
		},
	],
	industryOptions: [],
	focusOnEvents: [],
});
const appConfigStore = useAppConfig();
const { AppConfigInfo } = storeToRefs(appConfigStore); // 系统配置信息
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo); // 用户信息
const isProvinceOrder = ref(false); // 是否需要排除掉人社热点 默认否（宜宾）
// 查看工单详情
const getOrderDetail = async (id: string) => {
	state.loading = true;
	try {
		const { result } = await orderDetail(id);
		state.ruleForm = result;

		if (['YiBin'].includes(themeConfig.value.appScope)) {
			isProvinceOrder.value = state.ruleForm.source !== 100;
		}

		// 如果获取到id 调用查询详情
		state.ruleForm = Object.assign(state.ruleForm, result);
		state.ruleForm.files = transformFile(result.files);
		if (result.duplicateIds && result.duplicateIds.length) {
			// 是否重复
			state.ruleForm.isRepeat = 'true';
			state.ruleForm.duplicateTitle = '已选择';
		} else {
			state.ruleForm.isRepeat = 'false';
		}
		if (state.ruleForm.focusOnEvents) {
			// 重点关注事项
			state.ruleForm.focusOnEventsArr = result.focusOnEvents.split(',');
		}

		if (state.ruleForm.sourceChannelCode) {
			state.ruleForm.channel = {
				// 来源渠道
				dicDataValue: state.ruleForm.sourceChannelCode,
				dicDataName: state.ruleForm.sourceChannel,
			};
		}
		if (state.ruleForm.industryId) {
			state.ruleForm.industryObj = {
				// 行业分类
				id: state.ruleForm.industryId,
				name: state.ruleForm.industryName,
			};
		}
		if (state.ruleForm.hotspotExternal) {
			//热点分类默认展开
			state.hotspotExternal = state.ruleForm.hotspotExternal.split(',');
		}
		if (state.ruleForm.eventCategoryExternal) {
			//热点分类默认展开
			state.eventCategoryExternal = state.ruleForm.eventCategoryExternal.split(',');
		}
		if (state.ruleForm.licenceTypeCode) {
			state.ruleForm.licenceTypeObj = {
				// 证件类型
				dicDataValue: state.ruleForm.licenceTypeCode,
				dicDataName: state.ruleForm.licenceType,
			};
		}
		if (state.ruleForm.orderTagCode) {
			state.ruleForm.orderTagObj = {
				// 工单标签
				dicDataValue: state.ruleForm.orderTagCode,
				dicDataName: state.ruleForm.orderTag,
			};
		}

		if (!state.ruleForm.acceptType) {
			// 外部输入数据没有受理名称和热点名称 需要根据code调用一次change事件获取
			const currentAcceptType = state.acceptTypeOptions.find((item: any) => {
				return item.dicDataValue === state.ruleForm.acceptTypeCode;
			});
			state.ruleForm.acceptType = currentAcceptType?.dicDataName ?? '';
		}
		if (state.ruleForm.acceptTypeCode) {
			state.ruleForm.acceptTypeObj = {
				// 受理类型
				dicDataValue: state.ruleForm.acceptTypeCode,
				dicDataName: state.ruleForm.acceptType,
			};
		}
		if (state.ruleForm.transpondCityValue) {
			state.ruleForm.transpondCityObj = {
				// 市州互转
				dicDataValue: state.ruleForm.transpondCityValue,
				dicDataName: state.ruleForm.transpondCityName,
			};
		}

		state.dialogVisible = true;
		state.loading = false;
	} catch (error) {
		state.loading = false;
		state.dialogVisible = false;
	}
};
// 打开弹窗
const openDrawer = (id: string) => {
	getOrderDetail(id);
};
//
// 关闭弹窗
const closeDrawer = () => {
	state.dialogVisible = false;
};
// 选择来源渠道
const changeChannel = (val: any) => {
	state.ruleForm.fromPhone = null;
	state.ruleForm.sourceChannel = val?.dicDataName ?? null;
	state.ruleForm.sourceChannelCode = val?.dicDataValue ?? null;
	ruleFormRef.value.resetFields('fromPhone'); // 清除来电号码
	const item = state.pushTypeOptions.find((item: any) => item.dicDataValue === '7'); // 110
	if (['110', 'YB110'].includes(val?.dicDataValue)) {
		// 如果来源渠道选择了110 推送分类联动选择110
		state.ruleForm.orderPushTypes.push(item);
	} else {
		// 清除110选择
		state.ruleForm.orderPushTypes = state.ruleForm.orderPushTypes.filter((item: any) => item.dicDataValue !== '7');
	}
};
// 选择来点人身份如果是企业 推送分类自动选择助企纾困
const selectIdentity = (val: number) => {
	if (val === 2) {
		const item = state.pushTypeOptions.find((item: any) => item.dicDataValue === '8'); // 助企纾困
		// 如果已经选择了助企纾困就不添加
		if (item) {
			if (state.ruleForm.orderPushTypes.includes(item)) return;
			state.ruleForm.orderPushTypes.push(item);
		}
	} else {
		// 如果选择其他需要清除
		state.ruleForm.orderPushTypes = state.ruleForm.orderPushTypes.filter((item: any) => item.dicDataValue !== '8');
	}
};
// 填写来电人姓名时根据填写内容自动选择性别
const inputName = (val: string) => {
	if (val.includes('先生')) {
		state.ruleForm.fromGender = 1;
	} else if (val.includes('女士')) {
		state.ruleForm.fromGender = 0;
	}
};
// 选择证件类型
const changeLicenceType = (val: any) => {
	state.ruleForm.licenceType = val?.dicDataName ?? null;
	state.ruleForm.licenceTypeCode = val?.dicDataValue ?? null;
};
// 选择受理类型
const changeAcceptType = (val: any) => {
	state.ruleForm.acceptType = val?.dicDataName ?? null;
	state.ruleForm.acceptTypeCode = val?.dicDataValue ?? null;
};
// 选择行业类型
const changeIndustry = (val: any) => {
	state.ruleForm.industryId = val?.id ?? null;
	state.ruleForm.industryName = val?.name ?? null;
};
// 选择工单标签
const changeOrderTag = (val: any) => {
	state.ruleForm.orderTag = val?.dicDataName ?? null;
	state.ruleForm.orderTagCode = val?.dicDataValue ?? null;
};
// 选择事件分类
const chooseEvent = (val: any, node: any, externalArr: any) => {
	state.ruleForm.eventCategoryName = val?.eventName; // 事件分类名称
	state.ruleForm.eventCategorySpliceName = val?.eventFullName; // 事件分类拼接名称
	state.ruleForm.eventCategoryExternal = externalArr?.join(',') ?? ''; // 事件分类id
};
// 选择热点分类
const knowledgeRef = ref<RefType>();
const chooseHotSpot = (val: any, node: any, externalArr: any) => {
	state.ruleForm.hotspotSpliceName = val?.hotSpotFullName; // 热点分类拼接名称
	state.ruleForm.hotspotName = val?.hotSpotName; // 热点分类名称
	state.ruleForm.hotspotCode = val?.provinceCode; // 热点分类code
	state.ruleForm.hotspotExternal = externalArr?.join(',') ?? ''; // 热点分类默认展开项
	knowledgeRef.value.querySearch(state.ruleForm.hotspotName);
};
// 获取事发地址
const areaRef = ref<RefType>();
const changeArea = () => {
	const currentNode = areaRef.value.getCheckedNodes();
	// 判断数组长度
	if (currentNode[0].pathLabels.length <= 4) {
		state.ruleForm.city = currentNode[0].pathLabels[0] ?? ''; // 市
		state.ruleForm.county = currentNode[0].pathLabels[1] ?? ''; // 区
		state.ruleForm.town = currentNode[0].pathLabels[2] ?? ''; // 地区
	} else {
		// 如果数组长度大于4
		state.ruleForm.city = currentNode[0].pathLabels[0] ?? ''; // 市
		state.ruleForm.county = currentNode[0].pathLabels[1] ?? ''; // 区
		state.ruleForm.town = currentNode[0].pathLabels[2] ?? ''; // 地区
		state.ruleForm.areaText = currentNode[0].pathLabels.slice(3).join('') ?? ''; // 地区
		console.log(state.ruleForm.areaText);
	}
};
// 选择重点关注事项
const changeFocusEvent = (val: string[]) => {
	state.ruleForm.isUrgent = val.includes('0'); // 是否紧急工单
	state.ruleForm.isFormalistWorkOrder = val.includes('1'); // 是否形式主义工单
	state.ruleForm.isSensitiveWorkOrders = val.includes('3'); // 是否敏感类工单
	state.ruleForm.isEnforcementOrder = val.includes('2'); // 是否行政执法类工单
	state.ruleForm.is24HoursComplete = val.includes('4'); // 24小时紧急工单
	state.ruleForm.acceptSms = val.includes('5'); // 受理短信
	state.ruleForm.isThreePartyConference = val.includes('6'); // 三方通话
	state.ruleForm.isSecret = val.includes('99'); // 是否保密
	state.ruleForm.focusOnEventsName = state.focusOnEvents
		.filter((item: any) => val.includes(item.dicDataValue))
		.map((item: any) => item.dicDataName)
		.join(',');
	if (state.ruleForm.sourceChannelCode === 'ZGSSP') {
		//如果 选择了自贡随手拍
		if (state.ruleForm.isSecret) {
			// 如果选择了保密 需要吧三方通话也选上
			state.ruleForm.isThreePartyConference = true;
			state.ruleForm.focusOnEventsArr = removeDuplicate([...state.ruleForm.focusOnEventsArr, '6']);
		}
	}
	state.ruleForm.focusOnEvents = state.ruleForm.focusOnEventsArr.join(',');
	console.log(
		`是否紧急工单:${val.includes('0')},是否行政执法类类工单:${val.includes('2')},是否形式主义工单:${val.includes('1')},是否敏感类工单:${val.includes(
			'3'
		)},是否24小时紧急工单:${val.includes('4')},是否受理短信:${val.includes('5')},是否三方通话:${val.includes('6')},是否保密:${val.includes('99')}`
	);
};
// 选择企业
const companySearchRef = ref<RefType>();
const handleSelect = () => {
	companySearchRef.value.openDialog();
};
// 选择企业
const selectCompany = (row: any) => {
	state.ruleForm.enterpriseName = row.enterpriseName;
	state.ruleForm.enterpriseCode = row.enterpriseCode;
	state.ruleForm.zhuanBanMingCheng = row.specialTeamName;
	state.ruleForm.zhuanBanCode = row.specialTeamCode;
};
// 根据热点和事发地址去查询重复性事件 是否展示重复性事件
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 isRepeatChange = (val: string) => {
	if (val === 'false') clearRepeat();
};
// 清除重复件
const clearRepeat = () => {
	ElMessageBox.confirm(`确认要清除选择的重复工单?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			orderRepeatSelectRef.value.clearSelection();
			setTimeout(() => {
				state.ruleForm.duplicateTitle = null;
				state.ruleForm.duplicateIds = [];
			}, 100);
		})
		.catch(() => {
			state.ruleForm.isRepeat = 'true';
		});
};
// 选择重复件
const orderRepeatSelectRef = ref<RefType>();
const selectRepeat = () => {
	orderRepeatSelectRef.value.openDialog(state.ruleForm);
};
// 确定选择重复工单
const orderRepeatSuccess = (row: any) => {
	state.ruleForm.duplicateIds = row.map((item: any) => item.id);
	state.ruleForm.duplicateTitle = '已选择';
	orderRepeatSelectRef.value.closeDialog();
};
// 选择是否市州互转
const changeTransPond = (val: any) => {
	if (!val) {
		ElMessageBox.confirm(`确认要清除选择的互转市州?`, '提示', {
			confirmButtonText: '确认',
			cancelButtonText: '取消',
			type: 'warning',
			draggable: true,
			cancelButtonClass: 'default-button',
			autofocus: false,
		})
			.then(() => {
				setTimeout(() => {
					state.ruleForm.transpondCityValue = null;
					state.ruleForm.transpondCityName = null;
					state.ruleForm.transpondCityId = null;
					state.ruleForm.transpondCityObj = null;
				}, 100);
			})
			.catch(() => {
				state.ruleForm.transpond = true;
			});
	}
};
// 选择市州互转
const changeTranspondCity = (val: any) => {
	state.ruleForm.transpondCityId = val?.id ?? null;
	state.ruleForm.transpondCityValue = val?.dicDataValue ?? null;
	state.ruleForm.transpondCityName = val?.dicDataName ?? null;
};
// 填写标题时根据填写内容自动选择受理类型
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 chooseAdvice = (item: any) => {
	state.ruleForm.content += item.content;
};
// 查看录音文件 播放录音
const playRecordRef = ref<RefType>();
const recordFile = (obj: any) => {
	playRecordRef.value.playRecord(obj.callId);
};
// 将当前工单添加到重复性事件中
const repeatableEventDetails = ref<EmptyArrayType>([]);
// 删除不必要的属性
const deleteUnnecessaryProperties = (obj: any) => {
	const propertiesToDelete = ['ageRangeObj', 'licenceTypeObj', 'channel', 'acceptTypeObj', 'transpondCity', 'orderTagObj'];
	propertiesToDelete.forEach((prop) => Reflect.deleteProperty(obj, prop));
};
// 保存
const ruleFormRef = ref<RefType>();
const emit = defineEmits(['updateList']);
const save = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		let orderDetail = {
			...state.ruleForm,
			repeatableEventDetails: repeatableEventDetails.value,
			isEdit: true,
		};
		deleteUnnecessaryProperties(orderDetail);
		const addOrderAndNavigate = () => {
			orderEdit(orderDetail)
				.then(() => {
					state.loading = false;
					emit('updateList');
					closeDrawer();
					ElMessage.success('保存成功');
				})
				.catch(() => {
					state.loading = false;
				});
		};
		addOrderAndNavigate();
	});
};
// 加载基础数据
const loadBaseData = async () => {
	try {
		const { result } = await orderBaseDataAdd();
		state.acceptTypeOptions = result?.acceptTypeOptions ?? [];
		state.channelOptions = result?.channelOptions ?? [];
		state.genderOptions = result?.genderOptions ?? [];
		state.identityTypeOptions = result?.identityTypeOptions ?? [];
		state.pushTypeOptions = result?.pushTypeOptions ?? [];
		state.licenceTypeOptions = result?.licenceTypeOptions ?? [];
		state.transpondCity = result?.transpondCity ?? [];
		state.focusOnEvents = result?.focusOnEvents ?? [];
		state.focusOnEvents.unshift({ dicDataName: '保密', dicDataValue: '99' });
		state.orderTags = result?.orderTags ?? [];
		state.pushTypeOptions = state.pushTypeOptions.map((item: any) => {
			return {
				...item,
				pushTypeCode: item.dicDataValue,
				pushType: item.dicDataName,
			};
		});
		state.industryOptions = result.industry ?? []; // 行业分类
	} catch (error) {
		console.log(error);
	}
};
// 加载省市区
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 getCurrentData = (val: any) => {
	if (state.ruleForm.id || state.ruleForm.no) {
		if (!state.ruleForm.hotspotName || !state.ruleForm.hotspotSpliceName) {
			state.ruleForm.hotspotName = val?.data?.hotSpotName;
			state.ruleForm.hotspotSpliceName = val?.data?.hotSpotFullName;
			state.ruleForm.hotspotCode = val?.data?.provinceCode;
		}
	}
};
onMounted(() => {
	loadBaseData();
	loadAddress();
});
defineExpose({
	openDrawer,
	closeDrawer,
});
</script>
