<template>
	<div class="todo-order-container layout-pd">
		<el-card shadow="never">
			<el-tabs v-model="state.queryParams.IsHandled" class="demo-tabs" @tab-change="queryList">
				<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 inline>
				<el-form-item label="关键字" prop="Keyword">
					<el-input v-model="state.queryParams.Keyword" placeholder="工单编码/标题" clearable @keyup.enter="queryList" class="keyword-input" />
				</el-form-item>
				<el-form-item label="是否省工单" prop="IsProvince">
					<el-select v-model="state.queryParams.IsProvince" placeholder="请选择是否省工单">
						<el-option label="是" value="true" />
						<el-option label="否" value="false" />
					</el-select>
				</el-form-item>
				<el-form-item label="是否会签" prop="IsCountersign">
					<el-select v-model="state.queryParams.IsCountersign" placeholder="请选择是否会签">
						<el-option label="是" value="true" />
						<el-option label="否" value="false" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="queryList" :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-form-item>
			</el-form>
			<!-- 表格 -->
			<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()"
			>
				<!-- 表格 header 按钮 -->
				<template #tableHeader="scope">
					<el-button type="primary" @click="onAddOrder" v-auth="'todo:seats:add'"> <SvgIcon name="ele-Plus" class="mr5" />新建工单 </el-button>
				</template>
				<template #expiredStatus="{ row }">
					<span :class="'overdue-status-' + row.expiredStatus" :title="row.expiredStatusText"></span>
				</template>
				<template #isProvince="{ row }">
					<span>{{ row.isProvince ? '省工单' : '市工单' }}</span>
				</template>
				<template #title="{ row }">
					<order-detail :order="row" @updateList="queryList">{{ row.title }}</order-detail>
				</template>
				<template #employeeName="{ row }">
					<span
						>{{ row.acceptorName }} <span v-if="row.acceptorStaffNo">[{{ row.acceptorStaffNo }}]</span>
					</span>
				</template>
				<!-- 表格操作 -->
				<template #operation="{ row }">
					<el-button link type="success" @click="onOrderEdit(row)" title="编辑工单" v-if="row.canEdit" v-auth="'todo:seats:edit'"> 修改 </el-button>
					<el-button link type="primary" @click="onSign(row)" title="签收工单" v-if="row.canSign" v-auth="'todo:seats:sign'"> 签收 </el-button>
					<order-detail :order="row" @updateList="queryList" />
				</template>
			</ProTable>
		</el-card>
	</div>
</template>
<script setup lang="tsx" name="todoOrder">
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElButton, ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { throttle } from '@/utils/tools';
import { formatDate } from '@/utils/formatTime';
import { useRouter } from 'vue-router';
import { seatsListTodo, orderSign } from '@/api/todo/order';
// 引入组件
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
// 定义变量内容
const state = reactive({
	queryParams: {
		// 查询条件
		PageIndex: 1, // 当前页
		PageSize: 10, // 每页条数
		IsHandled: 'false', // 工单状态
		Keyword: null, // 关键字
		IsProvince: null, // 是否省工单
		IsCountersign: null, // 是否会签
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
});
const ruleFormRef = ref<RefType>(); // 表单ref
const router = useRouter(); // 路由
const proTableRef = ref<RefType>(); // 表格ref
// 表格配置项
const columns = ref<any[]>([
	{ type: 'selection', fixed: 'left', width: 55 },
	{ prop: 'expiredStatus', label: '超期状态', align: 'center' },
	{ prop: 'no', label: '工单编码', width: 150 },
	{ prop: 'isProvince', 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: 'acceptType', label: '受理类型', width: 150 },
	{ prop: 'emergencyLevelText', label: '紧急程度', width: 150 },
	{ prop: 'sourceChannel', label: '来源方式', width: 100 },
	{ prop: 'hotspotName', label: '热点分类', width: 200 },
	{ prop: 'employeeName', label: '受理人', width: 120 },
	{ prop: 'operation', label: '操作', fixed: 'right', width: 140, align: 'center' },
]);
// 获取查询条件基础信息
/** 获取列表 */
const queryList = throttle(async () => {
	try {
		state.loading = true;
    const index = columns.value.findIndex((item) => item.prop === 'acceptType');
    if (state.queryParams.IsHandled === 'true') {
      if (!columns.value.find((item) => item.prop === 'orgLevelOneName')) {
        columns.value.splice(
          index,
          0,
          { prop: 'orgLevelOneName', label: '一级部门', width: 150 },
          { prop: 'actualHandleOrgName', label: '接办部门', width: 150 }
        );
      }
    } else {
      if (columns.value.find((item) => item.prop === 'orgLevelOneName')) {
        columns.value = columns.value.filter((item) => item.prop !== 'orgLevelOneName' && item.prop !== 'actualHandleOrgName');
      }
    }
		const res: any = await seatsListTodo(state.queryParams);
		state.tableData = res.result?.items ?? [];
		state.total = res.result?.total ?? 0;
		state.loading = false;
	} catch (e) {
		state.loading = false;
	}
}, 300);
/** 重置按钮操作 */
const resetQuery = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
}, 300);
// 新增工单
const onAddOrder = () => {
	if (!router.hasRoute('orderAccept')) {
		ElMessage.warning('当前用户未配置工单受理页面');
		return;
	}
	router.push({
		name: 'orderAccept',
		params: {
			tagsViewName: '工单受理',
		},
	});
};
// 导出
const onExport = () => {
	console.log('导出');
};
// 编辑工单
const onOrderEdit = (row: any) => {
	if (!router.hasRoute('orderAccept')) {
		ElMessage.warning('当前用户未配置工单受理页面');
		return;
	}
	router.push({
		name: 'orderAccept',
		params: {
			tagsViewName: '工单受理-' + row.no,
			id: row.id,
			callId: '0',
		},
	});
};
// 签收工单
const onSign = (row: any) => {
	ElMessageBox.confirm(`您确定要要签收【${row.title}】，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			orderSign(row.id).then(() => {
				ElMessage.success('签收成功');
				queryList();
			});
		})
		.catch(() => {});
};
onMounted(() => {
	queryList();
});
</script>
