<template>
	<el-dialog v-model="state.dialogVisible" draggable title="新增安全志愿者" destroy-on-close append-to-body @close="close">
		<el-form :model="state.ruleForm" label-width="100px" ref="ruleFormRef">
			<el-form-item label="志愿者类型" prop="safetyTypeId" :rules="[{ required: true, message: '请选择志愿者类型', trigger: 'change' }]">
				<el-select v-model="state.ruleForm.safetyTypeId" class="w100" placeholder="请选择志愿者类型" @change="queryList" clearable>
					<el-option v-for="item in statusOptions" :key="item.id" :label="item.name" :value="item.id" />
				</el-select>
			</el-form-item>
			<el-form-item label="关联人员" prop="citizenIds" :rules="[{ required: false, message: '请选择关联人员', trigger: 'change' }]">
				<template #label>
					<p class="flex-center-align">
						关联人员
						<el-tooltip content="请先选择志愿者类型,再查询关联人员列表" placement="top-start" trigger="hover">
							<SvgIcon name="ele-QuestionFilled" class="ml3"></SvgIcon>
						</el-tooltip>
					</p>
				</template>
				<vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents" class="w100">
					<template #form>
						<el-row class="mb20" :gutter="20">
							<el-col :span="24" :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
								<el-input v-model="state.queryParams.PhoneNumber" placeholder="请填写电话号码" clearable @keyup.enter="handleQuery" />
							</el-col>
							<el-col :span="24" :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
								<el-button type="primary" @click="handleQuery" :loading="gridOptions.loading">
									<SvgIcon name="ele-Search" class="mr5" />查询
								</el-button>
							</el-col>
						</el-row>
					</template>
					<template #pager>
						<pagination
							@pagination="queryList"
							:total="state.total"
							v-model:current-page="state.queryParams.PageIndex"
							v-model:page-size="state.queryParams.PageSize"
							:disabled="gridOptions.loading"
						/>
					</template>
				</vxe-grid>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="gridOptions.loading" :disabled="isChecked">确 定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, defineAsyncComponent, computed } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { throttle } from '@/utils/tools';
import { addSafetyVolunteer, baseSafetyVolunteer, searchSafetyVolunteer } from '@/api/snapshot/config';
// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	queryParams: {
		// 查询参数
		PageIndex: 1,
		PageSize: 20,
	},
	total: 0, // 总条数
	ruleForm: {
		safetyTypeId: null, // 志愿者类型
		citizenIds: [], // 关联人员
	},
});
// 查询基础数据
const statusOptions = ref<EmptyArrayType>([]);
const getStatusOptions = () => {
	// 获取基础数据
	baseSafetyVolunteer().then((res) => {
		statusOptions.value = res.result.safetyTypes ?? [];
	});
};
// 打开弹窗
const ruleFormRef = ref<RefType>();
const openDialog = () => {
	getStatusOptions();
	state.dialogVisible = true;
};
/** 搜索按钮操作 节流操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 获取参数列表
const queryList = () => {
	if (!state.ruleForm.safetyTypeId) { // 没有选择志愿者类型
		gridOptions.data = [];
		state.total = 0;
		state.ruleForm.citizenIds = [];
		gridRef.value.clearCheckboxRow();
		return;
	}
	gridOptions.loading = true;
	// 发送请求获取数据
	searchSafetyVolunteer({ ...state.queryParams, safetyTypeId: state.ruleForm.safetyTypeId })
		.then((res) => {
			gridOptions.data = res.result.items ?? [];
			state.total = res.result.total ?? 0;
			gridOptions.loading = false;
		})
		.catch(() => {
			gridOptions.loading = false;
		});
};
const gridRef = ref<RefType>();
// 选中事件
const isChecked = computed(() => {
	if (!gridRef.value) return true;
	const selectRecords = gridRef.value.getCheckboxRecords();
	const selectReserveRecords = gridRef.value.getCheckboxReserveRecords();
	return !Boolean(selectRecords.length + selectReserveRecords.length);
});
const gridOptions = reactive<any>({
	showOverflow: true,
	border: true,
	loading: false,
	maxHeight: 400,
	checkboxConfig: {
		reserve: true,
		showReserveStatus: true,
	},
	columns: [
		{ type: 'checkbox', width: 60 },
		{ field: 'name', title: '姓名' },
		{ field: 'phoneNumber', title: '电话号码' },
	],
	data: [],
	rowConfig: { isHover: true, height: 30, isCurrent: true, useKey: true, keyField: 'citizenId' },
});

const gridEvents: any = {};

// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.resetFields();
	ruleFormRef.value?.resetFields();
	state.queryParams.PhoneNumber = null;
};
// 新增
const onSubmit = throttle(async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		const $grid = gridRef.value;
		const selectRecords = $grid.getCheckboxRecords();
		const selectReserveRecords = $grid.getCheckboxReserveRecords();
		if (selectRecords.length === 0 && selectReserveRecords.length === 0) {
			ElMessage({
				message: '请至少选择一条数据',
				type: 'warning',
			});
			return;
		}
		const selectAllRecords = [...selectRecords, ...selectReserveRecords];
		const citizenIds = selectAllRecords.map((item: any) => item.citizenId);
		gridOptions.loading = true;
		state.ruleForm.citizenIds = citizenIds;
		addSafetyVolunteer(state.ruleForm)
			.then(() => {
				ElMessage({
					message: '新增成功',
					type: 'success',
				});
				emit('updateList');
			})
			.catch(() => {})
			.finally(() => {
				gridOptions.loading = false;
				closeDialog();
			});
	});
}, 300);
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
