<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">
					<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" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
										</el-select>
									</el-form-item>
								</template>
								<!-- 来电弹单 -->
								<template v-if="state.createBy === 'tel'">
									<el-form-item label="来源渠道" prop="channel">
										<el-select v-model="state.ruleForm.channel" placeholder="请选择来源渠道" class="w100" disabled>
											<el-option v-for="item in state.channelOptions" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
										</el-select>
									</el-form-item>
								</template>
								<!-- 互联网来信 -->
								<template v-if="state.createBy === 'letter'">
									<el-form-item label="来源渠道" prop="channel">
										互联网来信
										<span>[{{ state.ruleForm.channel }}]</span>
									</el-form-item>
								</template>
							</el-col>
							<!-- 转接来源 -->
							<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
								<!-- 手动创建 -->
								<template v-if="state.createBy === 'manual'">
									<el-form-item label="转接来源" prop="transferPhone"> 暂无 </el-form-item>
								</template>
								<!-- 来电弹单 -->
								<template v-if="state.createBy === 'tel'">
									<el-form-item label="转接来源" prop="transferPhone">
										<span>[{{ state.ruleForm.transferPhone }}]</span>
									</el-form-item>
								</template>
								<!-- 互联网来信 -->
								<template v-if="state.createBy === 'letter'">
									<el-form-item label="转接来源" prop="transferPhone">
										<span>[{{ state.ruleForm.transferPhone }}]</span>
									</el-form-item>
								</template>
							</el-col>
							<!-- 来电号码 -->
							<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" v-if="state.ruleForm.channel === 'RGDH'">
								<!-- 手动创建 -->
								<template v-if="state.createBy === 'manual'">
									<el-form-item
										label="来电号码"
										prop="fromPhone"
										:rules="[
											{ required: true, message: '请填写来电号码', trigger: 'blur' },
											{
												pattern: /^((0\d{2,3}(-)?\d{7,8})|(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8})$/,
												message: '来电号码格式错误',
												trigger: 'blur',
											},
										]"
									>
										<el-input v-model="state.ruleForm.fromPhone" placeholder="请填写来电号码" clearable @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.isSecret" 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"
										:default-expanded-keys="state.hotspotExternal"
									/>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
								<el-form-item label="事发时间" prop="incidentTime" :rules="[{ required: false, message: '请选择事发时间', trigger: 'change' }]">
									<el-date-picker
										v-model="state.ruleForm.incidentTime"
										type="datetime"
										placeholder="请选择事发时间"
										value-format="YYYY-MM-DD[T]HH:mm:ss"
										class="w100"
									/>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-row :gutter="0">
									<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
										<el-form-item label="事发地址" prop="areaCode" :rules="[{ required: true, message: '请选择事发地址', trigger: 'change' }]">
											<el-cascader
												:options="state.areaOptions"
												filterable
												:props="{ value: 'id', label: 'areaName', emitPath: false }"
												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: false, 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' }]">
                  <common-advice
                      @chooseAdvice="chooseAdvice"
                      v-model="state.ruleForm.content"
                      placeholder="请填写诉求详情"
                      :loading="state.formLoading"
                      :commonEnum="commonEnum.Seat"
                      modal
                  />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
								<el-form-item label="附件" prop="remark" :rules="[{ required: false, message: '请填写诉求内容', trigger: 'change' }]">
									<annex-list></annex-list>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="24" :lg="24" :xl="24">
								<el-form-item>
									<el-button class="default-button" @click="save(ruleFormRef)" v-auth="'business:order:add'"> 保存 </el-button>
									<el-button type="primary" v-waves @click="submit(ruleFormRef)" v-auth="'business:order:startWorkflow'"> 提交 </el-button>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</el-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"
							row-key="id"
							@selection-change="handleSelectionChange"
							max-height="300"
							ref="multipleTableRef"
						>
							<el-table-column type="selection" label="重复件" width="80" v-if="state.ruleForm.isRepeat === 'true'" />
							<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 { throttle } from '/@/utils/tools';
