<template>
	<div class="auxiliary-external-citizen-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<!-- 表格 -->
			<ProTable
				ref="proTableRef"
				:columns="columns"
				:data="state.tableData"
				@updateTable="queryList"
				:loading="state.loading"
				:total="state.total"
				v-model:page-index="state.queryParams.PageIndex"
				v-model:page-size="state.queryParams.PageSize"
			>
				<template #table-search>
					<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>
				</template>
				<template #tableHeader="scope">
					<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="!scope.isSelected" :loading="state.loading" v-auth="'auxiliary:externalCitizen:delete'"
					><SvgIcon name="ele-Delete" class="mr5" />删除
					</el-button>
				</template>
				<template #operation="{ row }">
					<el-button link type="primary" @click="onEdit(row)" title="编辑市民信息" v-auth="'auxiliary:externalCitizen:edit'"> 修改 </el-button>
				</template>
			</ProTable>
		</div>
		<!-- 编辑   -->
		<edit-info ref="editInfoRef" @updateList="queryList" />
	</div>
</template>

<script lang="tsx" setup name="auxiliaryExternalCitizen">
import { 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 proTableRef = ref<RefType>(); // 表格ref
// 表格配置项
const columns = ref<any[]>([
	{ type: 'selection', width: 40, align: 'center' },
	{ prop: 'name', label: '市民姓名' },
	{ prop: 'phoneNum', label: '联系电话' },
	{
		prop: 'creationTime',
		label: '创建时间',
		minWidth: 160,
		render: (scope: any) => {
			return formatDate(scope.row.creationTime, 'YYYY-mm-dd HH:MM:SS');
		},
	},
	{ prop: 'operation', label: '操作', fixed: 'right', minWidth: 90, align: 'center' },
]);
// 定义变量内容
const state = reactive({
	loading: false, // 加载状态
	queryParams: {
		// 查询参数
		PageIndex: 1,
		PageSize: 20,
		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;
		})
		.finally(() => {
			state.loading = false;
		});
};
// 重置表单
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 = proTableRef.value.selectedList.map((item: any) => item.id);
	ElMessageBox.confirm(`您确定删除选中的${ids.length}条数据，是否继续?`, '提示', {
		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);
};
// 页面加载时
onMounted(() => {
	queryList();
});
</script>
<style scoped lang="scss">
.upload-demo {
	display: inline-flex;
	vertical-align: middle;
	margin-right: 12px;
}
</style>