<template>
	<div class="order-edit-container layout-padding">
		<el-row :gutter="15" class="h100">
			<!-- 左边工单信息 -->
			<el-col :span="12" class="left-content mb20 h100">
				<el-scrollbar class="box pd20">
					<!-- <div class="flex-center-between mb20">
						<p class="table-title">工单信息</p>
					</div> -->
					<el-form
						:model="state.ruleForm"
						ref="ruleFormRef"
						label-width="110px"
						label-position="right"
						scroll-to-error
						v-loading="state.formLoading"
					>
						<p class="border-title mb10">来电信息</p>
						<el-row :gutter="0">
							<!-- 来源渠道 -->
							<el-col :span="12">
								<!-- 手动创建 -->
								<template v-if="state.createFrom == 'manual'">
									<el-form-item label="来源渠道" prop="channel" :rules="[{ required: true, message: '请选择来源渠道', trigger: 'change' }]">
										<el-select v-model="state.ruleForm.channel" placeholder="请选择来源渠道" class="w100">
											<el-option v-for="item in state.channelOptions" :key="item.key" :label="item.value" :value="item.key" />
										</el-select>
									</el-form-item>
								</template>
								<!-- 来电弹单 -->
								<template v-else-if="state.createFrom == 'tel'">
									<el-form-item label="来源渠道">
										<span>[{{ telStatusInfo.telsNo }}]</span>
									</el-form-item>
								</template>
								<!-- 互联网来信 -->
								<template v-else-if="state.createFrom == 'letter'">
									<el-form-item label="来源渠道">
										<span>[{{ telStatusInfo.telsNo }}]</span>
									</el-form-item>
								</template>
							</el-col>
							<!-- 转接来源 -->
							<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
								<!-- 手动创建 -->
								<template v-if="state.createFrom == 'manual'">
									<el-form-item label="转接来源" prop="transferPhone"> 暂无 </el-form-item>
								</template>
								<!-- 来电弹单 -->
								<template v-else-if="state.createFrom == 'tel'">
									<el-form-item label="转接来源">
										<span>[{{ telStatusInfo.telsNo }}]</span>
									</el-form-item>
								</template>
								<!-- 互联网来信 -->
								<template v-else-if="state.createFrom == 'letter'">
									<el-form-item label="转接来源">
										<span>[{{ telStatusInfo.telsNo }}]</span>
									</el-form-item>
								</template>
							</el-col>
							<!-- 来电号码 -->
							<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="state.ruleForm.channel == 0">
								<!-- 手动创建 -->
								<template v-if="state.createFrom == '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 @blur="searchHistory"> </el-input>
									</el-form-item>
								</template>
								<!-- 来电弹单 -->
								<template v-else-if="state.createFrom == 'tel'">
									<el-form-item label="来电号码">
										<span>[{{ telStatusInfo.telsNo }}]</span>
									</el-form-item>
								</template>
								<!-- 互联网来信 -->
								<template v-else-if="state.createFrom == 'letter'">
									<el-form-item label="来电号码">
										<span>[{{ phoneNumber }}]</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.createFrom == 'manual'">
										<span>{{ state.ruleForm.employeeName + '[' + state.ruleForm.employeeStaffNo + ']' }}</span>
									</template>
									<!-- 来电弹单 -->
									<template v-else-if="state.createFrom == 'tel'">
										<span>[{{ telStatusInfo.telsNo }}]</span>
									</template>
									<!-- 互联网来信 -->
									<template v-else-if="state.createFrom == '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-input v-model="state.ruleForm.fromName" 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="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">
										<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"
										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"
										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: !state.ruleForm.needContact, 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.contact"
										:disabled="state.ruleForm.needContact"
										:placeholder="state.ruleForm.needContact ? '无需联系' : '请填写联系电话'"
										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="acceptSms" :rules="[{ required: false, message: '请选择', trigger: 'blur' }]">
									<el-checkbox v-model="state.ruleForm.acceptSms" label="受理短信" :disabled="state.ruleForm.needContact" />
									<el-checkbox
										v-model="state.ruleForm.needContact"
										label="无需联系"
										@change="
											() => {
												ruleFormRef.resetFields('contact');
												ruleFormRef.resetFields('acceptSms');
											}
										"
									/>
								</el-form-item>
							</el-col>
							<!-- 当“来电/信人身份”为“企业”时必填 -->
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item
									label="工作单位"
									prop="company"
									:rules="[{ required: state.ruleForm.identityType === 2, message: '请填写工作单位', trigger: 'blur' }]"
								>
									<el-input v-model="state.ruleForm.company" placeholder="请填写工作单位" clearable> </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">
								<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-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-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.acceptType">
										<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="acceptType" :rules="[{ required: true, message: '请选择受理类型', trigger: 'change' }]">
									<el-select v-model="state.ruleForm.acceptType" placeholder="请选择受理类型" class="w100">
										<el-option
											v-for="item in state.acceptTypeOptions"
											:key="item.key"
											:disabled="item.disabled"
											: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="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
										clearable
										placeholder="请选择热点分类"
										:props="HotspotProps"
										lazy
										:load="load"
										node-key="id"
										check-strictly
										:render-after-expand="false"
										@node-click="hotsoptChange"
										ref="hotspotRef"
										: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"
									/>
									<!-- value-format="YYYY-MM-DD" -->
								</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 }"
												placeholder="请选择事发地址"
												class="w100"
												v-model="state.ruleForm.areaCode"
												ref="areaRef"
												@change="changeArea"
											>
												<template #default="{ node, data }">
													<span>{{ data.areaName }}</span>
													<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
												</template>
											</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: true, message: '请填写详细地址', trigger: 'blur' }]" label-width="10px">
											<el-input v-model="state.ruleForm.street" placeholder="请填写详细地址" clearable> </el-input>
										</el-form-item>
									</el-col>
								</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">
														<SvgIcon name="ele-Delete" size="16px" />
													</el-button>
													<el-button link type="primary" class="ml1" @click="selectRepat">
														<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="content" :rules="[{ required: true, message: '请填写诉求详情', trigger: 'blur' }]">
									<Comment
										@chooseComment="chooseComment"
										v-model="state.ruleForm.content"
										placeholder="请填写诉求详情"
										:loading="state.formLoading"
										:commonEeum="commonEeum.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' }]">
									<Upload :fileList="state.fileList" />
								</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"> 保存 </el-button>
									<el-button type="primary" v-waves @click="submit"> 提交 </el-button>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-scrollbar>
			</el-col>
			<!-- 右侧内容 -->
			<el-col :span="12" class="right-content h100">
				<el-scrollbar>
					<div class="right-content-box box pd20">
						<!-- <el-tabs v-model="state.activeName">
							<el-tab-pane label="历史工单" name="first"> </el-tab-pane>
							<el-tab-pane label="市民画像" name="second"> 市民画像 </el-tab-pane>
						</el-tabs> -->
						<el-form :model="state.queryParams" ref="queryParamsRef" :inline="true" @submit.native.prevent>
							<el-form-item label="关键词" prop="Keyword">
								<el-input v-model="state.queryParams.Keyword" placeholder="工单标题/工单编码" clearable @keyup.enter="handleQuery" />
							</el-form-item>
							<el-form-item>
								<el-button type="primary" @click="handleQuery" :loading="state.historyOrderLoading">
									<SvgIcon name="ele-Search" class="mr5" />查询
								</el-button>
								<el-button @click="resetQuery(queryParamsRef)" :loading="state.historyOrderLoading" class="default-button">
									<SvgIcon name="ele-Refresh" class="mr5" />重置
								</el-button>
							</el-form-item>
						</el-form>
						<el-table :data="state.tableData" v-loading="state.historyOrderLoading" @current-change="handleSelectionChange" max-height="300">
							<el-table-column prop="phoneNo" label="重复件" width="70" v-if="state.ruleForm.isRepeat === 'true'">
								<template #default="scope">
									<el-radio v-model="state.tableRadio" :label="scope.row.id" @change="handleRowChange(scope.row)">&nbsp;</el-radio>
								</template>
							</el-table-column>
							<el-table-column type="index" width="60" label="序号" />
							<el-table-column prop="phoneNo" label="工单标题" show-overflow-tooltip width="180">
								<template #default="scope">
									<span style="color: var(--el-color-primary)">{{ scope.row.title }}</span>
								</template>
							</el-table-column>
							<el-table-column prop="hotspot" label="热点分类" show-overflow-tooltip> </el-table-column>
							<el-table-column prop="no" label="工单编码" show-overflow-tooltip> </el-table-column>
							<el-table-column prop="currentStepName" label="当前环节" show-overflow-tooltip></el-table-column>
							<el-table-column prop="statusText" label="状态" width="70" fixed="right" align="center">
								<template #default="scope">
									<!-- 草稿 -->
									<span style="color: var(--el-color-info)" v-if="scope.row.status === 0">{{ scope.row.statusText }}</span>
									<!-- 待签收 -->
									<span style="color: var(--el-color-success)" v-if="scope.row.status === 10">{{ scope.row.statusText }}</span>
									<!-- 办理中 -->
									<span style="color: var(--el-color-primary)" v-if="scope.row.status === 20">{{ scope.row.statusText }}</span>
									<!-- 会签中 -->
									<span style="color: var(--el-color-primary)" v-if="scope.row.status === 30">{{ scope.row.statusText }}</span>
									<!-- 退回 -->
									<span style="color: var(--el-color-danger)" v-if="scope.row.status === 40">{{ scope.row.statusText }}</span>
									<!-- 办理完成 -->
									<span style="color: var(--el-color-success)" v-if="scope.row.status === 50">{{ scope.row.statusText }}</span>
									<!-- 已归档 -->
									<span style="color: var(--el-color-info)" v-if="scope.row.status === 60">{{ scope.row.statusText }}</span>
								</template>
							</el-table-column>
							<el-table-column prop="statusText" label="操作" width="70" fixed="right" align="center">
								<template #default="scope">
									<el-button link type="primary" @click="onSupply(scope.row)"> 补充 </el-button>
								</template>
							</el-table-column>
						</el-table>
						<!-- 分页 -->
						<pagination
							:total="state.total"
							v-model:page="state.queryParams.PageIndex"
							v-model:limit="state.queryParams.PageSize"
							@pagination="searchHistory"
						/>
					</div>
					<div class="right-content-knowledge mt20 box pd20">
						<div class="flex-center-between mb20">
							<p class="table-title">知识检索</p>
						</div>
						<div class="knowledge-container">
							<el-input
								v-model="state.KnowledgeKeyword"
								class="knowledge-input mb20"
								placeholder="请填写搜索内容"
								@keyup.enter="searchKnowledge(state.KnowledgeKeyword)"
							>
								<template #prefix>
									<SvgIcon name="ele-Search" size="16px" />
								</template>
								<template #suffix>
									<el-button
										class="knowledge-search-button"
										type="primary"
										:loading="state.loading"
										round
										@click="searchKnowledge(state.KnowledgeKeyword)"
									>
										<SvgIcon name="ele-Search" size="16px" color="#fff" />
									</el-button>
								</template>
							</el-input>
							<div>
								<span class="mr10" v-if="state.items.length">搜索热词</span>
								<el-tag
									v-for="(item, index) in state.hotWords"
									:key="index"
									class="mr10 mb10"
									style="cursor: pointer"
									@click="knowretrievalPaged(item)"
									round
								>
									{{ item }}
								</el-tag>
							</div>
							<ul class="mt10" v-loading="state.loading">
								<el-empty description="暂无数据" v-if="!state.knowledgeList.length" class="mb20">
									<template #image>
										<span></span>
									</template>
								</el-empty>
								<li v-for="(item, index) in state.knowledgeList" :key="index" class="mb20" v-else>
									<p class="font16">
										<SvgIcon name="iconfont icon-dian" size="16px" /> <b>{{ item.title }}</b>
									</p>
									<p class="pt6 indent text-ellipsis2" v-html="item.content"></p>
								</li>
							</ul>
						</div>
						<!-- 分页 -->
						<pagination
							:total="state.knowledgeTotal"
							v-model:page="state.knowledgequery.PageIndex"
							v-model:limit="state.knowledgequery.PageSize"
							@pagination="knowretrievalPaged(state.KnowledgeKeyword)"
							:pageSizes="[5, 10, 15, 20]"
							layout="total, prev, pager, next"
						/>
					</div>
				</el-scrollbar>
			</el-col>
		</el-row>
		<!-- 拓展表单 -->
		<ExpandForm ref="ExpandFormRef" @saveExpandForm="saveExpandForm" v-if="state.expandFormMouted"/>
		<!-- 历史工单 -->
		<History ref="HistoryOrderRef" @saveSlect="saveSlect" />
		<!-- 提交流程 -->
		<Process ref="processRef" @submitProcessSuccess="submitProcessSuccess" />
		<!-- 补充信息 -->
		<Supply ref="SupplyRef" @onSupplySubmit="onSupplySubmit" />
	</div>
