<template>
	<div class="order-add-container layout-padding">
		<el-row :gutter="15" class="h100">
			<!-- 左边工单信息 -->
			<el-col :span="12" class="left-content mb20 h100">
				<el-scrollbar class="box pd20 h100">
					<!-- <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 :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
								<!-- 手动创建 -->
								<template v-if="state.createBy === 'manual'">
									<el-form-item label="来源渠道" prop="channel"
										:rules="[{ required: true, message: '请选择来源渠道', trigger: 'change' }]">
										<el-select v-model="state.ruleForm.channel" placeholder="请选择来源渠道" class="w100"
											clearable @change="() => {
												ruleFormRef.resetFields('fromPhone');
												state.ruleForm.fromPhone = '';
											}
												">
											<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-if="state.createBy === 'tel'">
									<el-form-item label="来源渠道" prop="channel">
										<el-select v-model="state.ruleForm.channel" placeholder="请选择来源渠道" class="w100"
											disabled>
											<el-option v-for="item in state.channelOptions" :key="item.key"
												:label="item.value" :value="item.key" />
										</el-select>
									</el-form-item>
								</template>
								<!-- 互联网来信 -->
								<template v-if="state.createBy === 'letter'">
									<el-form-item label="来源渠道" prop="channel">
										互联网来信
										<span>[{{ state.ruleForm.channel }}]</span>
									</el-form-item>
								</template>
							</el-col>
							<!-- 转接来源 -->
							<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
								<!-- 手动创建 -->
								<template v-if="state.createBy === 'manual'">
									<el-form-item label="转接来源" prop="transferPhone"> 暂无 </el-form-item>
								</template>
								<!-- 来电弹单 -->
								<template v-if="state.createBy === 'tel'">
									<el-form-item label="转接来源" prop="transferPhone">
										<span>[{{ state.ruleForm.transferPhone }}]</span>
									</el-form-item>
								</template>
								<!-- 互联网来信 -->
								<template v-if="state.createBy === 'letter'">
									<el-form-item label="转接来源" prop="transferPhone">
										<span>[{{ state.ruleForm.transferPhone }}]</span>
									</el-form-item>
								</template>
							</el-col>
							<!-- 来电号码 -->
							<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="state.ruleForm.channel === 0">
								<!-- 手动创建 -->
								<template v-if="state.createBy === 'manual'">
									<el-form-item label="来电号码" prop="fromPhone" :rules="[
										{ required: true, message: '请填写来电号码', trigger: 'blur' },
										{
											pattern: /^((0\d{2,3}(-)?\d{7,8})|(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8})$/,
											message: '来电号码格式错误',
											trigger: 'blur',
										},
									]">
										<el-input v-model="state.ruleForm.fromPhone" placeholder="请填写来电号码" clearable
											@blur="searchHistory"> </el-input>
									</el-form-item>
								</template>
								<!-- 来电弹单 -->
								<template v-if="state.createBy === 'tel'">
									<el-form-item label="来电号码" prop="fromPhone">
										<el-input v-model="state.ruleForm.fromPhone" placeholder="请填写来电号码" disabled>
										</el-input>
									</el-form-item>
								</template>
								<!-- 互联网来信 -->
								<template v-if="state.createBy === 'letter'">
									<el-form-item label="来电号码">
										<span>[{{ state.ruleForm.fromPhone }}]</span>
									</el-form-item>
								</template>
							</el-col>
							<!-- 服务坐席 -->
							<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
								<el-form-item label="服务坐席">
									<!-- 手动创建 -->
									<template v-if="state.createBy === 'manual'">
										<span>{{ state.ruleForm.employeeName + '[' + state.ruleForm.employeeStaffNo + ']'
										}}</span>
									</template>
									<!-- 来电弹单 -->
									<template v-if="state.createBy === 'tel'">
										<span>{{ state.ruleForm.employeeName + '[' + telStatusInfo.telsNo + ']' }}</span>
									</template>
									<!-- 互联网来信 -->
									<template v-if="state.createBy === 'letter'">
										<span>[{{ telStatusInfo.telsNo }}]</span>
									</template>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
								<el-form-item label="来电/信人" prop="fromName"
									:rules="[{ required: true, message: '请填写来电/信人', trigger: 'blur' }]">
									<el-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" @change="selectIdentity">
										<el-radio :label="item.key" v-for="item in state.identityTypeOptions"
											:key="item.key">{{ item.value }}</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
								<el-form-item label="证件类型" prop="licenceTypeObj"
									:rules="[{ required: false, message: '请选择证件类型', trigger: 'change' }]">
									<el-select v-model="state.ruleForm.licenceTypeObj" placeholder="请选择证件类型" class="w100"
										clearable value-key="dicDataValue" @change="(val:any) => {
											state.ruleForm.licenceType = val.dicDataName;
											state.ruleForm.licenceTypeCode = val.dicDataValue
										}">
										<el-option v-for="item in state.licenceTypeOptions" :key="item.dicDataValue"
											:label="item.dicDataName" :value="item" />
									</el-select>
								</el-form-item>
							</el-col>
							<!-- 若“证件类型”有值，则证件号码必填 -->
							<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
								<el-form-item label="证件号码" prop="licenceNo" :rules="[
									{ required: state.ruleForm.licenceTypeCode, message: '请填写证件号码', trigger: 'blur' },
									{
										pattern: licenceNoPattern,
										message: '证件号码格式错误',
										trigger: 'blur',
									},
								]">
									<el-input v-model="state.ruleForm.licenceNo" placeholder="请填写证件号码" clearable>
									</el-input>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
								<el-form-item label="年龄段" prop="ageRangeObj"
									:rules="[{ required: false, message: '请选择年龄段', trigger: 'change' }]">
									<el-select v-model="state.ruleForm.ageRangeObj" placeholder="请选择年龄段" class="w100"
										clearable value-key="dicDataValue" @change="(val:any) => {
											state.ruleForm.ageRange = val.dicDataName;
											state.ruleForm.ageRangeCode = val.dicDataValue
										}">
										<el-option v-for="item in state.ageRangeOptions" :key="item.dicDataValue"
											:label="item.dicDataName" :value="item" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
								<el-form-item label="联系电话" prop="contact" :rules="[
									{ required: true, message: '请填写联系电话', trigger: 'blur' },
									{
										pattern: /^((0\d{2,3}(-)?\d{7,8})|(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8})$/,
										message: '联系电话格式错误',
										trigger: 'blur',
									},
								]">
									<el-input v-model="state.ruleForm.contact"
										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="acceptSms"
									:rules="[{ required: false, message: '请选择', trigger: 'change' }]">
									<el-checkbox v-model="state.ruleForm.acceptSms" label="受理短信" />
                  <el-checkbox v-model="state.ruleForm.needContact" label="是否保密" />
								</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
										placeholder="请选择热点分类" :props="HotspotProps" lazy :load="load" node-key="id"
										check-strictly :render-after-expand="false" @node-click="hotSpotChange"
										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" />
								</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: false, 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="selectRepeat">
														<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" :commonEnum="commonEnum.Seat"
										modal />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="附件" prop="remark"
									:rules="[{ required: false, message: '请填写诉求内容', trigger: 'change' }]">
									<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" v-auth="'business:order:add'"> 保存
									</el-button>
									<el-button type="primary" v-waves @click="submit"
										v-auth="'business:order:startWorkflow'"> 提交 </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 class="h100">
					<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="{ row }">
									<el-radio v-model="state.tableRadio" :label="row.id"
										@change="handleRowChange(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="{ row }">
									<span style="color: var(--el-color-primary)">{{ row.title }}</span>
								</template>
							</el-table-column>
							<el-table-column prop="hotspotName" 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="{ row }">
									<!-- 草稿 -->
									<span style="color: var(--el-color-info)" v-if="row.status === 0">{{ row.statusText
									}}</span>
									<!-- 待签收 -->
									<span style="color: var(--el-color-success)" v-if="row.status === 10">{{ row.statusText
									}}</span>
									<!-- 办理中 -->
									<span style="color: var(--el-color-primary)" v-if="row.status === 20">{{ row.statusText
									}}</span>
									<!-- 会签中 -->
									<span style="color: var(--el-color-primary)" v-if="row.status === 30">{{ row.statusText
									}}</span>
									<!-- 退回 -->
									<span style="color: var(--el-color-danger)" v-if="row.status === 40">{{ row.statusText
									}}</span>
									<!-- 办理完成 -->
									<span style="color: var(--el-color-success)" v-if="row.status === 50">{{ row.statusText
									}}</span>
									<!-- 已归档 -->
									<span style="color: var(--el-color-info)" v-if="row.status === 60">{{ row.statusText
									}}</span>
								</template>
							</el-table-column>
							<el-table-column prop="statusText" label="操作" width="70" fixed="right" align="center">
								<template #default="{ row }">
									<el-button @click="onSupply(row)" link type="primary"> 补充 </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="knowledgeRetrievalPaged(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="knowledgeRetrievalPaged(state.KnowledgeKeyword)">
										<SvgIcon name="ele-Search" size="16px" color="#fff" />
									</el-button>
								</template>
							</el-input>
							<div>
								<span class="mr10" v-if="state.hotWords.length">搜索热词</span>
								<el-tag v-for="(item, index) in state.hotWords" :key="index" class="mr10 mb10"
									style="cursor: pointer" @click="knowledgeRetrievalPaged(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 knowledge-item"
									@click="onPreview(item)" 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="knowledgeRetrievalPaged(state.KnowledgeKeyword)" :pageSizes="[5, 10, 15, 20]"
							layout="total, prev, pager, next" class="pt10" />
					</div>
				</el-scrollbar>
			</el-col>
		</el-row>
		<!-- 拓展表单 -->
		<order-expand-form ref="ExpandFormRef" @saveExpandForm="saveExpandForm" />
		<!-- 历史工单 -->
		<order-history ref="HistoryOrderRef" @saveSelect="saveSelect" />
		<!-- 提交流程 -->
		<order-process ref="processRef" @orderProcessSuccess="orderProcessSuccess" />
		<!-- 补充信息 -->
		<order-supply ref="SupplyRef" @onSupplySuccess="onSupplySuccess" />
	</div>
