<template>
	<div class="todo-order-container layout-pd">
		<el-card shadow="never">
			<el-tabs v-model="state.queryParams.IsHandled" @tab-change="handleQuery">
				<el-tab-pane name="false" label="工单待办"></el-tab-pane>
				<el-tab-pane name="true" label="工单已办"></el-tab-pane>
			</el-tabs>
			<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent>
				<el-row :gutter="20">
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item label="工单标题" prop="Keyword">
							<el-input v-model="state.queryParams.Keyword" placeholder="工单标题" clearable @keyup.enter="handleQuery" />
						</el-form-item>
					</el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
            <el-form-item label="工单编码" prop="No">
              <el-input v-model="state.queryParams.No" placeholder="工单编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item label="生成时间" prop="scTime">
							<el-date-picker
								v-model="state.queryParams.scTime"
								type="datetimerange"
								unlink-panels
								range-separator="至"
								start-placeholder="开始时间"
								end-placeholder="结束时间"
								:shortcuts="shortcuts"
								@change="handleQuery"
								value-format="YYYY-MM-DD[T]HH:mm:ss"
                :default-time="defaultTimeStartEnd"
							/>
						</el-form-item>
					</el-col>
          <transition name="el-zoom-in-top">
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" v-show="!searchCol">
						<el-form-item label="是否省工单" prop="IsProvince">
							<el-select v-model="state.queryParams.IsProvince" placeholder="请选择是否省工单" @change="handleQuery" class="w100">
								<el-option label="是" value="true" />
								<el-option label="否" value="false" />
							</el-select>
						</el-form-item>
					</el-col>
          </transition>
					<transition name="el-zoom-in-top">
						<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" v-show="!searchCol">
							<el-form-item label="是否会签" prop="IsCounterSign">
								<el-select v-model="state.queryParams.IsCounterSign" placeholder="请选择是否会签" @change="handleQuery" class="w100">
									<el-option label="是" value="true" />
									<el-option label="否" value="" />
								</el-select>
							</el-form-item>
						</el-col>
					</transition>
					<transition name="el-zoom-in-top">
						<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6" v-show="!searchCol">
							<el-form-item label="超期状态" prop="ExpiredOrAlmostOverdue">
								<el-select v-model="state.queryParams.ExpiredOrAlmostOverdue" placeholder="请选择超期状态" @change="handleQuery" class="w100">
									<el-option label="已超期" value="true" />
									<el-option label="即将超期" value="false" />
								</el-select>
							</el-form-item>
						</el-col>
					</transition>
					<el-col :xs="24" :sm="12" :md="12" :lg="6" :xl="6">
						<el-form-item label="">
							<div class="flex-end w100">
								<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
								<el-button @click="resetQuery(ruleFormRef)" class="default-button" :loading="state.loading">
									<SvgIcon name="ele-Refresh" class="mr5" />重置
								</el-button>
								<el-button link type="primary" @click="closeSearch" :loading="state.loading">
									{{ searchCol ? '展开' : '收起' }}
									<SvgIcon :class="{ 'is-reverse': searchCol }" name="ele-ArrowUp" class="mr5 arrow" size="18px" />
								</el-button>
							</div>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<!-- 表格 -->
			<!--      :toolButton="['refresh', 'setting', 'exportCurrent', 'exportAll']"-->
			<ProTable
				ref="proTableRef"
				:columns="columns"
				:data="state.tableData"
				@updateTable="queryList"
				:loading="state.loading"
				:total="state.total"
				v-model:page-index="state.queryParams.PageIndex"
				v-model:page-size="state.queryParams.PageSize"
				:key="Math.random()"
				@export-current="exportTable($event)"
				@export-all="exportTable($event, true)"
			>
				<template #tableHeader="scope">
					<el-button type="primary" @click="onJbExport" :disabled="!scope.isSelected" :loading="state.loading" v-auth="'todo:seats:jbdExport'"
						><SvgIcon name="iconfont icon-daochu" class="mr5" />交办单导出
					</el-button>
				</template>
				<template #expiredStatusText="{ row }">
					<span :class="'overdue-status-' + row.expiredStatus" :title="row.expiredStatusText"></span>
				</template>
				<template #title="{ row }">
					<order-detail :order="row" @updateList="queryList">{{ row.title }}</order-detail>
				</template>
				<!-- 表格操作 -->
				<template #operation="{ row }">
					<order-detail :order="row" @updateList="queryList" />
				</template>
			</ProTable>
		</el-card>
	</div>
