<template>
	<div class="business-publish-todo-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent inline>
				<el-form-item label="数据范围" prop="QuerySelf" v-auth="'business:publish:todo:querySelf'">
					<el-segmented
						:options="[
							{ label: '我的', value: 'true' },
							{ label: '全部', value: 'false' },
						]"
						v-model="state.queryParams.QuerySelf"
						@change="handleQuery"
						:disabled="state.loading"
					/>
				</el-form-item>
				<el-form-item label="省市工单" prop="fastSearch">
					<el-segmented
						:options="[
							{
								value: 'all',
								label: '全部',
							},
							{
								value: 'city',
								label: '市工单',
							},
							{
								value: 'province',
								label: '省工单',
							},
						]"
						v-model="fastSearch"
						@change="fastSearchChange"
						:disabled="state.loading"
					/>
				</el-form-item>
				<el-form-item label="工单标题" prop="Title">
					<el-input v-model.trim="state.queryParams.Title" placeholder="工单标题" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item label="工单编码" prop="No">
					<el-input v-model.trim="state.queryParams.No" placeholder="工单编码" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
					<el-button @click="drawer = true" class="default-button"> <SvgIcon name="ele-Search" class="mr5" />更多查询</el-button>
				</el-form-item>
			</el-form>
			<vxe-toolbar
				ref="toolbarRef"
				:loading="state.loading"
				custom
				:refresh="{
					queryMethod: handleQuery,
				}"
			>
				<template #buttons>
					<el-button type="primary" @click="onJbExport" :loading="state.loading" :disabled="isChecked"
						><SvgIcon name="iconfont icon-daochu" class="mr5" />交办单导出
					</el-button>
					<el-button type="primary" @click="publishMultiple" v-auth="'business:publish:todo:multiple'" :disabled="isChecked">
						<SvgIcon name="iconfont icon-tianjiawenjian" class="mr5" />批量发布
					</el-button>
					<el-button type="primary" @click="onMigration" v-auth="'business:publish:todo:migration'" :disabled="isChecked">
						<SvgIcon name="ele-Rank" class="mr5" />平级移动
					</el-button>
				</template>
			</vxe-toolbar>
			<div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
				<vxe-table
					border
					:loading="state.loading"
					:data="state.tableData"
					:column-config="{ resizable: true }"
					:row-config="{ isCurrent: true, isHover: true, height: 30 }"
					ref="tableRef"
					@checkbox-all="selectAllChangeEvent"
					@checkbox-change="selectChangeEvent"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 0 }"
					id="businessPublishTodo"
					:custom-config="{ storage: true }"
				>
					<vxe-column type="checkbox" width="60" align="center"></vxe-column>
					<vxe-column field="expiredStatusText" title="超期状态" width="90" align="center">
						<template #default="{ row }">
							<span :class="'overdue-status-' + row.expiredStatus" :title="row.expiredStatusText"></span>
						</template>
					</vxe-column>
					<vxe-column field="no" title="工单编码" width="140"></vxe-column>
					<vxe-column field="isProvinceText" title="省/市工单" width="100"></vxe-column>
					<vxe-column field="statusText" title="工单状态" width="100"></vxe-column>
					<vxe-column field="title" title="工单标题" width="200">
						<template #default="{ row }">
							<order-detail :order="row" @updateList="queryList(true)">{{ row.title }}</order-detail>
						</template>
					</vxe-column>
					<vxe-column field="sourceChannel" title="来源渠道" width="100"></vxe-column>
					<vxe-column field="acceptType" title="受理类型" width="100"></vxe-column>
					<vxe-column field="counterSignTypeText" title="是否会签" width="90"></vxe-column>
					<vxe-column field="actualHandleOrgName" title="接办部门" width="140"></vxe-column>
					<vxe-column field="hotspotName" title="热点分类" width="140"></vxe-column>
					<vxe-column field="acceptorName" title="受理人" width="120"></vxe-column>
					<vxe-column field="actualHandleTime" title="接办时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.actualHandleTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="startTime" title="受理时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.startTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="filedTime" title="办结时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.filedTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column title="操作" fixed="right" width="90" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="publish(row)" title="发布工单" v-auth="'business:publish:todo:publish'"> 发布 </el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
			<div class="flex-end" style="align-items: center">
				<span v-loading="totalLoading" class="mr10">共 {{ totalCount }} 条</span>
				<!--				sizes-->
				<el-pagination
					layout="prev, pager, next"
					:total="state.total"
					@current-change="handleCurrentChange"
					:page-size="state.queryParams.PageSize"
					:current-page="state.queryParams.PageIndex"
					@size-change="handleSizeChange"
					:disabled="state.loading"
				/>
			</div>
		</div>
		<!-- 工单发布详情 -->
		<order-publish ref="orderPublishRef" @updateList="queryList(true)" />
		<!-- 工单平移 -->
		<order-migration ref="orderMigrationRef" @updateList="queryList(true)" />
		<!--	更多查询	-->
		<el-drawer v-model="drawer" title="更多查询" size="500px">
			<el-form :model="state.queryParams" ref="drawerRuleFormRef" @submit.native.prevent label-width="100px">
				<el-form-item label="归档类型" prop="FiledType">
					<el-select v-model="state.queryParams.FiledType" placeholder="请选择归档类型" @change="handleQuery" clearable>
						<el-option label="中心归档" value="10" />
						<el-option label="部门归档" value="20" />
					</el-select>
				</el-form-item>
				<el-form-item label="是否会签" prop="IsCountersign">
					<el-select v-model="state.queryParams.IsCountersign" placeholder="请选择是否会签" @change="handleQuery" clearable>
						<el-option label="是" value="true" />
						<el-option label="否" value="false" />
					</el-select>
				</el-form-item>
				<el-form-item label="受理时间" prop="slTime">
					<el-date-picker
						v-model="state.queryParams.slTime"
						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-form-item label="来电号码" prop="FromPhone">
					<el-input v-model.trim="state.queryParams.FromPhone" placeholder="来电号码" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="接办部门" prop="ActualHandleOrgName">
					<el-input v-model="state.queryParams.ActualHandleOrgName" placeholder="请填写接办部门名称" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="受理类型" prop="AcceptType">
					<el-select v-model="state.queryParams.AcceptType" placeholder="请选择受理类型" clearable @change="handleQuery">
						<el-option v-for="item in acceptTypeOptions" :value="item.dicDataValue" :key="item.dicDataValue" :label="item.dicDataName" />
					</el-select>
				</el-form-item>
				<el-form-item label="热点分类" prop="Hotspot">
					<el-input v-model.trim="state.queryParams.Hotspot" placeholder="热点分类名称" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="受理人" prop="NameOrNo">
					<el-input v-model="state.queryParams.NameOrNo" placeholder="受理人/坐席工号" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="派单人" prop="CenterToOrgHandlerName">
					<el-input v-model="state.queryParams.CenterToOrgHandlerName" placeholder="派单人" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="来源渠道" prop="Channel">
					<el-select v-model="state.queryParams.Channel" placeholder="请选择来源渠道" clearable @change="handleQuery">
						<el-option v-for="items in channelOptions" :key="items.dicDataValue" :label="items.dicDataName" :value="items.dicDataValue" />
					</el-select>
				</el-form-item>
				<el-form-item label="办结时间" prop="bjTime">
					<el-date-picker
						v-model="state.queryParams.bjTime"
						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>
				<template v-if="['ZiGong'].includes(themeConfig.appScope)">
					<!--					<el-form-item label="行业" prop="Channel">
						<el-select v-model="state.queryParams.Channel" placeholder="请选择行业" clearable @change="handleQuery">
							<el-option v-for="items in channelOptions" :key="items.dicDataValue" :label="items.dicDataName" :value="items.dicDataValue" />
						</el-select>
					</el-form-item>-->
					<el-form-item label="工单标签" prop="OrderTag">
						<el-select v-model="state.queryParams.OrderTag" placeholder="请选择工单标签" clearable @change="handleQuery">
							<el-option v-for="items in orderTags" :key="items.dicDataValue" :label="items.dicDataName" :value="items.dicDataValue" />
						</el-select>
					</el-form-item>
				</template>
				<el-form-item label="是否超期" prop="IsOverTime">
					<el-select v-model="state.queryParams.IsOverTime" placeholder="请选择是否超期" class="w100" clearable @change="handleQuery">
						<el-option label="是" :value="true" />
						<el-option label="否" :value="false" />
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button type="primary" @click="handleQuery" :loading="state.loading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
				<el-button @click="resetQuery(drawerRuleFormRef)" class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置 </el-button>
			</template>
		</el-drawer>
	</div>