</template>

<script setup lang="ts" name="orderEdit">
import { defineAsyncComponent, ref, reactive, computed, onMounted, nextTick } from 'vue';
import { ElMessage } 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 { desensitizationPhone, commonEeum } from '/@/utils/tools';
import { orderBasedataAdd, hotspottype, historyOrder, orderDetail, orderEdit } from '/@/api/business/order';
import { useUserInfo } from '/@/stores/userInfo';
import { treeArea } from '/@/api/business/commonP';
import { knowpopscreen, getkeyword } from '/@/api/knowledge';
import mittBus from '/@/utils/mitt';

// 引入组件
const Process = defineAsyncComponent(() => import('/@/views/business/order/components/Process.vue'));
const ExpandForm = defineAsyncComponent(() => import('/@/views/business/order/components/ExpandForm.vue'));
const History = defineAsyncComponent(() => import('/@/views/business/order/components/History.vue'));
const Comment = defineAsyncComponent(() => import('/@/views/business/order/components/Comment.vue'));
const Supply = defineAsyncComponent(() => import('/@/views/business/order/components/Supply.vue'));
const Upload = defineAsyncComponent(() => import('/@/components/Upload/index.vue'));
// 定义变量内容
const state = reactive<any>({
	createFrom: 'manual', // 工单创建方式 默认手动创建  tel:来电弹单  letter:互联网来信 默认表示手动创建
	activeName: 'first', // tabs
	ruleForm: {
		// 表单
		street: '',
		transferPhone: '',
		employeeName: '',
		employeeStaffNo: '',
		duplicateTitle: '',
		duplicateId: '',
		content: '',
		acceptSms: false,
		needContact: false,
		fromPhone:'',
	},
	formLoading: false, // 表单加载状态
	historyOrderLoading: false, // 历史工单加载状态
	loading: false, // 知识检索加载状态
	acceptTypeOptions: [], // 受理类型
	channelOptions: [], // 来源频道
	emergencyLevelOptions: [], // 紧急程度
	genderOptions: [], // 性别
	identityTypeOptions: [], //来电人身份
	licenceTypeOptions: [], // 证件类型
	ageRangeOptions: [], // 年龄段
	orderTypeOptions: [], // 工单类型
	pushTypeOptions: [], //推送分类
	areaOptions: [], //省市区
	repeatOptions: [
		//是否重复
		{
			value: '是',
			key: 'true',
		},
		{
			value: '否',
			key: 'false',
		},
	],
	tableRadio: null as any, // 重复件选择
	orgData: [],
	tableData: [], // 历史工单
	total: 0,
	queryParams: {
		PageIndex: 1,
		PageSize: 10,
		Keyword: '',
	},
	KnowledgeKeyword: '', //知识检索内容
	items: [],
	knowledgeList: [], //知识检索列表
	external: [],
	hotspotExternal: [], // 热点分类展开
	knowledgequery: {
		// 知识库查询
		PageIndex: 1,
		PageSize: 5,
		Keyword: '',
	},
	knowledgeTotal: 0, // 知识库总条数
	fileList: [],
	expandFormMouted:false,
});
const ruleFormRef = ref();
const queryParamsRef = ref();
const useTelStatusStore = useTelStatus();
const { telStatusInfo } = storeToRefs(useTelStatusStore);
const processRef = ref();
const storesUserInfo = useUserInfo();
const { userInfos } = storeToRefs(storesUserInfo);
state.ruleForm.employeeName = userInfos.value.name;
state.ruleForm.employeeStaffNo = userInfos.value.staffNo;
const route = useRoute();
const router = useRouter();
const HistoryOrderRef = ref();
const hotspotRef = ref();
const SupplyRef = ref();
// 证件号码验证
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]$/;
			break;

		default: //默认只允许数字字母
			return /^[A-Za-z0-9]+$/;
			break;
	}
});
// 热点分类远程搜索
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 hotsoptChange = (val: any, e: any) => {
	state.hotspotExternal = [];
	state.external = [];
	state.hotspotExternal = getParentId(e, state.external);
	state.ruleForm.hotspotSpliceName = val.hotSpotFullName;
	state.ruleForm.hotspot = val.hotSpotName;
	knowretrievalPaged(val.hotSpotName);
};
//  知识检索
const knowretrievalPaged = async (val?: string) => {
	if (val) {
		state.knowledgequery.Keyword = val;
		state.KnowledgeKeyword = val;
	} else {
		state.knowledgequery.Keyword = '';
		state.KnowledgeKeyword = '';
	}
	try {
		state.loading = true;
		const res: any = await knowpopscreen(state.knowledgequery);
		state.knowledgeList = res.result?.items ?? [];
		state.knowledgeTotal = res.result?.total ?? 0;
		state.loading = false;
	} catch (error) {
		state.loading = false;
	}
};
// 递归查找父级Id
const getParentId = (val: any, arr: string[]) => {
	if (val.data.parentId) {
		arr.push(val.data.parentId);
		getParentId(val.parent, arr);
	}
	return arr;
};
// 手机号码脱敏处理
const phoneNumber = computed(() => {
	return desensitizationPhone(telStatusInfo.value.onCallArr[0]?.from);
});
// 选择工单类型 处理受理类型选择数据
const selectOrderType = (val: any) => {
	ruleFormRef.value.resetFields('acceptType');
	if (val === 1) {
		// 选择了12315市场监管受理单
		state.acceptTypeOptions = state.acceptTypeOptions.map((item: any) => {
			if (item.key === 5 || item.key === 6) {
				//直接投诉或者建议
				return {
					key: item.key,
					value: item.value,
					disabled: false,
				};
			} else {
				return {
					key: item.key,
					value: item.value,
					disabled: true,
				};
			}
		});
	} else {
		state.acceptTypeOptions = state.acceptTypeOptions.map((item: any) => {
			return {
				key: item.key,
				value: item.value,
				disabled: false,
			};
		});
	}
};
const areaRef = ref();
// 选择省市区
const changeArea = () => {
	const currentNode = areaRef.value.getCheckedNodes();
	state.ruleForm.province = currentNode[0]?.pathLabels[0] ?? '';
	state.ruleForm.city = currentNode[0]?.pathLabels[1] ?? '';
	state.ruleForm.county = currentNode[0]?.pathLabels[2] ?? '';
};
const ExpandFormRef = ref();
// 打开拓展表单
const showExpandForm = () => {
	ExpandFormRef.value.openDialog(state.ruleForm.acceptType);
};
// 拓展表单保存
const saveExpandForm = (val: any) => {
	switch (state.ruleForm.acceptType) {
		case 5: //举报
			state.ruleForm.orderReport = val;
			break;
		case 6: //投诉
			state.ruleForm.orderComplain = val;
			break;
		default:
			break;
	}
};
// 保存
const save = () => {
	ruleFormRef.value.validate((valid: boolean) => {
		if (valid) {
			state.ruleForm.hotspotExternal = state.hotspotExternal.join(',');
			let submitObj = JSON.parse(JSON.stringify(state.ruleForm));
			Reflect.deleteProperty(submitObj, 'ageRangeObj'); // 删除无用的参数 年龄段
			Reflect.deleteProperty(submitObj, 'pushTypeObj'); // 删除无用的参数 推送分类
			Reflect.deleteProperty(submitObj, 'licenceTypeObj'); // 删除无用的参数 证件类型
			if (submitObj.acceptType === 5) Reflect.deleteProperty(submitObj, 'orderComplain'); // 举报 删除投诉表单
			if (submitObj.acceptType === 6) Reflect.deleteProperty(submitObj, 'orderReport'); // 投诉 删除举报表单
			if (submitObj.orderType === 1 && submitObj.acceptType) {
				//拓展表单
				if (ExpandFormRef.value.state.validated) {
					//验证通过
					orderEdit(submitObj).then(() => {
						ElMessage.success('操作成功');
						// 关闭当前 tagsView
						mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
						mittBus.emit('clearCache', 'order');
						router.replace({
							path: '/business/order',
						});
					});
				} else {
					//不通过 展示弹窗
					ExpandFormRef.value.openDialog(submitObj.acceptType, true); // 立即提交展示验证
				}
			} else {
				// 修改
				orderEdit(submitObj).then(() => {
					ElMessage.success('操作成功');
					// 关闭当前 tagsView
					mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
					mittBus.emit('clearCache', 'order');
					router.replace({
						path: '/business/order',
					});
				});
			}
		} else {
			return false;
		}
	});
};
// 提交
const submit = () => {
	ruleFormRef.value.validate((valid: boolean) => {
		if (valid) {
			state.ruleForm.hotspotExternal = state.hotspotExternal.join(',');
			let submitObj = JSON.parse(JSON.stringify(state.ruleForm));
			Reflect.deleteProperty(submitObj, 'ageRangeObj'); // 删除无用的参数 年龄段
			Reflect.deleteProperty(submitObj, 'pushTypeObj'); // 删除无用的参数 推送分类
			Reflect.deleteProperty(submitObj, 'licenceTypeObj'); // 删除无用的参数 证件类型
			if (submitObj.acceptType === 5) Reflect.deleteProperty(submitObj, 'orderComplain'); // 举报 删除投诉表单
			if (submitObj.acceptType === 6) Reflect.deleteProperty(submitObj, 'orderReport'); // 投诉 删除举报表单
			if (submitObj.orderType === 1 && submitObj.acceptType) {
				//拓展表单
				if (ExpandFormRef.value.state.validated) {
					// 修改
					orderEdit(submitObj).then(() => {
						processRef.value.openDialog({ id: route.params.id, title: '提交', commonEeum: commonEeum.Seat, processType: 'start' });
					});
				} else {
					//不通过 展示弹窗
					ExpandFormRef.value.openDialog(submitObj.acceptType, true); // 立即提交展示验证
				}
			} else {
				// 修改
				orderEdit(submitObj).then(() => {
					processRef.value.openDialog({ id: route.params.id, title: '提交', commonEeum: commonEeum.Seat, processType: 'start' });
				});
			}
		} else {
			return false;
		}
	});
};
// 选择是否重复
const isRepeatChange = (val: string) => {
	if (val === 'false') clearRepeat();
};
// 清除重复件
const clearRepeat = () => {
	state.ruleForm.duplicateTitle = '';
	state.ruleForm.duplicateId = '';
	state.tableRadio = '';
};
// 选择重复件
const selectRepat = () => {
	HistoryOrderRef.value.openDialog(state.ruleForm);
};
// 弹窗确定选择重复件
const saveSlect = (row: any) => {
	state.ruleForm.duplicateId = row.id;
	state.ruleForm.duplicateTitle = row.title;
	state.tableRadio = row.id;
	HistoryOrderRef.value.closeDialog();
};
// 右边表格选中重复件
const handleSelectionChange = (row: any) => {
	if (row) {
		state.ruleForm.duplicateId = row.id;
		state.tableRadio = row.id;
		state.ruleForm.duplicateTitle = row.title;
	}
};
// 选择重复件
const handleRowChange = (row: any) => {
	state.ruleForm.duplicateId = row.id;
	state.ruleForm.duplicateName = row.title;
};
// 选中常用意见
const chooseComment = (item: any) => {
	state.ruleForm.content += item.content;
};
// 历史工单搜索
const searchKnowledge = (value?: string) => {
	if (value) state.KnowledgeKeyword = value;
	state.historyOrderLoading = true;
	state.historyOrderLoading = false;
};
// 流程提交成功
const submitProcessSuccess = () => {
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'order');
	router.push({
		path: '/business/order',
	});
};
/** 搜索按钮操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	searchHistory();
};
/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	handleQuery();
};
/** 获取历史工单 */
const searchHistory = () => {
	if(!state.ruleForm.fromPhone) return;// 如果没有来电号码 不进行查询
	state.historyOrderLoading = true;
	let request = {
		...state.queryParams,
		PhoneNo: state.ruleForm.fromPhone,
		OrderId: route.params.id, //传入id 排除重复工单选择自己
	};
	historyOrder(request)
		.then((response: any) => {
			state.tableData = response?.result.items ?? [];
			state.total = response?.result.total;
			setTimeout(() => {
				state.historyOrderLoading = false;
			}, 300);
		})
		.catch(() => {
			state.historyOrderLoading = false;
		});
};
// 补充信息
const onSupply = (val: any) => {
	SupplyRef.value.openDialog(val);
};
// 补充意见提交成功
const onSupplySubmit = () => {
	searchHistory();
};
onMounted(async () => {
	nextTick(async () => {
		if (route.params.id) {
			state.formLoading = true;
			state.historyOrderLoading = true;
			state.loading = true;
			try {
				const area: any = await treeArea();
				const res: any = await orderBasedataAdd(); //基础数据
				const hotspot: any = await getkeyword(); // 获取知识检索热词
				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 ?? []; //省市区数据
				state.hotWords = hotspot.result ?? [];
				// 如果获取到id 调用查询详情
				const response: any = await orderDetail(route.params.id);
				state.ruleForm = response.result;
				if (state.ruleForm.channel === 0) {
					// 来源渠道为电话查询历史工单
					searchHistory();
				}
				if (state.ruleForm.orderType === 1) {
					// 工单类型 选择了12315市场监管受理单
					state.acceptTypeOptions = state.acceptTypeOptions.map((item: any) => {
						if (item.key === 5 || item.key === 6) {
							//直接投诉或者建议
							return {
								key: item.key,
								value: item.value,
								disabled: false,
							};
						} else {
							return {
								key: item.key,
								value: item.value,
								disabled: true,
							};
						}
					});
					state.expandFormMouted = true;
				}
				if (response.result.duplicateId) {
					// 是否重复
					state.ruleForm.isRepeat = 'true';
					state.tableRadio = state.ruleForm.duplicateId;
				} else {
					state.ruleForm.isRepeat = 'false';
				}
				if (response.result.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.pushTypeObj = {
					// 推送分类
					dicDataValue: state.ruleForm.pushTypeCode,
					dicDataName: state.ruleForm.pushType,
				};
				knowretrievalPaged(state.ruleForm.hotspot);
				state.historyOrderLoading = false;
				state.formLoading = false;
				state.loading = false;
			} catch (error) {
				state.historyOrderLoading = false;
				state.formLoading = false;
				state.loading = false;
			}
		} else {
			ElMessage.warning('参数有误，请重新进入');
			state.historyOrderLoading = false;
			state.formLoading = false;
			state.loading = false;
		}
	});
});
</script>

<style scoped lang="scss">
.box {
	background-color: var(--el-color-white);
	border-radius: 8px;
}
:deep(.el-divider--horizontal) {
	margin-top: 0;
}
.border-title {
	font-size: var(--el-font-size-medium);
	line-height: var(--el-font-size-medium);
	color: var(--el-color-primary);
	border-left: 4px solid var(--el-color-primary);
	padding-left: 7px;
}
.order-edit-container {
	color: var(--hotline-color-text-main);
	.right-content {
		&-knowledge {
			.knowledge-container {
				position: relative;
				.knowledge-input {
					:deep(.el-input__wrapper) {
						border-radius: 20px;
						background: var(--hotline-bg-main-color);
					}
				}
				.knowledge-search-button {
					height: calc(100% - 6px);
				}
				.indent {
					text-indent: 1em;
					color: var(--hotline-color-text-main-light);
					line-height: 20px;
				}
			}
		}
	}
}
</style>
