<template>
	<div class="order-edit-container layout-padding">
		<el-row :gutter="20" class="h100">
			<!-- 左边工单信息 -->
			<el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="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.historyOrderLoading"
					>
						<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.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: /^(13[0-9]|14[01456879]|15[0-3,5-9]|16[2567]|17[0-8]|18[0-9]|19[0-3,5-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.licenceType || state.ruleForm.licenceType === 0, 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' }]"
								>
									<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="受理短信" />
									<el-checkbox v-model="state.ruleForm.needContact" label="无需联系" @change="(val:boolean)=> ruleFormRef.resetFields('contact')" />
								</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="date" placeholder="请选择事发时间" value-format="YYYY-MM-DD[T]HH:mm:ss.sss[Z]" 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"
									class="textarea"
									:rules="[{ required: true, message: '请填写诉求详情', trigger: 'blur' }]"
								>
									<el-input
										v-model="state.ruleForm.content"
										type="textarea"
										:autosize="{ minRows: 10, maxRows: 20 }"
										placeholder="请填写诉求详情"
										clearable
										maxlength="2000"
									>
									</el-input>
									<span class="bttons">
										<el-button @click="showComents" class="default-button" :loading="state.historyOrderLoading">常用意见</el-button>
										<el-button type="primary" @click="onAddComments" :loading="state.historyOrderLoading">添加到常用意见</el-button>
									</span>
								</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' }]">
									<el-upload
										v-model:file-list="fileList"
										class="upload-demo w100"
										action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
										multiple
										:before-remove="beforeRemove"
										:on-exceed="handleExceed"
										ref="uploadListRef"
									>
										<el-button> <SvgIcon name="ele-Upload" /> 上传附件 </el-button>
										<template #file="{ file }">
											<div class="el-upload-list__item-info">
												<a class="el-upload-list__item-name">
													<SvgIcon class="mr5" :name="fileType(checkFile(file.name))" size="16px" />
													<span class="el-upload-list__item-file-name">{{ file.name }}</span>
												</a>
											</div>
											<SvgIcon name="ele-Close" class="el-icon--close" size="14px" title="删除文件" @click="handleRemove(file)" />
										</template>
									</el-upload>
								</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 :xs="24" :sm="24" :md="12" :lg="12" :xl="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" v-waves>
									<SvgIcon name="ele-Search" class="mr5" />查询
								</el-button>
								<el-button @click="resetQuery(queryParamsRef)" :loading="state.historyOrderLoading" v-waves 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">{{ 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" />
		<!-- 常用意见管理 -->
		<Comment ref="CommentRef" @chooseComment="chooseComment" modal />
		<!-- 历史工单 -->
		<History ref="HistoryOrderRef" @saveSlect="saveSlect"/>
		<!-- 提交流程 -->
		<Process ref="processRef" @onSubmitProcess="onSubmitProcess" />
		<!-- 补充信息 -->
		<Supply ref="SupplyRef" @onSupplySubmit="onSupplySubmit" />
	</div>
</template>

<script setup lang="ts" name="orderEdit">
import { defineAsyncComponent, ref, reactive, computed, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { UploadProps, UploadUserFile, FormInstance } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useRoute, useRouter } from 'vue-router';
import { useTelStatus } from '/@/stores/telStatus';
import { desensitizationPhone, checkFile, fileType, commonEeum } from '/@/utils/tools';
import { orderBasedataAdd, hotspottype, historyOrder, orderDetail, orderEdit } from '/@/api/business/order';
import { useUserInfo } from '/@/stores/userInfo';
import { addCommon, 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 state = reactive<any>({
	createFrom: 'manual', // 工单创建方式 默认手动创建  tel:来电弹单  letter:互联网来信 默认表示手动创建
	activeName: 'first', // tabs
	ruleForm: {
		// 表单
		street: '',
		transferPhone: '',
		employeeName: '',
		employeeStaffNo: '',
		duplicateTitle: '',
		duplicateId: '',
		content:''
	},
	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, // 知识库总条数
});
const ruleFormRef = ref();
const queryParamsRef = ref();
const useTelStatusStore = useTelStatus();
const { telStatusInfo } = storeToRefs(useTelStatusStore);
const uploadListRef = ref();
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 CommentRef = ref();
const hotspotRef = ref();
const SupplyRef = ref();
// 热点分类远程搜索
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 fileList = ref<UploadUserFile[]>([]);
// 删除确认
const beforeRemove: UploadProps['beforeRemove'] = (uploadFile) => {
	return ElMessageBox.confirm(`确定要删除 ${uploadFile.name} ?`).then(
		() => true,
		() => false
	);
};
// 删除文件
const handleRemove = (file: any) => {
	uploadListRef.value.handleRemove(file);
};

const handleExceed: UploadProps['onExceed'] = (files, uploadFiles) => {
	ElMessage.warning(`The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length} totally`);
};
// 选择工单类型 处理受理类型选择数据
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('操作成功');
						router.replace({
							path: '/business/order',
						});
						// 关闭当前 tagsView
						mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
					});
				} else {
					//不通过 展示弹窗
					ExpandFormRef.value.openDialog(submitObj.acceptType, true); // 立即提交展示验证
				}
			} else {
				// 修改
				orderEdit(submitObj).then(() => {
					ElMessage.success('操作成功');
					router.replace({
						path: '/business/order',
					});
					// 关闭当前 tagsView
					mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
				});
			}
		} 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.ruleForm.duplicateTitle = row.title;
	}
};
// 选择重复件
const handleRowChange = (row: any) => {
	state.ruleForm.duplicateId = row.id;
	state.ruleForm.duplicateName = row.title;
};
// 打开常用意见管理
const showComents = () => {
	CommentRef.value.openDialog(commonEeum.Seat);
};
// 添加到常用意见
const onAddComments = async () => {
	if (!state.ruleForm.content) {
		ElMessage.warning('请先输入诉求详情');
		return;
	}
	await addCommon({
		typeCode: commonEeum.Seat,
		content: state.ruleForm.content,
	});
	ElMessage.success('操作成功');
	CommentRef.value.closeDialog();
};
// 选中常用意见
const chooseComment = (item: any) => {
	state.ruleForm.content += item.content;
	CommentRef.value.closeDialog();
};
// 历史工单搜索
const searchKnowledge = (value?: string) => {
	if (value) state.KnowledgeKeyword = value;
	state.historyOrderLoading = true;
	state.historyOrderLoading = false;
};
// 流程提交成功
const onSubmitProcess = () => {
	router.push({
		path: '/business/order',
	});
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
};
/** 搜索按钮操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	searchHistory();
};
/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	handleQuery();
};
/** 获取历史工单 */
const searchHistory = () => {
	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.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,
							};
						}
					});
				}
				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.loading = false;
			} catch (error) {
				state.historyOrderLoading = false;
				state.loading = false;
			}
		} else {
			ElMessage.warning('参数有误，请重新进入');
			state.historyOrderLoading = false;
			state.loading = false;
		}
	});
});
</script>

<style scoped lang="scss">
.box {
	background-color: var(--el-color-white);
	border-radius: 8px;
}
.upload-demo {
	:deep(.el-upload-list) {
		display: flex;
		flex-wrap: wrap;
		.el-upload-list__item {
			width: calc(25% - 10px);
			border: var(--el-border);
			margin-right: 10px;
		}
	}
}
: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;
}
.textarea {
	position: relative;
	.bttons {
		position: absolute;
		right: 10px;
		bottom: 10px;
	}
}
.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;
					text-overflow: -o-ellipsis-lastline;
					overflow: hidden; //溢出内容隐藏
					text-overflow: ellipsis; //文本溢出部分用省略号表示
					display: -webkit-box; //特别显示模式
					-webkit-line-clamp: 2; //行数
					line-clamp: 2;
					-webkit-box-orient: vertical; //盒子中内容竖直排列
				}
			}
		}
	}
}
</style>
