<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="handleExportAll" :loading="exportAllLoading">全部导出</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" :loading="importLoading" :disabled="importLoading" @click="submitImport">确认导入</el-button>
		</template>
		</el-dialog>

	</fs-page>
</template>
<script lang="ts" setup name="device">
import { onMounted ,ref, defineExpose} 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, ElLoading } 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 importLoading = ref(false);
const fileList = ref<File[]>([]);

const exportAllLoading = ref(false);
defineExpose({ importLoading, exportAllLoading });



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

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

const submitImport = async () => {
  if (importLoading.value) return;
  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 {
    importLoading.value = true;
    const res: any = await request({
      url: '/api/system/device/batch_import/',
      method: 'post',
      data: formData,
      headers: {
        'Content-Type': 'multipart/form-data',
        "Authorization": token ? `JWT ${token}` : ''
      }
    });
    console.log("导入resssss:::", res)
    ElMessage.success(res.msg);
    importDialogVisible.value = false;
    fileList.value = [];
    crudExpose.doRefresh();
  } catch (error) {
    ElMessage.error('导入失败，请检查文件格式或内容');
    console.error(error);
  } finally {
    importLoading.value = false;
  }
};


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 handleExportAll = async () => {
	exportAllLoading.value = true;
	try {
		const query = (crudExpose as any)?.getSearchFormData ? (crudExpose as any).getSearchFormData() : {};
		const pageSize = (crudExpose as any)?.crudBinding?.value?.pagination?.pageSize || 50;
		let page = 1;
		const allIds: number[] = [];
		while (true) {
			const res: any = await request({
				url: '/api/system/device/',
				method: 'get',
				params: { ...query, page, limit: pageSize },
				timeout: 0
			});
			const list: any[] = Array.isArray(res?.data) ? res.data : (Array.isArray(res?.results) ? res.results : []);
			if (!Array.isArray(list) || list.length === 0) break;
			for (const item of list) {
				if (item?.id != null) allIds.push(item.id);
			}
			const total = res?.total ?? res?.count ?? undefined;
			if (total !== undefined) {
				if (allIds.length >= Number(total)) break;
			}
			if (list.length < pageSize) break;
			page += 1;
		}
		if (allIds.length === 0) {
			ElMessage.warning('当前筛选结果为空，无法导出');
			return;
		}
		await downloadFilePost({
			url: '/api/system/device/export_selected/',
			method: 'post',
			data: { device_ids: allIds },
			filename: '设备导出',
			timeout: 0
		});
	} finally {
		exportAllLoading.value = false;
	}
}


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>
