<template>
	<fs-page>
		<fs-crud ref="crudRef" v-bind="crudBinding"> 
			<template #actionbar-right>
				<el-button type="primary" @click="handleBatchImport" class="batch-imports">批量导入</el-button>
				<el-button type="primary" @click="handleExports" >批量导出</el-button>
				<el-button type="primary"  @click="handleDownloadTemplate">下载模板</el-button>
				<el-button type="danger" @click="handleBatchDelete" >批量删除</el-button>
			</template>
			<!-- <template #pagination-left>
			<el-tooltip content="批量删除">
			<fs-button  @click="handleBatchDelete">批量删除</fs-button>
			</el-tooltip> 
			</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="device">
import { onMounted ,ref} from 'vue';
import { useFs} from '@fast-crud/fast-crud';
import { createCrudOptions } from './crud';
import * as api from './api';
// import { GetPermission } from './api';
// import { handleColumnPermission } from '/@/utils/columnPermission';
import { ElMessage } from 'element-plus';
import axios from 'axios'
import Cookies from 'js-cookie';
import {request, downloadFile,downloadFilePost } from '/@/utils/service';


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


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



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/device/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(res.msg);
		importDialogVisible.value = false;
		fileList.value = [];
		crudExpose.doRefresh(); 
	})
  } catch (error) {
    ElMessage.error('导入失败，请检查文件格式或内容');
    console.error(error);
  }
};


const handleExports = async () => {
	const selectedRows = (crudExpose as any).selectedIds?.value || [];	
	console.log("selectedRows::",selectedRows)
	if (selectedRows.length === 0) {
		ElMessage.warning('请先选择要导出的设备')
		return
	}
	downloadFilePost({
	url: '/api/system/device/export_selected/',
	method: 'post',
	data: {
		device_ids: selectedRows
	},
	filename: '设备导出'
	})

}


const handleDownloadTemplate =async () =>{
	downloadFile({
		url: '/api/system/device/download_template/',
		method: 'get',
		filename: '设备模板'
		})

}


const handleBatchDelete= async () => {
	const selectedRows = (crudExpose as any).selectedIds?.value || [];	
	console.log("selectedRows::",selectedRows)
	if (selectedRows.length === 0) {
		ElMessage.warning('请先选择要删除的设备')
		return
	}
	await request({
		url: '/api/system/device/multiple_delete/',
		method: 'delete',
		data: {
			keys: selectedRows
		},
	}).then((res: any) => {
		ElMessage.success('删除成功');
		crudExpose.doRefresh(); 
	})

}

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

</style>
