<template>
	<div class="plan-index-container layout-padding">
		<div class="layout-padding-auto layout-padding-view pd20">
			<el-form :model="state.queryParams" ref="ruleFormRef" inline @submit.native.prevent :disabled="state.tableLoading">
                <el-form-item label="标签" prop="tagIds">
                    <el-tree-select
                        v-model="state.queryParams.tagIds"
                        :data="state.tagData"
                        node-key="id"
                        :props="{ label: 'name' }"
                        multiple
                        collapse-tags
                        collapse-tags-tooltip
                        :render-after-expand="false"
                        style="width: 240px"
                        @change="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="难易程度" prop="difficultyLevel">
                    <el-select v-model="state.queryParams.difficultyLevel" clearable placeholder="请选择" @change="handleQuery" :disabled="state.tableLoading">
                        <el-option key='0' label="容易" :value="0" />
                        <el-option key='1' label="适中" :value="1" />
                        <el-option key='2' label="困难" :value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="题干" prop="title">
                    <el-input v-model="state.queryParams.title" placeholder="题干" clearable @keyup.enter="handleQuery" class="keyword-input" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery" :loading="state.tableLoading"> <SvgIcon name="ele-Search" class="mr5" />查询 </el-button>
                    <el-button @click="resetQuery(ruleFormRef)" class="default-button"> <SvgIcon name="ele-Refresh" class="mr5" />重置</el-button>
                </el-form-item>
            </el-form>
            <vxe-toolbar
                ref="toolbarRef"
                :loading="state.tableLoading"
                custom
                :refresh="{
                    queryMethod: handleQuery,
                }"
            >
                <template #buttons>
                    <el-button type="primary" @click="onAdd" v-auth="'question:index:add'" :loading="state.tableLoading">
                        <SvgIcon name="ele-Plus" class="mr10" />新增
                    </el-button>
                    <el-upload
                        v-model:file-list="fileList"
                        action="#"
                        :multiple="false"
                        ref="uploadListRef"
                        name="file"
                        :http-request="onUpload"
                        :show-file-list="false"
                        class="ml10 mr10"
                        :disabled="state.loading"
                    >
                        <el-button type="primary" plain :loading="state.loading" v-auth="'question:index:upload'"> <SvgIcon name="ele-Upload" class="mr5" /> 试题导入 </el-button>
                    </el-upload>
                    <el-button type="primary" plain @click="onDownload" v-auth="'question:index:download'" :loading="state.loading">
                        <SvgIcon name="ele-Download" class="mr5" />模板下载
                    </el-button>
                </template>
            </vxe-toolbar>
            <div style="overflow: hidden; width: 100%; height: 100%; flex: 1">
                <vxe-table
                    border
                    :loading="state.tableLoading"
                    :data="state.tableData"
                    :column-config="{ resizable: true }"
                    :row-config="{ isCurrent: true, isHover: true, height: 30, useKey: true }"
                    ref="tableRef"
                    height="auto"
                    auto-resize
                    show-overflow
                    :print-config="{}"
                    :scrollY="{ enabled: true, gt: 100 }"
                    id="examTrainQuestionBank"
                    :custom-config="{ storage: true }"
                    showHeaderOverflow
                >
                    <vxe-column field="questionTypeDesc" title="题型" width="100"></vxe-column>
                    <vxe-column field="tag" title="标签" width="150"></vxe-column>
                    <vxe-column field="difficultyLevelDesc" title="难度" width="100"></vxe-column>
                    <vxe-column field="title" title="题干" min-width="200"></vxe-column>
                    <!-- <vxe-column field="status" title="状态" width="160">
                        <template #default="{ row }">
                            <el-switch v-model="row.status" />
                        </template>
                    </vxe-column> -->
                    <vxe-column field="formalEnableDes" title="正式可用" width="150"></vxe-column>
                    <vxe-column field="simulateEnableDes" title="模拟可用" width="150"></vxe-column>
                    <vxe-column title="操作" fixed="right" width="120" align="center" :show-overflow="false">
                        <template #default="{ row }">
                            <el-button link type="primary" @click="onEdit(row)" title="编辑" v-auth="'question:index:edit'">
                                编辑
                            </el-button>
                            <el-button link type="danger" @click="onRowDel(row)" title="删除" v-auth="'question:index:delete'">
                                删除
                            </el-button>
                        </template>
                    </vxe-column>
                </vxe-table>
            </div>
            <pagination
                @pagination="queryList"
                :total="state.total"
                v-model:current-page="state.queryParams.PageIndex"
                v-model:page-size="state.queryParams.PageSize"
                :disabled="state.tableLoading"
            />
		</div>
	</div>
