<template>
	<fs-page>
		<fs-crud ref="crudRef" v-bind="crudBinding"> 
			<template #actionbar-right>
				<el-button type="primary" @click="handleBatchImport">批量导入</el-button>
				<el-button type="primary"  @click="handleDownloadTemplate">下载模板</el-button>
			</template>

		</fs-crud>

		<el-dialog v-model="importDialogVisible" title="批量导入设备" width="30%">
		<el-upload
			ref="uploadRef"
			:auto-upload="false"
			:file-list="fileList"
			:limit="1"
			:on-change="handleFileChange"
			:before-upload="() => false"
			accept=".xls,.xlsx"
		>
			<el-button type="primary">选择文件</el-button>
		</el-upload>
		<template #footer>
			<el-button @click="importDialogVisible = false">取消</el-button>
			<el-button type="primary" @click="submitImport">确认导入</el-button>
		</template>
		</el-dialog>

	</fs-page>
</template>

<script lang="ts" setup name="allusers">
import { useFs } from '@fast-crud/fast-crud';
import { onMounted,ref } from 'vue';
import { GetPermission } from './api';
import { createCrudOptions } from './crud';
import { handleColumnPermission } from '/@/utils/columnPermission';
import { downloadFile } from '/@/utils/service';
import { request } from '/@/utils/service';
import Cookies from 'js-cookie';
import { ElMessage } from 'element-plus';

const importDialogVisible = ref(false); 
const fileList = ref<File[]>([]);

const { crudBinding, crudRef, crudExpose, crudOptions, resetCrudOptions } = useFs({ createCrudOptions });

const handleBatchImport = () => {
	importDialogVisible.value = true;
}


const handleFileChange = (file: any) => {
	fileList.value = [file.raw];
};

const submitImport = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请先选择文件');
    return;
  }

  const rawFile = fileList.value[0]; 
  if (!rawFile) {
    ElMessage.error('文件无效，请重新选择');
    return;
  }


  const formData = new FormData();
  formData.append('file', rawFile);
  const token = Cookies.get('token'); 
  try {
	await request({
		url: '/api/system/app_user/batch_import/',
		method: 'post',
		data: formData,
		headers: {
			'Content-Type': 'multipart/form-data',
			"Authorization": token ? `JWT ${token}` : ''
		}
	}).then((res: any) => {
		console.log("导入resssss:::",res)
		ElMessage.success('导入成功');
		importDialogVisible.value = false;
		fileList.value = [];
		crudExpose.doRefresh(); 
	})
  } catch (error) {
    ElMessage.error('导入失败，请检查文件格式或内容');
    console.error(error);
  }
};


const handleDownloadTemplate = () => {
	downloadFile({
		url: '/api/system/app_user/download_template/',
		method: 'get',
		filename: '用户导入模板'
		})
}


// 页面打开后获取列表数据
onMounted(async () => {
	// 设置列权限
	const newOptions = await handleColumnPermission(GetPermission, crudOptions);
	//重置crudBinding
	resetCrudOptions(newOptions);
	// 刷新
	crudExpose.doRefresh();
});
</script>
