<template>
	<div class="business-oreder-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd15">
			<!-- <el-tabs v-model="state.activeName" class="h100" @tab-change="handleClick"> -->
			<!-- <el-tab-pane :name="item.value" v-for="item in state.tabPaneList" :key="item.value" :label="item.label"></el-tab-pane> -->
			<div class="flex-column">
				<!-- 查询条件 -->
				<div :class="{ 'search-coloct': !searchCol }" class="search-inner">
					<el-form :model="state.queryParams" ref="ruleFormRef" :inline="true" @submit.native.prevent class="mt15" label-width="100px">
						<el-row :gutter="35">
							<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
								<el-form-item label="关键字" prop="Keyword">
									<el-input v-model="state.queryParams.Keyword" placeholder="工单编码/标题" clearable @keyup.enter="getList(state.activeName)" />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
								<el-form-item label="关键字" prop="Content">
									<el-input v-model="state.queryParams.Content" placeholder="诉求详情" clearable @keyup.enter="getList(state.activeName)" />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
								<el-form-item label="受理类型" prop="AcceptType">
									<el-select v-model="state.queryParams.AcceptType" placeholder="请选择受理类型" multiple clearable class="w100">
										<el-option v-for="item in state.acceptTypeOptions" :value="item.key" :key="item.key" :label="item.value" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
								<el-form-item label="来源渠道" prop="Channel">
									<el-select v-model="state.queryParams.Channel" placeholder="请选择来源渠道" multiple clearable class="w100">
										<el-option v-for="item in state.channelOptions" :value="item.key" :key="item.key" :label="item.value" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
								<el-form-item label="热点分类" prop="HotspotId">
									<el-tree-select
										class="w100"
										v-model="state.queryParams.HotspotId"
										filterable
										clearable
										multiple
										:render-after-expand="false"
										show-checkbox
										placeholder="请选择热点分类"
										:props="HotspotProps"
										lazy
										:load="load"
										node-key="id"
										check-strictly
									/>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
								<el-form-item label="部门" prop="OrgCode">
									<el-cascader
										:options="state.orgsOptions"
										filterable
										:show-all-levels="false"
										:props="{ checkStrictly: true, value: 'id', label: 'orgName', emitPath: false, multiple: true }"
										placeholder="请选择所属部门"
										clearable
										class="w100"
										v-model="state.queryParams.OrgCode"
										ref="cascaderRef"
										@change="getselKnowledgeList"
									>
										<template #default="{ node, data }">
											<span>{{ data.orgName }}</span>
											<span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
										</template>
									</el-cascader>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
								<el-form-item label="受理坐席" prop="NameOrNo">
									<el-input v-model="state.queryParams.NameOrNo" placeholder="坐席姓名/坐席工号" clearable @keyup.enter="getList(state.activeName)" />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
								<el-form-item label="受理时间" prop="crTime">
									<el-date-picker
										v-model="state.queryParams.crTime"
										type="daterange"
										unlink-panels
										range-separator="至"
										start-placeholder="开始日期"
										end-placeholder="结束日期"
										:shortcuts="shortcuts"
										@change="timeStartChangeCr"
										value-format="YYYY-MM-DD[T]HH:mm:ss.sss[Z]"
									/>
									<!-- value-format="YYYY-MM-DD" -->
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
								<el-form-item label="转接来源" prop="TransferPhone">
									<el-input
										v-model="state.queryParams.TransferPhone"
										placeholder="请填写转接来源"
										clearable
										@keyup.enter="getList(state.activeName)"
									/>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
								<el-form-item label="紧急程度" prop="EmergencyLevel">
									<el-select v-model="state.queryParams.EmergencyLevel" placeholder="请选择受理类型" multiple clearable class="w100">
										<el-option v-for="item in state.emergencyLevelOptions" :value="item.key" :key="item.key" :label="item.value" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
								<el-form-item label="办理期限" prop="exTime">
									<el-date-picker
										v-model="state.queryParams.exTime"
										type="daterange"
										unlink-panels
										range-separator="至"
										start-placeholder="开始日期"
										end-placeholder="结束日期"
										:shortcuts="shortcuts"
										@change="timeStartChangeEx"
										value-format="YYYY-MM-DD[T]HH:mm:ss.sss[Z]"
									/>
									<!-- value-format="YYYY-MM-DD" -->
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
								<el-form-item label="电话号码" prop="PhoneNo">
									<el-input v-model="state.queryParams.PhoneNo" placeholder="来电号码/联系电话" clearable @keyup.enter="getList(state.activeName)" />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
								<el-form-item label="推送分类" prop="PushTypeCode">
									<el-select v-model="state.queryParams.PushTypeCode" placeholder="请选择推送分类" clearable class="w100">
										<el-option v-for="item in state.pushTypeOptions" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="6">
								<el-form-item label="工单状态" prop="Status">
									<el-select v-model="state.queryParams.Status" placeholder="请选择工单状态" multiple clearable class="w100">
										<el-option v-for="item in state.orderStatusOptions" :value="item.key" :key="item.key" :label="item.value" />
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</div>
				<!-- 按钮组 -->
				<div class="w100" style="display: flex; justify-content: flex-end">
					<el-button type="primary" @click="getList(state.activeName)" :loading="state.loading">
						<SvgIcon name="ele-Search" class="mr5" />查询
					</el-button>
					<el-button @click="resetQuery(ruleFormRef)" v-waves class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
					<el-button link type="primary" @click="closeSearch">
						{{ searchCol ? '收起' : '展开' }}
						<SvgIcon :class="{ 'is-reverse': searchCol }" name="ele-ArrowDown" class="mr5 arrow" size="18px" />
					</el-button>
				</div>
				<!-- 功能按钮 -->
				<div class="flex-center-between mb20">
					<!-- <p class="table-title">信息列表</p> -->
					<div>
						<el-button type="primary" @click="onAddWorkOrder"> <SvgIcon name="ele-Plus" class="mr5" />新增 </el-button>
						<!-- <el-button type="primary" :disabled="!state.multipleSelection.length" v-waves @click="onImportTable">
								<SvgIcon name="iconfont icon-daochu" class="mr5" />导出
							</el-button> -->
					</div>
				</div>
				<!-- 表格 -->
				<el-table :data="state.tableList" v-loading="state.loading" row-key="id" @selection-change="handleSelectionChange" @sort-change="sortChange">
					<!-- <el-table-column type="selection" width="55" :reserve-selection="true" /> -->
					<el-table-column type="index" width="60" label="序号" />
					<!--  sortable="custom" 工单编码排序 -->
					<el-table-column label="工单编码" prop="no" show-overflow-tooltip width="150">
						<template #default="scope">
							<span>{{ scope.row.no }}</span>
						</template>
					</el-table-column>
					<el-table-column label="标题" show-overflow-tooltip width="400">
						<template #default="scope">
							<span style="color: var(--el-color-primary)">{{ scope.row.title }}</span>
						</template>
					</el-table-column>
					<el-table-column label="工单状态" show-overflow-tooltip width="100">
						<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="currentStepName" label="当前环节" show-overflow-tooltip width="150"></el-table-column>
					<el-table-column prop="acceptTypeText" label="受理类型" show-overflow-tooltip width="150"></el-table-column>
					<el-table-column prop="hotspot" label="热点分类" show-overflow-tooltip width="200"></el-table-column>
					<!--  sortable="custom" 紧急程度排序 -->
					<el-table-column label="紧急程度" show-overflow-tooltip prop="emergencyLevelText" width="100">
						<template #default="scope">
							<span v-if="scope.row.emergencyLevel === 2 || scope.row.emergencyLevel === 3" style="color: var(--el-color-danger)">{{
								scope.row.emergencyLevelText
							}}</span>
							<span v-else style="color: var(--el-color-primary)">{{ scope.row.emergencyLevelText }}</span>
						</template>
					</el-table-column>
					<!--  sortable="custom" 办理期限排序 -->
					<el-table-column prop="expiredTime" label="办理期限" show-overflow-tooltip width="170">
						<template #default="scope">
							<span>{{ formatDate(scope.row.expiredTime, 'YYYY-mm-dd HH:MM:SS') }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="employeeName" label="受理坐席" show-overflow-tooltip width="170">
						<template #default="scope">
							<span>{{ scope.row.employeeName + '[' + scope.row.employeeStaffNo + ']' }}</span>
						</template>
					</el-table-column>
					<el-table-column label="操作" width="150" fixed="right" align="center">
						<!-- 草稿0 status 可以删除 -->
						<template #default="scope">
							<!-- <el-button text type="primary" @click="onEditTemp(scope.row)" title="修改">
								修改
							</el-button>
							<el-button text type="success" v-if="scope.row.status === 0" @click="onReleaseTemp(scope.row)" title="发布">
								发布
							</el-button>
							<el-button text type="warning" v-if="scope.row.status === 2" @click="tempEnable(scope.row)" title="启用">
								启用
							</el-button>-->
							<el-button text type="primary" @click="onOrderDetail(scope.row)" title="详情"> 详情 </el-button>
							<el-button text v-if="scope.row.status === 0" type="danger" @click="onDeleteOrder(scope.row)" title="删除"> 删除 </el-button>
						</template>
					</el-table-column>
					<template #empty>
						<Empty />
					</template>
				</el-table>
				<!-- 分页 -->
				<pagination
					:total="state.total"
					v-model:page="state.queryParams.PageIndex"
					v-model:limit="state.queryParams.PageSize"
					@pagination="getList(state.activeName)"
				/>
			</div>
			<!-- </el-tabs> -->
		</div>
		<!-- 工单详情 -->
		<order-detail ref="detailRef" @updateList="getList(state.activeName)" />
	</div>
</template>
<script setup lang="ts" name="order">
import { defineAsyncComponent, ref, reactive, onMounted, onActivated } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import { useRouter } from 'vue-router';
import { formatDate } from '/@/utils/formatTime';
// import table2excel from 'js-table2excel';
import { listBaseData, orderList, hotspottype, orderDelete } from '/@/api/business/order';

// 引入组件
const OrderDetail = defineAsyncComponent(() => import('/@/views/business/order/components/orderDetail.vue'));
const shortcuts = [
	{
		text: '近一周',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
			return [start, end];
		},
	},
	{
		text: '近一个月',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
			return [start, end];
		},
	},
	{
		text: '近三个月',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
			return [start, end];
		},
	},
];
// 定义变量内容
const ruleFormRef = ref();
const searchCol = ref(false);
const router = useRouter();
const detailRef = ref();
const state = reactive(<any>{
	activeName: 'all',
	queryParams: {
		// 查询条件
		PageIndex: 1,
		PageSize: 10,
		Keyword: '',
		Content: '',
		AcceptType: '',
		Channel: '',
		HotspotId: [],
		OrgCode: [],
		NameOrNo: '',
		crTime: [],
		CreationTimeStart: '',
		CreationTimeEnd: '',
		TransferPhone: '',
		EmergencyLevel: [],
		exTime: [],
		ExpiredTimeStart: '',
		ExpiredTimeEnd: '',
		PhoneNo: '',
		Status: [],
		pushTypeOptions: '',
	},
	tableList: [], //表单
	loading: false,
	total: 0,
	multipleSelection: [], //多选表格
	tabPaneList: [
		{
			label: '全部工单',
			value: 'all',
		},
		{
			label: '即将超期',
			value: 'willExpire',
		},
		{
			label: '超期件',
			value: 'expire',
		},
		{
			label: '会签件',
			value: 'sign',
		},
		{
			label: '督办件',
			value: 'supervise',
		},
		{
			label: '撤销件',
			value: 'revoke',
		},
	],
	acceptTypeOptions: [], //受理类型
	channelOptions: [], // 来源频道
	emergencyLevelOptions: [], // 紧急程度
	orderStatusOptions: [], // 工单状态
	orgsOptions: [], // 部门
	pushTypeOptions: [], //推送分类
	orgData: [],
});
const cascaderRef = ref();
// 热点分类远程搜索
const HotspotProps = {
	label: 'hotSpotName',
	children: 'children',
	isLeaf: 'isLeaf',
};
// 热点分类远程搜索
const load = async (node: any, resolve: any) => {
	if (node.isLeaf) return resolve([]);
	let res: any = await hotspottype({ id: node.data.id ? node.data.id : '' });
	resolve(res.result);
};
// 获取选择组织name值
const getselKnowledgeList = () => {
	let currentNode = cascaderRef.value.getCheckedNodes();
	state.queryParams.orgCode = currentNode[0]?.data.orgCode ?? '';
};
// 展开/收起
const closeSearch = () => {
	searchCol.value = !searchCol.value;
};
// 受理时间
const timeStartChangeCr = (val: string[]) => {
	if (val) {
		state.queryParams.CreationTimeStart = val[0];
		state.queryParams.CreationTimeEnd = val[1];
	}
};
// 过期时间
const timeStartChangeEx = (val: string[]) => {
	if (val) {
		state.queryParams.ExpiredTimeStart = val[0];
		state.queryParams.ExpiredTimeStart = val[1];
	}
};
// 获取查询条件基础信息
const getBaseData = async () => {
	const res: any = await listBaseData();
	state.acceptTypeOptions = res.result?.acceptTypeOptions ?? [];
	state.channelOptions = res.result?.channelOptions ?? [];
	state.emergencyLevelOptions = res.result?.emergencyLevelOptions ?? [];
	state.orgsOptions = res.result?.orgsOptions ?? [];
	state.pushTypeOptions = res.result?.pushTypeOptions ?? [];
	state.orderStatusOptions = res.result?.orderStatusOptions ?? [];
};
/** 获取列表 */
const getList = (val: string) => {
	state.loading = true;
	let request = JSON.parse(JSON.stringify(state.queryParams));
	Reflect.deleteProperty(request, 'crTime'); // 删除无用的参数
	Reflect.deleteProperty(request, 'exTime'); // 删除无用的参数
	switch (val) {
		case 'all':
			orderList(request)
				.then((response: any) => {
					state.tableList = response?.result.items ?? [];
					state.total = response?.result.total;
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
			break;
		case 'willExpire':
			// workflowPaged(state.queryParams)
			// 	.then((response: any) => {
			// 		state.tableList = response.result?.items ?? [];
			// 		state.total = response.result?.total ?? 0;
			// 		state.total = 1;
			setTimeout(() => {
				state.loading = false;
			}, 300);
			// 	})
			// 	.catch(() => {
			// 		state.loading = false;
			// 	});
			break;
		case 'expire':
			// workflowPaged(state.queryParams)
			// 	.then((response: any) => {
			// 		state.tableList = response.result?.items ?? [];
			// 		state.total = response.result?.total ?? 0;
			// 		state.total = 1;
			setTimeout(() => {
				state.loading = false;
			}, 300);
			// 	})
			// 	.catch(() => {
			// 		state.loading = false;
			// 	});
			break;
		case 'sign':
			// workflowPaged(state.queryParams)
			// 	.then((response: any) => {
			// 		state.tableList = response.result?.items ?? [];
			// 		state.total = response.result?.total ?? 0;
			// 		state.total = 1;
			setTimeout(() => {
				state.loading = false;
			}, 300);
			// 	})
			// 	.catch(() => {
			// 		state.loading = false;
			// 	});
			break;
		case 'supervise':
			// workflowPaged(state.queryParams)
			// 	.then((response: any) => {
			// 		state.tableList = response.result?.items ?? [];
			// 		state.total = response.result?.total ?? 0;
			// 		state.total = 1;
			setTimeout(() => {
				state.loading = false;
			}, 300);
			// 	})
			// 	.catch(() => {
			// 		state.loading = false;
			// 	});
			break;
		case 'revoke':
			// workflowPaged(state.queryParams)
			// 	.then((response: any) => {
			// 		state.tableList = response.result?.items ?? [];
			// 		state.total = response.result?.total ?? 0;
			// 		state.total = 1;
			setTimeout(() => {
				state.loading = false;
			}, 300);
			// 	})
			// 	.catch(() => {
			// 		state.loading = false;
			// 	});
			break;
		default:
			break;
	}
};
// 表格排序
const sortChange = (column: any) => {
	console.log(column);
};
/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	state.queryParams.CreationTimeStart = '';
	state.queryParams.CreationTimeEnd = '';
	state.queryParams.ExpiredTimeStart = '';
	state.queryParams.ExpiredTimeStart = '';
	getList(state.activeName);
};
// 切换tab 查询列表
// const handleClick = (val: string) => {
// 	getList(val);
// };
// 多选表格
const handleSelectionChange = (val: any) => {
	state.multipleSelection = val;
};
// 新增工单
const onAddWorkOrder = () => {
	// 跳转到录入工单页面
	router.push('/business/order/accept');
};
// 查看详情
const onOrderDetail = (row: any) => {
	if (row.status === 0) {
		// 草稿状态跳转到编辑页面
		router.push({
			name: 'orderEdit',
			params: {
				id: row.id,
				tagsViewName: '工单受理-' + row.no,
			},
		});
	} else {
		// 已经发布的直接查看详情
		detailRef.value.openDialog(row);
	}
};
// 删除工单
const onDeleteOrder = (row: any) => {
	ElMessageBox.confirm(`确认删除【${row.no}】?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			orderDelete(row.id).then(() => {
				ElMessage.success('操作成功');
				getList(state.activeName);
			});
		})
		.catch(() => {});
};
// 导出列表
// const onImportTable = () => {
// 	const tabeHeader = [
// 		{ key: 'phoneNo', colWidth: '', title: '电话号码', type: 'text', isCheck: true },
// 		{ key: 'duration', colWidth: '', title: '黑名单时长(秒)', type: 'text', isCheck: true },
// 		{ key: 'creationTime', colWidth: '', title: '创建时间', type: 'text', isCheck: true },
// 	];
// 	table2excel(tabeHeader, state.multipleSelection, `${formatDate(new Date(), 'YYYY-mm-dd HH-MM')}`);
// };
onMounted(async () => {
	getBaseData();
	getList(state.activeName);
});
onActivated(() => {
	getList(state.activeName);
});
</script>
<style scoped lang="scss">
.business-oreder-container {
	:deep(.el-tabs__content) {
		height: 100%;
	}
	.flex-column {
		display: flex;
		flex-direction: column;
		height: 100%;
		.el-table {
			flex: 1;
		}
	}
	.search-inner {
		max-width: 100%;
		max-height: 500px;
		/* 增加过渡时间以适应高度 */
		transition: max-height 0.2s linear;
	}
	.arrow {
		transition: transform var(--el-transition-duration);
		transform: rotateZ(0);
		cursor: pointer;
	}
	.arrow.is-reverse {
		transform: rotateZ(-180deg);
	}
	.search-inner.search-coloct {
		max-height: 48px;
		overflow: hidden;
		margin-bottom: 20px;
	}
	:deep(.el-form-item) {
		width: 100%;
	}
}
</style>