</template>
<script setup lang="tsx" name="todoOrder">
import { defineAsyncComponent, onMounted, reactive, ref,onActivated, onBeforeUnmount } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { useRouter } from 'vue-router';
import { orderListTodo } from '@/api/todo/order';
import { exportJbOrder, exportOrder } from "@/api/business/order";
import { downloadFileByStream, downloadZip } from "@/utils/tools";
import { defaultDateThree, defaultTimeStartEnd, shortcuts } from "@/utils/constants";
import Other from '@/utils/other';
import mittBus from "@/utils/mitt";
// 引入组件
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
// 定义变量内容
const state = reactive<any>({
	queryParams: {
		// 查询条件
		PageIndex: 1, // 当前页
		PageSize: 10, // 每页条数
		IsHandled: 'false', // 工单状态
		Keyword: null, // 工单标题
    No: null, // 工单编码
		IsProvince: null, // 是否省工单
		IsCounterSign: null, // 是否会签
		ExpiredOrAlmostOverdue: null, // 超期状态
		scTime: defaultDateThree,
		StartTime: null,
		EndTime: null,
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
});
const ruleFormRef = ref<RefType>(); // 表单ref
const searchCol = ref(true); // 展开/收起
// 展开/收起
const closeSearch = () => {
	searchCol.value = !searchCol.value;
};
const router = useRouter(); // 路由
const proTableRef = ref<RefType>(); // 表格ref
// 表格配置项
const columns = ref<any[]>([]);
const columnsTodo = [
	{ type: 'selection', fixed: 'left', width: 55, align: 'center' },
	{ prop: 'expiredStatusText', label: '超期状态', align: 'center', width: 80 },
	{ prop: 'no', label: '工单编码', width: 150 },
	{ prop: 'isProvinceText', label: '省/市工单', width: 100 },
  // { prop: 'emergencyLevelText', label: '是否紧急'},
	{ prop: 'actualHandleStepName', label: '办理节点', width: 150 },
	{ prop: 'statusText', label: '工单状态', width: 100 },
	{ prop: 'title', label: '工单标题', width: 300 },
	{ prop: 'counterSignTypeText', label: '是否会签', width: 100 },
	{
		prop: 'creationTime',
		label: '生成时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.creationTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{
		prop: 'startTime',
		label: '受理时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.startTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{
		prop: 'expiredTime',
		label: '工单期满时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.expiredTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{ prop: 'acceptType', label: '受理类型', width: 150 },
	{ prop: 'sourceChannel', label: '来源方式', width: 100 },
	{ prop: 'hotspotName', label: '热点分类', width: 200 },
	{ prop: 'acceptorName', label: '受理人', width: 120 },
	{
		prop: 'reTransactNum',
		label: '重办次数',
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 140, align: 'center' },
];
const columnsDone = [
	// 已办
	{ type: 'selection', fixed: 'left', width: 55, align: 'center' },
	{ prop: 'expiredStatusText', label: '超期状态', align: 'center', width: 80 },
	{ prop: 'no', label: '工单编码', width: 150 },
	{ prop: 'isProvinceText', label: '省/市工单', width: 100 },
	{ prop: 'actualHandleStepName', label: '办理节点', width: 150 },
	{ prop: 'statusText', label: '工单状态', width: 100 },
	{ prop: 'title', label: '工单标题', width: 300 },
	{ prop: 'counterSignTypeText', label: '是否会签', width: 100 },
	{
		prop: 'creationTime',
		label: '生成时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.creationTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{
		prop: 'startTime',
		label: '受理时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.startTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{
		prop: 'expiredTime',
		label: '工单期满时间',
		width: 170,
		render: (scope) => {
			return <span>{formatDate(scope.row.expiredTime, 'YYYY-mm-dd HH:MM:SS')}</span>;
		},
	},
	{ prop: 'orgLevelOneName', label: '一级部门', width: 150 },
	{ prop: 'actualHandleOrgName', label: '接办部门', width: 150 },
	{ prop: 'acceptType', label: '受理类型', width: 150 },
	{ prop: 'sourceChannel', label: '来源方式', width: 100 },
	{ prop: 'hotspotName', label: '热点分类', width: 200 },
	{ prop: 'acceptorName', label: '受理人', width: 120 },
	{
		prop: 'reTransactNum',
		label: '重办次数',
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 140, align: 'center' },
];
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
/** 获取列表 */
const queryList = async () => {
	try {
		state.loading = true;
		if (state.queryParams.IsHandled === 'true') {
			columns.value = columnsDone;
		} else {
			columns.value = columnsTodo;
		}
		let request = Other.deepClone(state.queryParams);
		request.StartTime = state.queryParams.scTime === null ? null : state.queryParams.scTime[0];
		request.EndTime = state.queryParams.scTime === null ? null : state.queryParams.scTime[1];
		Reflect.deleteProperty(request, 'scTime');
		const res: any = await orderListTodo(request);
		state.tableData = res.result?.items ?? [];
		state.total = res.result?.total ?? 0;
		state.loading = false;
	} catch (e) {
		state.loading = false;
	}
};
/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
// 交办单导出
const onJbExport = () => {
	const ids = proTableRef.value.selectedList.map((item: any) => item.id);
	ElMessageBox.confirm(`您确定导出选中的${proTableRef.value.selectedList.length}个工单的交办单，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			exportJbOrder(ids)
				.then((res: any) => {
					downloadZip(res);
					state.loading = false;
					ElMessage.success('导出成功');
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
// 表格导出
const exportTable = (val: any, isExportAll = false) => {
	const columnInfos = val.map((item: any) => {
		return {
			prop: item.prop,
			name: item.label,
		};
	});
	const req = {
		queryDto: { ...state.queryParams },
		columnInfos,
		isExportAll,
	};
	state.loading = true;
	exportOrder(req)
		.then((res: any) => {
			state.loading = false;
			downloadFileByStream(res);
		})
		.catch(() => {
			state.loading = false;
		});
};
const historyParams = history.state;
onMounted(() => {
	if (historyParams.IsCountersign) {
		// 会签待办
		// 先重置其他查询条件
		ruleFormRef.value.resetFields();
		state.queryParams = { ...state.queryParams, IsCountersign: historyParams.IsCountersign };
	}
	if (historyParams.ExpiredOrAlmostOverdue) {
		// 即将超期 已超期
		ruleFormRef.value.resetFields();
		state.queryParams = { ...state.queryParams, ExpiredOrAlmostOverdue: historyParams.ExpiredOrAlmostOverdue };
	}
	queryList();
});
onActivated(() => {
  mittBus.on('clearCachePage', () => {
    //清除缓存
    queryList();
  });
});
onBeforeUnmount(() => {
  mittBus.off('clearCachePage');
});
</script>
<style scoped lang="scss">
.todo-order-container {
	.arrow {
		transition: transform var(--el-transition-duration);
		cursor: pointer;
	}
	.arrow.is-reverse {
		transform: rotateZ(-180deg);
	}
}
</style>