</template>

<script setup lang="ts" name="orderAdd">
import { defineAsyncComponent, ref, reactive, onMounted, computed } 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 { commonEnum, throttle } from '/@/utils/tools';
import { auth } from '/@/utils/authFunction';
import other from '/@/utils/other';
import { orderBaseDataAdd, orderAdd, hotSpotType, historyOrder, 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 OrderProcess = defineAsyncComponent(() => import('/@/views/business/order/components/Order-process.vue'));
const OrderExpandForm = defineAsyncComponent(() => import('/@/views/business/order/components/Order-expand-form.vue'));
const OrderHistory = defineAsyncComponent(() => import('/src/views/business/order/components/Order-history.vue'));
const Comment = defineAsyncComponent(() => import('/@/views/business/order/components/Order-comment.vue'));
const OrderSupply = defineAsyncComponent(() => import('/@/views/business/order/components/Order-supply.vue'));
const Upload = defineAsyncComponent(() => import('/@/components/Upload/index.vue'));
// 定义变量内容
const state = reactive<any>({
	createBy: 'manual', // 工单创建方式 默认手动创建  tel:来电弹单  letter:互联网来信 默认表示手动创建
	activeName: 'first', // tabs
	ruleForm: {
		// 表单
		street: '',//街道
		transferPhone: '',//转接电话
		employeeName: '',//员工姓名
		employeeStaffNo: '',//员工工号
		duplicateTitle: '',//重复工单标题
		duplicateId: '',//重复工单id
		content: '', // 工单内容
		licenceTypeCode: '', // 证件类型
		acceptSms: false, // 是否接收短信
    isSecret:false, //是否保密
		fromPhone: '', // 来电号码
		fromGender: '',// 来电人性别
	},
	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: '', //知识检索内容
	hotWords: [], // 知识检索热点
	knowledgeList: [], //知识检索列表
	external: [],
	hotspotExternal: [], // 热点分类展开
	knowledgeQuery: {
		// 知识库查询
		PageIndex: 1,
		PageSize: 5,
		Keyword: '',
	},
	knowledgeTotal: 0, // 知识库总条数
	fileList: [],
	orderId: '', // 工单id
});
const ruleFormRef = ref<RefType>();
const queryParamsRef = ref<RefType>();
const useTelStatusStore = useTelStatus();
const { telStatusInfo } = storeToRefs(useTelStatusStore);
const processRef = ref<RefType>();
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<RefType>();
const hotspotRef = ref<RefType>();
const SupplyRef = ref<RefType>();
// 证件号码验证
const licenceNoPattern = computed(() => {
	switch (state.ruleForm.licenceTypeCode) {
		case '10': // 身份证
			return /^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/;
		default: //默认只允许数字字母
			return /^[A-Za-z0-9]+$/;
	}
});
// 热点分类远程搜索
const HotspotProps = {
	label: 'hotSpotFullName',
	children: 'children',
	isLeaf: 'isLeaf',
};
// 热点分类懒加载
const load = async (node: any, resolve: any) => {
	if (node.isLeaf) return resolve([]);
	const res: any = await hotSpotType({ id: node.data.id ? node.data.id : '' });
	resolve(res.result);
};
// 选择热点分类
const hotSpotChange = (val: any, e: any) => {
	state.hotspotExternal = [];
	state.external = [];
	state.hotspotExternal = getParentId(e, state.external);
	state.ruleForm.hotspotSpliceName = val.hotSpotFullName;
  state.ruleForm.hotspotName = val.hotSpotName;
	knowledgeRetrievalPaged(val.hotSpotName);
};
//  知识检索
const knowledgeRetrievalPaged = async (val?: string) => {
	state.knowledgeQuery.Keyword = val ?? '';
	state.KnowledgeKeyword = val ?? '';
	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;
	}
};
// 手机号码脱敏处理
// const phoneNumber = computed(() => {
// 	return desensitizationPhone(telStatusInfo.value.onCallArr[0]?.from);
// });
// 递归查找父级Id
const getParentId = (val: any, arr: string[]) => {
	if (val.data.parentId) {
		arr.push(val.data.parentId);
		getParentId(val.parent, arr);
	}
	return arr;
};
// 选择工单类型 处理受理类型选择数据
const selectOrderType = (val: any) => {
	ruleFormRef.value.resetFields('acceptType');
	state.acceptTypeOptions = state.acceptTypeOptions.map((item: any) => {
		let isDisabled = val === 1 && ![30, 35].includes(item.key); // 选择了12315 市场监管受理单 举报:30 投诉:35
		return {
			key: item.key,
			value: item.value,
			disabled: isDisabled,
		};
	});
};
const areaRef = ref<RefType>();
// 选择省市区
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<RefType>();
// 打开拓展表单
const showExpandForm = () => {
	ExpandFormRef.value.openDialog(state.ruleForm.acceptType);
};
// 拓展表单保存
const saveExpandForm = (val: any) => {
	const acceptTypeMap: any = {
		30: 'orderReport',
		35: 'orderComplain'
	};
	const property = acceptTypeMap[state.ruleForm.acceptType];
	if (property) {
		state.ruleForm[property] = val;
	}
};
// 删除不必要的属性
const deleteUnnecessaryProperties = (obj: any) => {
	const propertiesToDelete = ['ageRangeObj', 'pushTypeObj', 'licenceTypeObj'];
	propertiesToDelete.forEach(prop => Reflect.deleteProperty(obj, prop));
	if (obj.acceptType === 30) Reflect.deleteProperty(obj, 'orderComplain');
	if (obj.acceptType === 35) Reflect.deleteProperty(obj, 'orderReport');
};
// 是否打开拓展表单
const shouldOpenDialog = (obj: any) => obj.orderType === 1 && obj.acceptType && !ExpandFormRef.value.state.validated;
// 保存
const save = throttle(() => {
	ruleFormRef.value.validate((valid: boolean) => {
		if (valid) {
			state.ruleForm.hotspotExternal = state.hotspotExternal.join(',');
			let submitObj = other.deepClone(state.ruleForm);
			deleteUnnecessaryProperties(submitObj);
			const addOrderAndNavigate = () => {
				orderAdd(submitObj).then(() => {
					ElMessage.success('操作成功');
					mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
					mittBus.emit('clearCache', 'order');
					router.push({
						path: '/business/order',
					});
				});
			};
			if (shouldOpenDialog(submitObj)) {
				ExpandFormRef.value.openDialog(submitObj.acceptType, true);
			} else {
				addOrderAndNavigate();
			}
		}
	});
}, 500);
// 选择来点人身份如果是企业 推送分类自动选择助企纾困
const selectIdentity = (val:number)=>{
  if(val === 2){
    state.ruleForm.pushTypeObj = state.pushTypeOptions.find((item:any)=>item.dicDataValue === '8'); // 助企纾困
    state.ruleForm.pushType = state.ruleForm.pushTypeObj.dicDataName;
    state.ruleForm.pushTypeCode = state.ruleForm.pushTypeObj.dicDataValue;
  }
}
const processOrder = (submitObj: any, isEdit: boolean) => {
	const operation = isEdit ? orderEdit : orderAdd;
	operation(submitObj).then((res) => {
		ElMessage.success('操作成功');
		state.orderId = isEdit ? state.orderId : res.result;
		processRef.value.openDialog({ id: state.orderId, title: '提交', commonEnum: commonEnum.Seat, processType: 'start' });
	});
};
const handleForm = (submitObj: any, isEdit: boolean) => {
	if (submitObj.orderType === 1 && submitObj.acceptType) {
		if (ExpandFormRef.value.state.validated) {
			processOrder(submitObj, isEdit);
		} else {
			ExpandFormRef.value.openDialog(submitObj.acceptType, true);
		}
	} else {
		processOrder(submitObj, isEdit);
	}
};
// 提交
const submit = throttle(() => {
	ruleFormRef.value.validate((valid: boolean) => {
		if (valid) {
			state.ruleForm.hotspotExternal = state.hotspotExternal.join(',');
			let submitObj = other.deepClone(state.ruleForm);
			deleteUnnecessaryProperties(submitObj);
			if (state.orderId) {
				handleForm(submitObj, true);
			} else {
				handleForm(submitObj, false);
			}
		} else {
			return false;
		}
	});
}, 500);
// 选择是否重复
const isRepeatChange = (val: string) => {
	if (val === 'false') clearRepeat();
};
// 清除重复件
const clearRepeat = () => {
	state.ruleForm.duplicateTitle = '';
	state.ruleForm.duplicateId = '';
	state.tableRadio = '';
};
// 选择重复件
const selectRepeat = () => {
	HistoryOrderRef.value.openDialog(state.ruleForm);
};
// 弹窗确定选择重复件
const saveSelect = (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 orderProcessSuccess = () => {
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'order');
	router.push({
		path: '/business/order',
	});
};
/** 搜索按钮操作 */
const handleQuery = throttle(() => {
	state.queryParams.PageIndex = 1;
	searchHistory();
}, 500);
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	handleQuery();
}, 500);
/** 获取历史工单 */
const searchHistory = throttle(() => {
	if (!auth('business:order:history')) ElMessage.error('抱歉，您没有权限查询历史工单！');
	else {
		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;
			});
	}
}, 500);
// 补充信息
const onSupply = (val: any) => {
	SupplyRef.value.openDialog(val);
};
// 补充意见提交成功
const onSupplySuccess = () => {
	searchHistory();
};
// 预览知识
const onPreview = (row: any) => {
	router.push({
		name: 'knowledgePreview',
		params: {
			id: row.id,
			tagsViewName: '知识预览',
		},
	});
};
onMounted(async () => {
	state.formLoading = true;
	state.loading = true;
	try {
		const [area, res, hotspot] = await Promise.all([
			treeArea(),
			orderBaseDataAdd(),
			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 ?? []; // 知识库热词
		//  route.query.createBy  createBy 代表来源  tel:来电弹单  letter:互联网来信 默认表示手动创建
		if (route.params.createBy) {
			state.createBy = route.params.createBy;
			if (route.params.createBy === 'tel') {
				//通话
				state.ruleForm.channel = 0; //电话
				state.ruleForm.fromPhone = route.params.telNo;
				state.ruleForm.callId = route.params.callId;
				state.ruleForm.transferPhone = route.params.transfer;
				searchHistory(); // 查询历史订单
			}
			console.log(route.params);
		}
	} catch (error) {
		state.formLoading = false;
		state.loading = 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;
}

.order-add-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);
				}

				.knowledge-item {
					&:last-child {
						margin-bottom: 0;
					}

					cursor: pointer;

					&:hover {
						color: var(--el-color-primary);
					}

					.indent {
						text-indent: 1em;
						color: var(--hotline-color-text-main-light);
						line-height: 20px;

						&:hover {
							color: var(--el-color-primary);
						}
					}
				}
			}
		}
	}
}
</style>
