<template>
	<fs-page>
		<fs-crud ref="crudRef" v-bind="crudBinding"> 
			<template #actionbar-right>
				<el-button type="primary" style="margin-left: 12px;" @click="handleBatchImport">批量导入</el-button>
				<el-button type="primary" @click="handleDownloadTemplate">下载模板</el-button>
        <el-button type="primary" :loading="exportAllLoading" :disabled="exportAllLoading" @click="handleExportAll">全部导出</el-button>
				<el-button type="primary" @click="handleBatchExport">批量导出</el-button>
			</template>
         <template #form_organization_ref="scope"><!-- :show-all-levels="false" 1-->
            <template v-if="scope.form.user_type === 0">
              <div style="display:flex; gap:8px; width:100%">
                <el-select
                  style="flex:1"
                  :disabled="scope.mode=='view'"
                  v-model="scope.form._college_id"
                  placeholder="请选择学院"
                  filterable
                 
                  clearable
                  @change="() => onCollegeChange(scope)"
                >
                  <el-option v-for="item in colleges" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </div>
            </template>

            <template v-else-if="scope.form.user_type === 1 || scope.form.user_type === 3">
              <el-select
                :disabled="scope.mode=='view'"
                v-model="scope.form.organization_ref"
                placeholder="请选择学院"
                filterable
                
                clearable
              >
                <el-option
                  v-for="item in colleges"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </template>
            <template v-else>
              <el-select
                :disabled="scope.mode=='view'"
                v-model="scope.form.organization"
                placeholder="请选择学院"
                filterable
                allow-create
                default-first-option
                clearable
              >
                <el-option
                  v-for="item in colleges"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </template>
         </template>
          <template #form_sub_organization="scope" >
            <el-select
              style="flex:1"
              :disabled="scope.mode=='view' || !scope.form._college_id"
              v-model="scope.form._major_id"
              placeholder="请选择专业"
              filterable
              clearable
              @change="() => onMajorChange(scope)"
            >
              <el-option v-for="item in getMajors(scope.form._college_id)" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </template>
          <template #form_grade_or_level="scope">
            <el-select
                        style="flex:1"
                        :disabled="scope.mode=='view' || !scope.form._major_id"
                        v-model="scope.form._grade_id"
                        placeholder="请选择班级"
                        filterable
                        clearable
                        @change="() => onGradeChange(scope)"
                      >
                        <el-option v-for="item in getGrades(scope.form._major_id)" :key="item.id" :label="item.name" :value="item.id" />
                      </el-select>
          </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="allusers">
import { useFs } from '@fast-crud/fast-crud';
import { onMounted,ref, computed } from 'vue';
import { GetPermission } from './api';
import { GetTree } from '../studentInfo/api';
import { createCrudOptions } from './crud';
import { handleColumnPermission } from '/@/utils/columnPermission';
import {request, downloadFile,downloadFilePost } from '/@/utils/service';
import Cookies from 'js-cookie';
import { ElMessage } from 'element-plus';

const importDialogVisible = ref(false); 
const fileList = ref<File[]>([]);
const options=ref<any[]>([])
const importLoading = ref(false);
const exportAllLoading = ref(false);
const colleges = computed(() => {
  const list = Array.isArray(options.value) ? options.value : []
  const firstLevel: any[] = []
  list.forEach((node: any) => {
    if (Array.isArray(node?.children)) firstLevel.push(...node.children)
  })
  return firstLevel.map((node: any) => ({ id: node.id, name: node.name }))
})
const props1 = {
  checkStrictly: true,
  label: 'name',
  value: 'id',
  children: 'children',
  emitPath: false // 只返回选中节点的值，不返回完整路径
}

function findNodeById(id: any) {
  if (!id) return undefined
  const stack: any[] = [...(options.value || [])]
  while (stack.length) {
    const node = stack.shift()
    if (node?.id === id) return node
    if (Array.isArray(node?.children) && node.children.length) stack.push(...node.children)
  }
  return undefined
}

function getMajors(collegeId: any) {
  const college = findNodeById(collegeId)
  return Array.isArray(college?.children) ? college.children : []
}

function getGrades(majorId: any) {
  const major = findNodeById(majorId)
  return Array.isArray(major?.children) ? major.children : []
}

function onCollegeChange(scope: any) {
  scope.form._major_id = undefined
  scope.form._grade_id = undefined
  if (scope.form.user_type === 0) {
    scope.form.organization_ref = undefined
  } else {
    scope.form.organization_ref = scope.form._college_id
  }
}

function onMajorChange(scope: any) {
  scope.form._grade_id = undefined
  if (scope.form.user_type === 0) {
    scope.form.organization_ref = undefined
  }
}

function onGradeChange(scope: any) {
  if (scope.form.user_type === 0) {
    scope.form.organization_ref = scope.form._grade_id
  }
}


const init=()=>{
	GetTree().then((res:any) => { 
			console.log('组织架构API响应:', res);
		// 兼容多种响应格式
		if(res && (res.code === 200 || res.code === 2000 || !res.code)){
			// 尝试多种数据结构
			const data = res.data || res.results || res;
			if (Array.isArray(data)) {
				options.value = data;
				console.log('成功赋值组织架构数据:', options.value);
			} else {
				console.warn('返回的数据不是数组格式:', data);
				options.value = [];
			}
		} else {
			console.error('获取组织架构数据失败:', res);
			options.value = [];
		}
	}).catch((error: any) => {
		console.error('请求组织架构数据失败:', error);
		options.value = [];
	});
}

const { crudBinding, crudRef, crudExpose, crudOptions, resetCrudOptions, selectedRows } = 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 {
    importLoading.value = true;
	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);
  } finally {
    importLoading.value = false;
  }
};


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

const handleBatchExport = () => {
	const selectedRows = (crudExpose as any).selectedIds?.value || [];	
	console.log("selectedRows::",selectedRows)
	if (selectedRows.length === 0) {
		ElMessage.warning('请先选择要导出的用户')
		return
	}
	downloadFilePost({
	url: '/api/system/app_user/export_selected/',
	method: 'post',
	data: {
		user_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/app_user/',
				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/app_user/export_selected/',
			method: 'post',
			data: { user_ids: allIds },
			filename: '用户导出-全部',
			timeout: 0
		});
	} catch (error) {
		ElMessage.error('全部导出失败');
		console.error(error);
	} finally {
		exportAllLoading.value = false;
	}
}

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

defineExpose({
  getMajors,
  getGrades,
  onCollegeChange,
  onMajorChange,
  onGradeChange,
  colleges,
})
</script>
