<template>
	<div class="snapshot-statistics-detail-point-list-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<vxe-grid v-bind="gridOptions" v-on="gridEvents" ref="gridRef" @checkbox-all="selectAllChangeEvent" @checkbox-change="selectChangeEvent">
				<template #form>
					<el-form :model="state.queryParams" ref="ruleFormRef" @submit.native.prevent inline :disabled="state.loading">
						<el-form-item 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 label="联系方式" prop="PhoneNumber">
							<el-input
								v-model.trim="state.queryParams.PhoneNumber"
								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-button @click="resetQuery(ruleFormRef)" class="default-button" :loading="state.loading">
								<SvgIcon name="ele-Refresh" class="mr5" />重置
							</el-button>
						</el-form-item>
					</el-form>
				</template>
				<template #action="{ row }">
					<el-button link type="primary" @click="onSafe(row, false)" v-if="row.isSecurityMax" v-auth="'snapshot:statistics:pointList:security'">
						取消安全卫士
					</el-button>
					<el-button link type="primary" @click="onSafe(row, true)" v-else v-auth="'snapshot:statistics:pointList:security'">
						设置安全卫士
					</el-button>
				</template>
				<template #pager>
					<pagination
						@pagination="queryList"
						:total="state.total"
						v-model:current-page="state.queryParams.PageIndex"
						v-model:page-size="state.queryParams.PageSize"
						:disabled="state.loading"
					/>
				</template>
			</vxe-grid>
		</div>
		<!--	更多查询	-->
		<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="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 state.acceptTypeOptions" :value="item.key" :key="item.key" :label="item.value" />
					</el-select>
				</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="ActualHandlerName">
					<el-input v-model="state.queryParams.ActualHandlerName" placeholder="接办人" clearable @keyup.enter="handleQuery" />
				</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="PhoneNo">
					<el-input v-model.trim="state.queryParams.PhoneNo" placeholder="联系电话" clearable @keyup.enter="handleQuery" />
				</el-form-item>
				<el-form-item label="来电人姓名" prop="FromName">
					<el-input v-model="state.queryParams.FromName" placeholder="来电人姓名" clearable @keyup.enter="handleQuery" />
				</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="snapshotStatisticsDetailPointList">
import { defineAsyncComponent, onMounted, reactive, ref, computed } from 'vue';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import Other from '@/utils/other';
import { getSSPStatisticsIntegral, getSSPStatisticsIntegralExport, setSecurityGuard } from '@/api/snapshot/statistics';
import { defaultDate } from '@/utils/constants';
import { useRoute } from 'vue-router';
import { defaultTimeStartEnd, shortcuts } from '@/utils/constants';