</template>

<script lang="tsx" setup name="examTrainQuestionBank">
import { ref, reactive, onMounted, defineAsyncComponent, computed } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import type { FormInstance } from 'element-plus';
import { formatDate } from '@/utils/formatTime';
import 'splitpanes/dist/splitpanes.css';
import Other from '@/utils/other';
import { downloadFileByStream } from '@/utils/tools';
import {deleteQuestion, getQuestionData, questionImport, questionTemplate} from '@/api/examTrain/questionBank';
import { examTagTreeList} from '@/api/examTrain/tag';

// 引入组件
const pagination = defineAsyncComponent(() => import('@/components/ProTable/components/Pagination.vue')); // 分页

const router = useRouter(); //路由

// 定义变量内容
const state = reactive<any>({
	queryParams: {
		PageIndex: 1, //页码
		PageSize: 20, //每页条数
        tagIds: null, // 标签id集合
        difficultyLevel: null, // 难易程度
		title: null, //题干
	},
	tagLoading: false, // 标签loading
	tagData: [], // 标签数据
	tableData: [], //表格数据
	total: 0, //总条数
    loading: false, // 下载上传loading
	tableLoading: false, //表格loading
});
/** 搜索按钮操作 节流操作 */
const handleQuery = () => {
	state.queryParams.PageIndex = 1;
	queryList();
};
// 获取标签数据
const getTagData = async () => {
	state.tagLoading = true;
	try {
		const { result } = await examTagTreeList();
		state.tagData = result ?? [];
		state.tagLoading = false;
	} catch (error) {
		state.tagLoading = false;
	}
};
/** 获取试题列表 */
const requestParams = ref<EmptyObjectType>({});
const queryList = () => {
	state.tableLoading = true;
    requestParams.value = Other.deepClone(state.queryParams);
	getQuestionData(requestParams.value)
		.then((response: any) => {
			state.tableData = response?.result.items ?? [];
			state.total = response?.result.pagination.totalCount ?? 0;
			state.tableLoading = false;
		})
		.catch(() => {
			state.tableLoading = false;
		});
};
/** 重置按钮操作 */
const ruleFormRef = ref<RefType>(); // 表单ref
const resetQuery = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	ruleFormRef.value?.resetFields();
	handleQuery();
};
// 新增
const onAdd = () => {
	router.push({
		name: 'questionEdit',
		params: {
			tagsViewName: '新增试题',
		},
	});
};
// 试题导入
const fileList = ref<EmptyArrayType>([]);
const uploadListRef = ref<RefType>(); // 上传组件ref
const onUpload = async (file: any) => {
	state.loading = true;
	let fileObj = file.file; // 相当于input里取得的files
	let fd = new FormData(); // FormData 对象
	fd.append('file', fileObj); // 文件对象
	questionImport(fd).then(() => {
        ElMessage.success('导入成功！');
        state.loading = false;
        queryList();
    }).catch(() => {
        state.loading = false;
    });
};
// 模板下载
const onDownload  = (row: any) => {
    state.loading = true;
	questionTemplate().then((res: any) => {
        state.loading = false;
        downloadFileByStream(res);
    })
    .catch(() => {
        state.loading = false;
    });
};
// 编辑
const onEdit  = (row: any) => {
	router.push({
		name: 'questionEdit',
		params: {
			id: row.id,
			tagsViewName: '编辑试题',
		},
	});
};
// 删除当前行
const onRowDel = (row: any) => {
	ElMessageBox.confirm(`是否确认删除当前试题？删除后不可恢复`, '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
        .then(() => {
			deleteQuestion({id: row.id}).then(() => {
				ElMessage.success('删除成功');
				queryList();
			});
		})
		.catch(() => {});
};
// 表格选中状态
const tableRef = ref<RefType>();
const toolbarRef = ref<RefType>();
onMounted(() => {
	queryList();
	if (tableRef.value && toolbarRef.value) {
		tableRef.value.connect(toolbarRef.value);
	}
	getTagData();
});
</script>