</template>
<script setup lang="tsx" name="businessPublishTodo">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import { batchPublishOrder, publishBaseInfo, publishListFixed, publishListFixedCount } from '@/api/todo/publish';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import { useThemeConfig } from '@/stores/themeConfig';
import { storeToRefs } from 'pinia';
import Other from '@/utils/other';
import { exportAssignment, getNeedArr } from '@/utils/tools';
// 引入组件
const OrderPublish = defineAsyncComponent(() => import('@/views/business/publish/components/Order-publish.vue')); // 发布
const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情
const OrderMigration = defineAsyncComponent(() => import('@/views/todo/center/Order-migration.vue')); // 工单平移
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
// 定义变量内容
const state = reactive<any>({
	queryParams: {
		// 查询条件
		PageIndex: 1,
		PageSize: 20,
		OrderTitle: null, // 关键词
		No: null,
		FiledType: null, // 归档类型
		IsCountersign: null, // 是否会签
		Keyword: null, // 标题
		QuerySelf: 'true', // 是否只查询自己的待发布工单
		IsProvinceOrder: null, // 是否省工单
		Channel: null,
		slTime: [],
		CreationTimeStart: null,
		CreationTimeEnd: null,
		bjTime: [],
		FiledTimeStart: null,
		FiledTimeEnd: null,
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
});
const fastSearch = ref('all'); // tab位置
const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
const fastSearchChange = (val: string) => {
	fastSearch.value = val;
	switch (val) {
		case 'all':
			state.queryParams.IsProvinceOrder = null;
			break;
		case 'city':
			state.queryParams.IsProvinceOrder = false;
			break;
		case 'province':
			state.queryParams.IsProvinceOrder = true;
			break;
	}
	handleQuery();
};
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryIndex.value = 0;
	queryList(true);
};
// 改变页码
const queryIndex = ref(0); // 数据批次
const totalTable = ref([]); // 数据总数
const handleCurrentChange = (val: number) => {
	state.queryParams.PageIndex = val;
	// 判断当前页是否是数据的最后一页
	if (val === Math.ceil(state.total / state.queryParams.PageSize)) {
		queryList();
	} else {
		state.tableData = getNeedArr(totalTable.value, state.queryParams.PageSize)[state.queryParams.PageIndex - 1]; //当前页的表格数据
	}
};
// 改变每页条数
const handleSizeChange = (val: any) => {
	state.queryParams.PageSize = val;
	// 判断当前页是否是数据的最后一页
	if (val === Math.ceil(state.total / state.queryParams.PageSize)) {
		queryList();
	} else {
		state.tableData = getNeedArr(totalTable.value, state.queryParams.PageSize)[state.queryParams.PageIndex - 1]; //当前页的表格数据
	}
};
/** 获取列表 */
const requestParams = ref<EmptyObjectType>({});
const totalCount = ref(0);
const totalLoading = ref(false);
const queryList = (isQuery: boolean = false) => {
	return new Promise((resolve, reject) => {
		state.loading = true;
		requestParams.value = Other.deepClone(state.queryParams);
		requestParams.value.CreationTimeStart = state.queryParams.slTime === null ? null : state.queryParams.slTime[0]; // 受理时间
		requestParams.value.CreationTimeEnd = state.queryParams.slTime === null ? null : state.queryParams.slTime[1];
		Reflect.deleteProperty(requestParams.value, 'slTime'); // 删除无用的参数
		requestParams.value.FiledTimeStart = state.queryParams.bjTime === null ? null : state.queryParams.bjTime[0]; // 期满时间
		requestParams.value.FiledTimeEnd = state.queryParams.bjTime === null ? null : state.queryParams.bjTime[1];
		Reflect.deleteProperty(requestParams.value, 'bjTime'); // 删除无用的参数
		requestParams.value.QueryIndex = queryIndex.value; // 数据批次
		if(isQuery) requestParams.value.QueryIndex = 0;
		publishListFixed(requestParams.value)
			.then((res: any) => {
				if (isQuery) {
					// 如果是查询
					totalTable.value = []; // 先清空
					totalTable.value = res?.result;
					state.total = totalTable.value.length;
					state.tableData = getNeedArr(totalTable.value, state.queryParams.PageSize)[state.queryParams.PageIndex - 1]; //当前页的表格数据
					queryIndex.value = 1; // 请求完成之后，页码加一避免重复
				} else {
					if (res?.result.length) queryIndex.value++;
					totalTable.value = totalTable.value.concat(res?.result);
					state.total = totalTable.value.length;
					state.tableData = getNeedArr(totalTable.value, state.queryParams.PageSize)[state.queryParams.PageIndex - 1]; //当前页的表格数据
				}
				state.loading = false;
				resolve(res);
			})
			.then(() => {
				// 查询总数
				publishListFixedCount(requestParams.value)
					.then((count) => {
						totalCount.value = count.result;
						totalLoading.value = false;
					})
					.catch(() => {
						totalLoading.value = false;
					});
			})
			.catch(() => {
				state.loading = false;
				totalLoading.value = false;
				reject();
			});
	});
};
/** 重置按钮操作 */
const drawerRuleFormRef = ref();
const ruleFormRef = ref<RefType>(); // 表单ref
const drawer = ref(false);
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	state.queryParams.QuerySelf = 'true';
	ruleFormRef.value?.resetFields();
	state.queryParams.IsProvinceOrder = null;
	fastSearch.value = 'all';
	queryList();
};
// 批量发布
const publishMultiple = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	ElMessageBox.confirm(`您确定要发布选中的工单吗，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			batchPublishOrder({ ids }).then(() => {
				ElMessage.success('操作成功');
				/*ElNotification({
					dangerouslyUseHTMLString: true,
					message: `<p style="word-break: break-all;max-height: 500px;overflow: auto">${res.result}</p>`,
					type: 'info',
				})*/
				handleQuery();
			});
		})
		.catch(() => {});
};
// 发布
const orderPublishRef = ref<RefType>(); // 工单发布详情ref
const publish = (row: any) => {
	orderPublishRef.value.openDialog(row);
};
// 平移功能
const orderMigrationRef = ref<RefType>();
const onMigration = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	orderMigrationRef.value.openDialog('publishTodo', ids);
};
// 获取基础信息
const channelOptions = ref<EmptyArrayType>([]); // 来源渠道
const acceptTypeOptions = ref<EmptyArrayType>([]); // 受理类型
const orderTags = ref<EmptyArrayType>([]); // 工单标签
const getBaseInfo = async () => {
	// 获取基础信息
	try {
		const { result } = await publishBaseInfo();
		channelOptions.value = result.channelOptions;
		acceptTypeOptions.value = result.acceptTypeOptions;
		orderTags.value = result.orderTags;
	} catch (e) {
		console.log(e);
	}
};
// 交办单导出
const onJbExport = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	exportAssignment(ids);
};
const tableRef = ref<RefType>();
const checkTable = ref<EmptyArrayType>([]);
const selectAllChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEvent = ({ checked }) => {
	if (tableRef.value) {
		const records = tableRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isChecked = computed(() => {
	return !Boolean(checkTable.value.length);
});
const toolbarRef = ref<RefType>();
onMounted(() => {
	queryList().then(() => {
		getBaseInfo();
	});
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