// 引入组件
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
// 定义变量内容
const state = reactive<any>({
	queryParams: {
		PageIndex: 1, // 当前页
		PageSize: 20, // 每页条数
		// 查询条件
		PhoneNumber: null, // 联系方式
		SortField: null,
		SortRule: null,
		crTime: defaultDate,
		StartTime: null,
		EndTime: null,
	},
	tableData: [], //表单
	loading: false, // 加载
	total: 0, // 总数
	acceptTypeOptions: [], //受理类型
	channelOptions: [], // 来源频道
	orderStatusOptions: [], // 工单状态
	currentStepOptions: [], // 办理节点
	industryOptions: [], //行业
	orgsOptions: [], // 部门
	pushTypeOptions: [], //推送分类
	orgData: [], // 机构数据
	areaOptions: [], // 省市区数据
	area: [], // 区域
	industry: [], // 行业
	orderStatus: [], // 工单状态
	orderTags: [], // 工单标签
	steps: [], // 当前节点
});
const requestParams = ref<EmptyObjectType>({});
const gridOptions = reactive<any>({
	loading: false,
	border: true,
	showOverflow: true,
	columnConfig: {
		resizable: true,
	},
	scrollY: {
		enabled: true,
		gt: 100,
	},
	toolbarConfig: {
		zoom: true,
		custom: true,
		refresh: {
			queryMethod: () => {
				handleQuery();
			},
		},
		tools: [{ toolRender: { name: 'exportCurrent' } }, { toolRender: { name: 'exportAll' } }],
	},
	params: {
		exportMethod: getSSPStatisticsIntegralExport,
		exportParams: requestParams,
	},
	customConfig: {
		storage: true,
	},
	id: 'snapshotStatisticsDetailPointList',
	rowConfig: { isHover: true, height: 30, isCurrent: true, useKey: true },
	height: 'auto',
	columns: [
		{ type: 'checkbox', width: 50, align: 'center' },
		{ field: 'phoneNumber', title: '联系方式' },
		{ field: 'userName', title: '姓名' },
		{ field: 'totalPoints', title: '历史总积分' },
		{ field: 'outPoints', title: '已兑换积分' },
		{ field: 'validPoints', title: '当前可用积分' },
		{ field: 'rank', title: '当前排名', sortable: true },
		{ title: '操作', width: 130, fixed: 'right', align: 'center', slots: { default: 'action' } },
	],
	data: [],
	sortConfig: {
		remote: true,
	},
});
const gridEvents = {
	sortChange(val: any) {
		state.queryParams.SortField = val.order ? val.field : null;
		// 0 升序 1 降序
		state.queryParams.SortRule = val.order ? (val.order == 'desc' ? 1 : 0) : null;
		handleQuery();
	},
};
// 手动查询，将页码设置为1
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 改变页码
const route = useRoute();
const routeQueryParams = route.query;
const queryList = () => {
	return new Promise((resolve, reject) => {
		requestParams.value = Other.deepClone(state.queryParams);
		requestParams.value.StartTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[0]; // 受理时间
		requestParams.value.EndTime = state.queryParams.crTime === null ? null : state.queryParams.crTime[1];
		Reflect.deleteProperty(requestParams.value, 'crTime'); // 删除无用的参数
		requestParams.value.County = routeQueryParams.County; // 区域
		state.loading = true;
		gridOptions.loading = true;
		getSSPStatisticsIntegral(requestParams.value)
			.then((response: any) => {
				gridOptions.data = response?.result.items ?? [];
				state.total = response?.result.total;
				state.loading = false;
				gridOptions.loading = false;
				gridRef.value.clearCheckboxRow();
				checkTable.value = [];
				resolve(response);
			})
			.catch(() => {
				state.loading = false;
				gridOptions.loading = false;
				gridRef.value.clearCheckboxRow();
				checkTable.value = [];
				reject();
			});
	});
};
/** 重置按钮操作 */
const drawerRuleFormRef = ref();
const ruleFormRef = ref<RefType>(); // 表单ref
const drawer = ref(false);
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	ruleFormRef.value?.resetFields();
	queryList();
};
const checkTable = ref<EmptyArrayType>([]);
const gridRef = ref<RefType>();
const selectAllChangeEvent = ({ checked }) => {
	if (gridRef.value) {
		const records = gridRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '所有勾选事件' : '所有取消事件', records);
	}
};

const selectChangeEvent = ({ checked }) => {
	if (gridRef.value) {
		const records = gridRef.value.getCheckboxRecords();
		checkTable.value = records;
		console.log(checked ? '勾选事件' : '取消事件', records);
	}
};
const isChecked = computed(() => {
	return !checkTable.value.length;
});
// 设置安全卫士
const onSafe = (row: any, isSecurityMax: boolean) => {
	if (isSecurityMax) {
		// 设置安全卫士
		ElMessageBox.confirm(`您确定要设置安全卫士, 是否继续?`, '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
			draggable: true,
		})
			.then(() => {
				setSecurityGuard({ userId: row.userId, isSecurityMax }).then(() => {
					ElMessage.success('设置成功');
					queryList();
				});
			})
			.catch(() => {});
	} else {
		// 取消安全卫士
		ElMessageBox.confirm(`您确定要取消设置安全卫士, 是否继续?`, '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
			draggable: true,
		})
			.then(() => {
				setSecurityGuard({ userId: row.userId, isSecurityMax }).then(() => {
					ElMessage.success('取消设置成功');
					queryList();
				});
			})
			.catch(() => {});
	}
};
onMounted(() => {
	if (routeQueryParams.StartTime) {
		state.queryParams.crTime = [routeQueryParams.StartTime, routeQueryParams.EndTime];
	} else {
		state.queryParams.crTime = defaultDate;
	}
	queryList();
});
</script>
