<template>
    <div class="app-container">

        <el-table v-loading="loading" :data="submissionsList" @selection-change="handleSelectionChange">
            <el-table-column label="报表名称" align="center" prop="reportName" />
            <el-table-column label="学期" align="center" prop="term_id">
                <template slot-scope="scope">
                    <div v-for="item in yearOptions" :key="item.id">
                        <span v-if="scope.row.term_id == item.id">
                            {{ item.termName }}
                        </span>
                    </div>
                </template>
            </el-table-column>

            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-view"
                        @click="lookStuVClick(scope.row)">查看学生</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />

        <el-dialog :visible.sync="dialogVisible" fullscreen :close-on-click-modal="false" @close="handleDialogClose"
            @submission-success="handleSubmissionSuccess">
            <stu v-if="dialogVisible" :reportData="currentReport" />
        </el-dialog>

        <el-dialog title="查看学生" :visible.sync="lookStuV" fullscreen :close-on-click-modal="false" append-to-body>
            <XgList v-if="lookStuV" :reportData="reportData" />
        </el-dialog>



    </div>
</template>

<script>
import { listSubmissions } from "@/api/diagnostic/submissions";
import { getTerm } from "@/api/diagnostic/DiaReportRelease";
import stu from "@/views/diagnostic/DiaFillOutReport/stu";
import XgList from "@/views/diagnostic/DiaFillOutReport/XgList";

export default {
    name: "Submissions",
    components: {
        stu,
        XgList
    },
    data() {
        return {
            loading: true,
            ids: [],
            single: true,
            multiple: true,
            showSearch: true,
            total: 0,
            submissionsList: [],
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                reportName: null,
                term_id: null,
            },
            yearOptions: [],
            dialogVisible: false,
            currentReport: {},
            formData: {
                content: "",
            },

            reportData: {},
            lookStuV: false
        };
    },
    created() {
        this.getList();
        this.getTermOptions();
    },
    methods: {
        lookStuVClick(row) {
            this.reportData = { ...row };
            this.lookStuV = true;
        },
        /** 查询学生报提交记录列表 */
        getList() {
            this.loading = true;
            listSubmissions(this.queryParams).then(response => {
                this.submissionsList = response.rows;
                this.loadSubmittedStatus(); // 加载本地保存的提交状态
                this.total = response.total;
                this.loading = false;
            });
        },

        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },

        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },

        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id);
            this.single = selection.length !== 1;
            this.multiple = !selection.length;
        },

        /** 获取学期选项数据 */
        getTermOptions() {
            getTerm().then(response => {
                this.yearOptions = response.data;
            }).catch(error => {
                console.error('获取学期选项失败', error);
                this.$message.error("获取学期数据失败");
            });
        },

        /** 填写报表按钮操作 */
        handleFillReport(row) {
            this.currentReport = { ...row };
            this.dialogVisible = true;
        },

        /** 提交表单 */
        submitForm() {
            this.$message.success("提交成功!");
            this.dialogVisible = false;
        },

        /** 关闭弹窗时重置表单 */
        handleDialogClose() {
            this.formData.content = ""; // 清空表单
        },

        /** 处理子组件提交成功事件 */
        handleSubmissionSuccess(reportId) {
            // 更新内存中的状态
            const index = this.submissionsList.findIndex(item => item.id === reportId);
            if (index !== -1) {
                this.$set(this.submissionsList[index], 'status', '2'); // 状态码'2'表示已填写
                this.saveSubmittedStatus(reportId); // 保存到localStorage
                this.$message.success('状态已更新为"已填写"');
            }
        },

        /** 保存提交状态到localStorage */
        saveSubmittedStatus(reportId) {
            try {
                const submittedReports = JSON.parse(localStorage.getItem('submittedReports')) || {};
                submittedReports[reportId] = true;
                localStorage.setItem('submittedReports', JSON.stringify(submittedReports));
            } catch (error) {
                console.error('保存提交状态失败:', error);
            }
        },

        /** 从localStorage加载提交状态 */
        loadSubmittedStatus() {
            try {
                const submittedReports = JSON.parse(localStorage.getItem('submittedReports')) || {};
                this.submissionsList = this.submissionsList.map(item => {
                    return {
                        ...item,
                        status: submittedReports[item.id] ? '2' : item.status // 若已提交,设置状态为'2'
                    };
                });
            } catch (error) {
                console.error('加载提交状态失败:', error);
            }
        },


        /** 获取状态文本 */
        getStatusText(status) {
            const statusMap = {
                '0': '填写中',
                '1': '停用',
                '2': '已填写'
            };
            return statusMap[status] || '未知状态';
        },

        /** 获取状态标签类型 */
        getStatusType(status) {
            const typeMap = {
                '0': 'success', // 填写中:绿色
                '1': 'danger', // 停用:红色
                '2': 'primary'  // 已填写:蓝色
            };
            return typeMap[status] || 'info';
        },

        /** 获取状态标签效果 */
        getStatusEffect(status) {
            return status === '2' ? 'light' : 'dark'; // 已填写使用浅色标签
        }
    }
};
</script>

<style scoped></style>