<template>
	<div class="auxiliary-external-citizen-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent>
				<el-form-item label="市民姓名" prop="Name">
					<el-input v-model="state.queryParams.Name" placeholder="请填写市民姓名" clearable @keyup.enter="handleQuery" class="keyword-input" />
				</el-form-item>
				<el-form-item label="联系电话" prop="PhoneNum">
					<el-input
						v-model="state.queryParams.PhoneNum"
						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="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-upload
						v-model:file-list="fileList"
						action="#"
						:multiple="false"
						ref="uploadListRef"
						name="file"
						:http-request="onImport"
						:show-file-list="false"
						class="upload-demo"
						:disabled="state.loading"
					>
						<el-button type="primary" v-auth="'auxiliary:externalCitizen:import'" :loading="state.loading"> <SvgIcon name="ele-Upload" class="mr5" /> 导入市民 </el-button>
					</el-upload>
					<el-button type="primary" @click="onDownload" v-auth="'auxiliary:externalCitizen:download'" :loading="state.loading">
						<SvgIcon name="ele-Download" class="mr5" /> 模板下载
					</el-button>
					<el-button type="danger" @click="onDelete" :disabled="isChecked" :loading="state.loading" v-auth="'auxiliary:externalCitizen:delete'"
					><SvgIcon name="ele-Delete" 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,useKey: true }"
					ref="tableRef"
					@checkbox-all="selectAllChangeEvent"
					@checkbox-change="selectChangeEvent"
					height="auto"
					auto-resize
					show-overflow
					:scrollY="{ enabled: true, gt: 100 }"
					id="auxiliaryExternalCitizen"
					:custom-config="{ storage: true }"
					showHeaderOverflow
				>
					<vxe-column type="checkbox" width="50" align="center"></vxe-column>
					<vxe-column field="name" title="市民姓名" ></vxe-column>
					<vxe-column field="phoneNum" title="联系电话"></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 title="操作" fixed="right" width="90" align="center">
						<template #default="{ row }">
							<el-button link type="primary" @click="onEdit(row)" title="编辑市民信息" v-auth="'auxiliary:externalCitizen:edit'"> 修改 </el-button>
						</template>
					</vxe-column>
				</vxe-table>
			</div>
			<pagination
				@pagination="queryList"
				:total="state.total"
				v-model:current-page="state.queryParams.PageIndex"
				v-model:page-size="state.queryParams.PageSize"
				:disabled="state.loading"
			/>
		</div>
		<!-- 编辑   -->
		<edit-info ref="editInfoRef" @updateList="queryList" />
	</div>
</template>

<script lang="tsx" setup name="auxiliaryExternalCitizen">
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, ElNotification, FormInstance } from 'element-plus';
import { externalCitizenDelete, externalCitizenImport, externalCitizenList, externalCitizenTemplate } from '@/api/auxiliary/externalCitizen';
import { downloadFileByStream } from '@/utils/tools';
import { formatDate } from '@/utils/formatTime';

// 引入组件
const EditInfo = defineAsyncComponent(() => import('@/views/auxiliary/externalCitizen/components/Edit.vue')); // 标签编辑
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

// 定义变量内容
const state = reactive({
	loading: false, // 加载状态
	queryParams: {
		// 查询参数
		PageIndex: 1,
		PageSize: 2,
		PhoneNum: null,
		Name: null,
	},
	total: 0, // 总条数
	tableData: [], // 表格数据
});
const ruleFormRef = ref<RefType>(null); // 表单ref
/** 搜索按钮操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 获取列表
const queryList = () => {
	state.loading = true;
	externalCitizenList(state.queryParams)
		.then((res) => {
			state.loading = false;
			state.tableData = res.result.items ?? [];
			state.total = res.result.total ?? 0;
			tableRef.value.clearCheckboxRow();
			checkTable.value = [];
		})
		.finally(() => {
			state.loading = false;
			tableRef.value.clearCheckboxRow();
			checkTable.value = [];
		});
};
// 重置表单
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	queryList();
};
// 导入
const fileList = ref<EmptyArrayType>([]);
const uploadListRef = ref<RefType>(); // 上传组件ref
const onImport = async (file: any) => {
	state.loading = true;
	let fileObj = file.file; // 相当于input里取得的files
	let fd = new FormData(); // FormData 对象
	fd.append('file', fileObj); // 文件对象
	try {
		const { result } = await externalCitizenImport(fd);
		ElNotification({
			title: '导入完成',
			message: `总条数：${result.count}条，新增：${result.addCount}条，失败：${result.errorCount}条`,
			type: 'success',
		})
		queryList();
		state.loading = false;
	} catch (e) {
		console.log(e);
		state.loading = false;
	}
};
// 模板下载
const onDownload = () => {
	ElMessageBox.confirm(`您确定下载外部市民导入模板，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			externalCitizenTemplate()
				.then((res: any) => {
					state.loading = false;
					downloadFileByStream(res);
				})
				.catch(() => {
					state.loading = false;
				});
		})
		.catch(() => {});
};
// 删除
const onDelete = () => {
	const ids = checkTable.value.map((item: any) => item.id);
	ElMessageBox.confirm(`您确定删除选中的外部市民，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
		draggable: true,
		cancelButtonClass: 'default-button',
		autofocus: false,
	})
		.then(() => {
			state.loading = true;
			externalCitizenDelete(ids).then(()=>{
				ElMessage.success('删除成功');
				queryList();
			}).catch(()=>{
				state.loading = false;
			})
		}).catch(() => {
		state.loading = false;
	});
}
// 修改
const editInfoRef = ref<RefType>();
const onEdit = (row: any) => {
	editInfoRef.value.openDialog(row);
};
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>
<style scoped lang="scss">
.upload-demo {
	display: inline-flex;
	vertical-align: middle;
	margin-right: 12px;
}
</style>