<template>
	<div class="order-add-container layout-padding">
		<el-row :gutter="10" class="h100">
			<!-- 中间工单信息 -->
			<el-col :span="12" class="left-content mb20 h100" v-loading="state.formLoading">
				<el-scrollbar class="h100">
					<el-card shadow="never">
						<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="110px" label-position="right" scroll-to-error>
							<p class="border-title mb10">来电信息</p>
							<el-row :gutter="20">
								<!-- 服务坐席 -->
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item label="服务坐席">
										<span>{{ state.ruleForm.acceptorName }}</span>
									</el-form-item>
								</el-col>
								<!-- 来源渠道 -->
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item label="来源渠道" prop="channel" :rules="[{ required: false, message: '请选择来源渠道', trigger: 'change' }]">
										<el-select
											v-model="state.ruleForm.channel"
											placeholder="请选择来源渠道"
											class="w100"
											clearable
											value-key="value"
											disabled
											@change="
												(val) => {
													state.ruleForm.sourceChannel = val?.key ?? null;
													state.ruleForm.sourceChannelCode = val?.value ?? null;
												}
											"
										>
											<el-option v-for="item in state.channelOptions" :value="item" :key="item.value" :label="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="fromName" :rules="[{ required: false, 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="contact" :rules="[{ required: false, message: '请填写联系电话', trigger: 'blur' }]">
										<el-input v-model="state.ruleForm.contact" 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="24" :xl="24" v-if="state.ruleForm.no">
									<el-form-item label="工单编码">
										{{ state.ruleForm.no }} <span v-if="state.ruleForm?.password">【{{ state.ruleForm.password }}】</span>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
									<el-form-item label="受理类型" prop="acceptTypeObj" :rules="[{ required: true, message: '请选择受理类型', trigger: 'change' }]">
										<el-select
											v-model="state.ruleForm.acceptTypeObj"
											placeholder="请选择受理类型"
											class="w100"
											value-key="value"
											disabled
											@change="
												(val) => {
													state.ruleForm.acceptType = val?.key ?? null;
													state.ruleForm.acceptTypeCode = val?.value ?? null;
												}
											"
										>
											<el-option v-for="item in state.acceptTypeOptions" :key="item.value" :label="item.key" :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="enforcementOrdersHandlers"
										:rules="[{ required: true, message: '请选择执法部门', trigger: 'change' }]"
									>
										<el-select
											v-model="state.ruleForm.enforcementOrdersHandlers"
											placeholder="请选择执法部门"
											class="w100"
											value-key="id"
											multiple
											collapse-tags
											collapse-tags-tooltip
											:max-collapse-tags="2"
										>
											<el-option v-for="item in state.orgsOptions" :key="item.id" :label="item.name" :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="hotspotId" :rules="[{ required: false, message: '请选择热点分类', trigger: 'change' }]">
										<el-tree-select
											v-model="state.ruleForm.hotspotId"
											:data="state.enforcementHotspot"
											:render-after-expand="false"
											class="w100"
											node-key="id"
											:props="{
												isLeaf: 'hasChild',
												children: 'children',
												label: 'hotSpotFullName',
											}"
											expand-on-click-node
											collapse-tags-tooltip
											:max-collapse-tags="2"
											placeholder="请选择热点分类"
											filterable
											:default-expanded-keys="state.hotspotExternal"
											@change="changeHotSpot"
											ref="hotspotRef"
                      clearable
										/>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
									<el-row :gutter="0">
										<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
											<el-form-item
												label="事发地址"
												prop="areaCode"
												:rules="[{ required: true, message: '请选择事发地址', trigger: 'change' }]"
												v-loading="addressLoading"
											>
												<el-cascader
													:options="state.areaOptions"
													filterable
													:props="{ value: 'id', label: 'areaName', emitPath: false, checkStrictly: true }"
													placeholder="请选择事发地址"
													class="w100"
													v-model="state.ruleForm.areaCode"
													ref="areaRef"
													@change="changeArea"
												>
												</el-cascader>
											</el-form-item>
										</el-col>
										<el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
											<el-form-item
												label=""
												prop="street"
												:rules="[{ required: false, message: '请填写详细地址', trigger: 'blur' }]"
												label-width="10px"
												class="w100 flex"
											>
												<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
													<el-input v-model="state.ruleForm.street" placeholder="请填写详细地址" clearable> </el-input>
												</el-col>
											</el-form-item>
										</el-col>
									</el-row>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
									<el-form-item label="工单标题" prop="title" :rules="[{ required: true, message: '请填写工单标题', trigger: 'blur' }]">
										<el-input v-model="state.ruleForm.title" placeholder="请填写工单标题" clearable> </el-input>
									</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="files" :rules="[{ required: false, message: '请填写诉求内容', trigger: 'change' }]">
										<annex-list :businessId="state.orderId" classify="受理上传" v-model="state.ruleForm.files" v-model:format="filesFormat" />
									</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="onCancel"> 取消 </el-button>
										<el-button class="default-button" @click="save(ruleFormRef)" :loading="buttonLoading"> 保存 </el-button>
									</el-form-item>
								</el-col>
							</el-row>
						</el-form>
					</el-card>
				</el-scrollbar>
			</el-col>
		</el-row>
	</div>
</template>

<script setup lang="ts" name="judgeOrderAdd">
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import type { FormInstance } from 'element-plus';
import { ElMessage } from 'element-plus';
import { storeToRefs } from 'pinia';
import { useRoute, useRouter } from 'vue-router';
import { throttle, transformFile } from '@/utils/tools';
import { commonEnum } from '@/utils/constants';
import { useUserInfo } from '@/stores/userInfo';
import { treeArea } from '@/api/auxiliary/area';
import mittBus from '@/utils/mitt';
import { listBaseData } from '@/api/judicial';
import { addJudicial, editJudicial, getJudicial } from '@/api/judicial/order';
import { removeDuplicate } from '@/utils/arrayOperation';
import { useThemeConfig } from '@/stores/themeConfig';

// 引入组件
const CommonAdvice = defineAsyncComponent(() => import('@/components/CommonAdvice/index.vue')); // 常用意见
const AnnexList = defineAsyncComponent(() => import('@/components/AnnexList/index.vue')); // 附件列表
// 定义变量内容
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const state = reactive<any>({
	createBy: 'manual', // 工单创建方式 默认手动创建  tel:来电弹单  letter:互联网来信 默认表示手动创建
	ruleForm: {
		sourceChannel: '自定义', // 来源频道
		sourceChannelCode: 'ZDY', //来源频道code
		channel: {
			value: 'ZDY',
			key: '自定义',
		},
		acceptorName: null, // 员工姓名
		contact: null, // 联系电话
		no: null, // 工单编码
		title: null, // 工单标题
		acceptType: '投诉', // 受理类型
		acceptTypeCode: '35', // 受理类型code
		acceptTypeObj: {
			value: '35',
			key: '投诉',
		},
		hotspotId: '', // 热点分类
		areaCode: themeConfig.value.cityCode, // 区域编码
		city: themeConfig.value.cityName, // 市
		street: null, // 街道
		content: '', // 工单内容
		enforcementOrdersHandlers: [],
	},
	formLoading: false, // 表单加载状态
	hotspotExternal: [], // 热点分类外部数据
	acceptTypeOptions: [], // 受理类型
	channelOptions: [], // 来源频道
	orgsOptions: [], // 部门
	enforcementHotspot: [], //热点
	areaOptions: [], //省市区
	transpondCity: [],
	orderId: null, // 工单id
});
const storesUserInfo = useUserInfo(); // 用户信息
const { userInfos } = storeToRefs(storesUserInfo); // 用户信息
state.ruleForm.acceptorName = userInfos.value.name; // 员工姓名
const route = useRoute(); // 路由
// 获取事发地址
const areaRef = ref<RefType>();
const changeArea = () => {
	const currentNode = areaRef.value.getCheckedNodes();
	// 判断数组长度
	if (currentNode[0].pathLabels.length <= 4) {
		state.ruleForm.city = currentNode[0].pathLabels[0] ?? ''; // 市
		state.ruleForm.county = currentNode[0].pathLabels[1] ?? ''; // 区
		state.ruleForm.town = currentNode[0].pathLabels[2] ?? ''; // 地区
	} else {
		// 如果数组长度大于4
		state.ruleForm.city = currentNode[0].pathLabels[0] ?? ''; // 市
		state.ruleForm.county = currentNode[0].pathLabels[1] ?? ''; // 区
		state.ruleForm.town = currentNode[0].pathLabels[2] ?? ''; // 地区
		state.ruleForm.areaText = currentNode[0].pathLabels.slice(3).join('') ?? ''; // 地区
		console.log(state.ruleForm.areaText);
	}
};
// 选择热点分类
const hotspotRef = ref();
// 递归查找父级Id
const getParentId = (val: any, arr: string[]) => {
	if (val.data.parentId) {
		arr.push(val.data.parentId);
		getParentId(val.parent, arr);
	}
	return removeDuplicate(arr);
};
const changeHotSpot = (val: any) => {
	const currentNode = hotspotRef.value.getNode(val);
	state.ruleForm.hotspotExternal = getParentId(currentNode, []).join(',');
	state.ruleForm.hotspotSpliceName = currentNode.data.hotSpotFullName; // 热点分类拼接名称
	state.ruleForm.hotspotName = currentNode.data?.hotSpotName; // 热点分类名称
	state.ruleForm.hotspotCode = currentNode.data?.provinceCode; // 热点分类code
};
const ruleFormRef = ref<RefType>();
// 删除不必要的属性
const deleteUnnecessaryProperties = (obj: any) => {
	const propertiesToDelete = ['channel', 'acceptTypeObj', 'enforcementOrdersHandlers'];
	propertiesToDelete.forEach((prop) => Reflect.deleteProperty(obj, prop));
};
const filesFormat = ref<EmptyArrayType>([]); // 附件列表格式化
const buttonLoading = ref<boolean>(false);
// 保存
const save = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		buttonLoading.value = true;
		state.ruleForm.enforcementOrdersHandler = state.ruleForm.enforcementOrdersHandlers.map((item: any) => {
			return {
				key: item.name,
				value: item.id,
			};
		});
		let orderDetail = {
			...state.ruleForm,
			files: filesFormat.value,
		};
		deleteUnnecessaryProperties(orderDetail);
		const operation = state.orderId ? editJudicial : addJudicial;
		operation(orderDetail)
			.then(() => {
				buttonLoading.value = false;
				ElMessage.success('操作成功');
				onCancel();
			})
			.catch(() => {
				buttonLoading.value = false;
			});
	});
}, 300);
// 选中常用意见
const chooseAdvice = (item: any) => {
	state.ruleForm.content += item.content;
};
// 取消
const onCancel = () => {
	mittBus.emit('clearCache', 'judicialCustom');
	// 关闭当前 tagsView
	mittBus.emit('onCurrentContextmenuClick', Object.assign({}, { contextMenuClickId: 1, ...route }));
};
// 加载基础数据
const loadBaseData = async () => {
	try {
		const { result } = await listBaseData();
		state.acceptTypeOptions = result.acceptTypeOptions ?? []; // 受理类型
		state.channelOptions = result.channelOptions ?? [];
		state.orgsOptions = result.orgsOptions ?? [];
		state.enforcementHotspot = result.enforcementHotspot ?? [];
	} catch (error) {
		console.log(error);
	}
};
// 如果是修改加载表单内容
const loadForm = async () => {
	state.formLoading = true;
	if (route.query.id) {
		// 如果 有id
		state.orderId = route.query.id;
		try {
			const response = await getJudicial(<string>route.query.id);
			// 如果获取到id 调用查询详情
			state.ruleForm = response.result;
			state.ruleForm.files = transformFile(response.result.files);
			state.ruleForm.channel = {
				// 来源渠道
				value: state.ruleForm.sourceChannelCode,
				key: state.ruleForm.sourceChannel,
			};
			state.ruleForm.acceptTypeObj = {
				// 受理类型
				value: state.ruleForm.acceptTypeCode,
				key: state.ruleForm.acceptType,
			};
			state.ruleForm.enforcementOrdersHandlers = state.ruleForm.enforcementOrdersHandler.map((item: any) => {
				// 执法部门
				return {
					name: item.key,
					id: item.value,
				};
			});
			if (state.ruleForm.hotspotExternal) {
				//热点分类默认展开
				state.hotspotExternal = state.ruleForm.hotspotExternal.split(',');
			}
			state.formLoading = false;
		} catch (e) {
			console.log(e);
			state.formLoading = false;
		}
	} else {
		state.formLoading = false;
	}
};
// 加载省市区
const addressLoading = ref<boolean>(false);
const loadAddress = async () => {
	addressLoading.value = true;
	try {
		const { result } = await treeArea();
		state.areaOptions = result ?? []; //省市区数据
		addressLoading.value = false;
	} catch (error) {
		console.log(error);
	} finally {
		addressLoading.value = false;
	}
};
loadBaseData();
loadForm();
onMounted(async () => {
	await loadAddress();
});
</script>
