<template>
	<div class="dataShare-orderNoCallLog-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="CaseSerial">
					<el-input v-model="state.queryParams.CaseSerial" placeholder="省本地编码" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item label="时间段" prop="crTime">
					<el-date-picker
						v-model="state.queryParams.crTime"
						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"
						:clearable="false"
					/>
				</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="resetQuery(ruleFormRef)" class="default-button" :loading="state.loading">
						<SvgIcon name="ele-Refresh" 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="onEdit(true)" :disabled="isChecked" :loading="state.loading" title="修改并推送"> 修改并推送 </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,useKey: true }"
					ref="tableRef"
					@checkbox-all="selectAllChangeEvent"
					@checkbox-change="selectChangeEvent"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 100 }"
					id="dataShareOrderNoCallLog"
					:custom-config="{ storage: true }"
				>
					<vxe-column type="checkbox" width="50" align="center"></vxe-column>
					<vxe-column field="requestData.CASE_TITLE" title="工单标题" min-width="200">
						<template #default="{ row }">
							<order-detail :order="{ id: row.orderId }" :disabled="!row.orderId" @updateList="queryList(true)">{{
								row.requestData?.CASE_TITLE
							}}</order-detail>
						</template>
					</vxe-column>
					<vxe-column field="provinceNo" title="省本地编码" min-width="240"></vxe-column>
					<vxe-column field="caseSource" title="来源渠道" width="100"></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="creationTime" title="入库时间" width="160">
						<template #default="{ row }">
							{{ formatDate(row.creationTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="firstTime" title="第一次上传省上的时间" width="170">
						<template #default="{ row }">
							{{ formatDate(row.firstTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
					<vxe-column field="lastTime" title="最近一次推送时间" width="170">
						<template #default="{ row }">
							{{ formatDate(row.lastTime, 'YYYY-mm-dd HH:MM:SS') }}
						</template>
					</vxe-column>
				</vxe-table>
			</div>
			<div class="flex-end" style="align-items: center">
				<el-text class="mr10" v-loading="totalLoading">共 {{ totalCount }} 条</el-text>
				<el-pagination
					layout="prev, pager, next"
					:total="state.total"
					@current-change="handleCurrentChange"
					:page-size="state.queryParams.PageSize"
					:current-page="state.queryParams.PageIndex"
					:disabled="totalLoading"
				/>
			</div>
		</div>
	</div>
</template>
<script setup lang="tsx" name="dataShareOrderNoCallLog">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import { defaultDateTime, defaultTimeStartEnd, shortcuts } from '@/utils/constants';
import { formatDate } from '@/utils/formatTime';
import { editNoCallSource, getNoCallListNewFixed, getNoCallListNewTotal } from '@/api/dataShare';
import Other from '@/utils/other';
import { getNeedArr } from '@/utils/tools';

const OrderDetail = defineAsyncComponent(() => import('@/components/OrderDetail/index.vue')); // 工单详情

// 定义变量内容
const ruleFormRef = ref<RefType>(); // 表单ref
const state = reactive<any>({
	queryParams: {
		PageIndex: 1,
		PageSize: 20,
		crTime: defaultDateTime,
		StartTime: null,
		EndTime: null,
		CaseSerial: null,
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
});
/** 搜索按钮操作 */
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 totalCount = ref(0);
const totalLoading = ref(false);
const queryList = (isQuery: boolean = false) => {
	state.loading = true;
	totalLoading.value = true;
	let request = Other.deepClone(state.queryParams);
	request.StartTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[0];
	request.EndTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[1];
	Reflect.deleteProperty(request, 'crTime');
	request.QueryIndex = queryIndex.value; // 数据批次
	getNoCallListNewFixed(request)
		.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;
		})
		.then(() => {
			// 查询总数
			getNoCallListNewTotal(request)
				.then((count) => {
					totalCount.value = count.result;
					totalLoading.value = false;
				})
				.catch(() => {
					totalLoading.value = false;
				});
		})
		.catch(() => {
			totalLoading.value = false;
			state.loading = false;
		});
};
/** 重置按钮操作 */
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList(true);
};
// 修改
const onEdit = (isPush: boolean) => {
	const title = isPush ? '修改并推送' : '修改来源渠道';
	const ids = checkTable.value.map((item: any) => item.provinceNo);
	ElMessageBox.confirm(`您确定要${title}选择中的工单，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			editNoCallSource({ ids, isPush }).then(() => {
				ElMessage.success('操作成功');
				queryList(true);
			});
		})
		.catch(() => {});
};
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();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
});
</script>