import {commonEnum} from '/@/utils/constants';
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('/@/views/business/order/components/Order-history.vue'));  // 历史工单
const CommonAdvice = defineAsyncComponent(() => import('/@/components/CommonAdvice/index.vue')); // 常用意见
const OrderSupply = defineAsyncComponent(() => import('/@/views/business/order/components/Order-supply.vue')); // 补充信息
const AnnexList = defineAsyncComponent(() => import('/@/components/AnnexList/index.vue'));  // 附件列表
// 定义变量内容
const state = reactive<any>({
	createBy: 'manual', // 工单创建方式 默认手动创建  tel:来电弹单  letter:互联网来信 默认表示手动创建
	activeName: 'first', // tabs
	ruleForm: {
		channel: '', // 来源频道
		transferPhone: '', // 转接来源
		fromPhone: '', // 来电号码
		employeeName: '', // 员工姓名
		employeeStaffNo: '', // 员工工号
		fromName: '', // 来电人姓名
		fromGender: 1, // 来电人性别 默认先生
		identityType: 1, // 来电/信人身份 默认市民
		licenceType: '', // 证件类型
		licenceTypeCode: '', // 证件类型code
		licenceNo: '', // 证件号码
		ageRange: '', // 年龄段
		ageRangeCode: '', // 年龄段code
		contact: '', // 联系电话
		acceptSms: false, // 是否接收短信 默认false
		isSecret: false, // 是否保密 默认false
		company: '', // 工作单位
		no: '', // 工单编号
		title: '', // 工单标题
		orderType: 0, // 工单类型 默认通用工单
		acceptType: '', // 受理类型
		emergencyLevel: 1, // 紧急程度 默认一般
		hotspotId: '', // 热点问题
		incidentTime: '', // 事件发生时间
		areaCode: '', // 区域编码
		street: '', // 街道
		isRepeat: 'false', // 是否重复工单 默认否
		duplicateId: '', //重复工单id
		duplicateTitle: '', // 重复工单标题
		pushType: '', // 推送类型
		pushTypeCode: '', // 推送类型code
		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: '', //知识检索内容
	hotWords: [], // 知识检索热点
	knowledgeList: [], //知识检索列表
	external: [], // 知识检索展开
	hotspotExternal: [], // 热点分类展开
	knowledgeQuery: {
		// 知识库查询
		PageIndex: 1, // 当前页
		PageSize: 5,  // 每页条数
		Keyword: '',  // 关键字
	},
	knowledgeTotal: 0, // 知识库总条数
	fileList: [],
	orderId: '', // 工单id
});
const queryParamsRef = ref<RefType>(); // 历史工单查询参数
const useTelStatusStore = useTelStatus(); // 来电弹屏
const { telStatusInfo } = storeToRefs(useTelStatusStore); // 来电弹屏信息
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 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 ruleFormRef = ref<RefType>();
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((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.ruleForm.hotspotExternal = [];
		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/index',
				});
			});
		};
		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 processRef = ref<RefType>();
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((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.ruleForm.hotspotExternal = state.hotspotExternal.join(',');
		let submitObj = other.deepClone(state.ruleForm);
		deleteUnnecessaryProperties(submitObj);
		if (state.orderId) {
			handleForm(submitObj, true);
		} else {
			handleForm(submitObj, false);
		}
	});
}, 500);
// 选择是否重复
const isRepeatChange = (val: string) => {
	if (val === 'false') clearRepeat();
};
const multipleSelection = ref<any[]>([]); // 重复件表格选中项
const multipleTableRef = ref<RefType>(); // 重复件表格ref
// 清除重复件
const clearRepeat = () => {
	state.ruleForm.duplicateTitle = '';
	state.ruleForm.duplicateId = '';
	state.tableRadio = '';
	multipleTableRef.value.clearSelection();
};
// 选择重复件
const HistoryOrderRef = ref<RefType>();
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;

	multipleTableRef.value!.toggleRowSelection(row, undefined);
	HistoryOrderRef.value.closeDialog();
};
// 右边表格选中重复件
const handleSelectionChange = (row: any) => {
	if (row) {
		state.ruleForm.duplicateId = row.id;
		state.tableRadio = row.id;
		state.ruleForm.duplicateTitle = row.title;
		multipleSelection.value = row;
	}
};
// 选中常用意见
const chooseAdvice = (item: any) => {
	state.ruleForm.content += item.content;
};
// 流程提交成功
const orderProcessSuccess = () => {
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
	mittBus.emit('clearCache', 'order');
	router.push({
		path: '/business/order/index',
	});
};
/** 搜索按钮操作 */
const 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 SupplyRef = ref<RefType>();
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 = 'RGDH'; //电话
				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>
