<template>
    <div class="app-container">
        <el-form :model="queryForm" ref="queryForm" size="small" :inline="true" label-width="88px">
            <el-form-item label="学期">
                <el-date-picker v-model="queryForm.schoolYear" type="year" value-format="yyyy" placeholder="选择年">
                </el-date-picker>
                <el-select v-model="queryForm.semester" placeholder="请选择学期">
                    <el-option label="上学期" value="1"></el-option>
                    <el-option label="下学期" value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="实验室名称">
                <el-input v-model="queryForm.experimentName" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="实验分类">
                <el-select v-model="queryForm.experimentClassify" placeholder="请选择" clearable>
                    <el-option v-for="dict in dict.type.experiment_classify" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="tableData" border style="width: 100%">
            <el-table-column align="center" type="index" label="序号" width="55" />
            <el-table-column align="center" prop="sub" label="学科">
                <template slot-scope="{ row }">
                    <div>{{ selectDictLabel(dict.type.lab_sub, row.sub) }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="grade" label="级部" />
            <el-table-column align="center" prop="schoolYear" label="学年" />
            <el-table-column align="center" prop="plannedTime" label="计划时间" />
            <el-table-column align="center" prop="experimentName" label="实验名称" />
            <el-table-column align="center" prop="experimentClassify" label="实验分类">
                <template slot-scope="{ row }">
                    <div>{{ selectDictLabel(dict.type.experiment_classify, row.experimentClassify) }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="experimentUseGoods" label="实验用品" />
            <el-table-column align="center" label="实验室">
                <template slot-scope="scope">
                    <div v-if="scope.row.schoolLabClassYearRelationList">
                        {{ scope.row.schoolLabClassYearRelationList.map(lab => lab.labName).join(", ") }}
                    </div>
                </template>
            </el-table-column>

            <el-table-column align="center" prop="declareState" label="申报状态">
                <template slot-scope="{ row }">
                    <div>{{ selectDictLabel(dict.type.declare_state, row.declareState) }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作" width="150">
                <template slot-scope="scope">
                    <el-button @click="handleLook(scope.row)" type="text" size="small">查看</el-button>
                    <el-button v-if="scope.row.declareState !== '3'" @click="handleAllocation(scope.row)" type="text"
                        size="small">分配实验室</el-button>
                </template>
            </el-table-column>

        </el-table>
        <!-- 查看 -->
        <el-dialog title="申请信息" :visible.sync="open" width="50%">
            <el-form :model="form" ref="form" size="small" label-width="100px" :disabled="isEdit">
                <el-row :gutter="30">
                    <el-col :span="10">
                        <el-form-item label="申请老师">
                            <el-input v-model="form.applyName" placeholder="请输入" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="实验分类">
                            <el-select v-model="form.experimentClassify" placeholder="请选择" clearable style="width: 100%;">
                                <el-option v-for="dict in dict.type.experiment_classify" :key="dict.value"
                                    :label="dict.label" :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="实验名称">
                            <el-input v-model="form.experimentName" placeholder="请输入" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="学科">
                            <el-select v-model="form.sub" placeholder="请选择" clearable style="width: 100%;">
                                <el-option v-for="dict in dict.type.lab_sub" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                </el-row>

                <el-row :gutter="20">
                    <el-col :span="20">
                        <el-form-item label="章节内容">
                            <el-input v-model="form.chapterContent" placeholder="请输入" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>


                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="级部">
                            <el-input v-model="form.grade" placeholder="请输入" clearable />
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="学年">
                            <el-input v-model="form.schoolYear" placeholder="请输入" clearable />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="20">
                        <el-form-item label="实验用品">
                            <el-input v-model="form.experimentUseGoods" type="textarea" placeholder="请输入"
                                clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="计划开始时间" prop="plannedStartTime">
                            <el-date-picker v-model="form.plannedStartTime" type="date" placeholder="选择"
                                value-format="yyyy-MM-dd" style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="计划结束时间" prop="plannedEndTime">
                            <el-date-picker v-model="form.plannedEndTime" type="date" placeholder="选择"
                                value-format="yyyy-MM-dd" style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="实验室选择">
                            <el-checkbox-group v-model="form.schoolLabClassYearRelationList">
                                <el-checkbox v-for="classItem in schoolLabClassYearRelationList" :key="classItem.labId"
                                    :label="classItem.labId">
                                    {{ classItem.labName }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>

                    </el-col>
                </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer" style="text-align: center;">
                <el-button @click="cancel"> 取 消 </el-button>

            </div>

        </el-dialog>
        <!-- 分配实验室弹窗 -->
        <el-dialog title="申请信息" :visible.sync="dialogTableVisible" width="50%">
            <el-form :model="postForm" ref="postForm" size="small" label-width="100px">
                <el-row :gutter="30">
                    <el-col :span="10">
                        <el-form-item label="申请老师">
                            <el-input v-model="postForm.applyName" placeholder="请输入" clearable :disabled="isEdits" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="实验分类">
                            <el-select v-model="postForm.experimentClassify" placeholder="请选择" clearable
                                style="width: 100%;" :disabled="isEdits">
                                <el-option v-for="dict in dict.type.experiment_classify" :key="dict.value"
                                    :label="dict.label" :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="实验名称">
                            <el-input v-model="postForm.experimentName" placeholder="请输入" clearable :disabled="isEdits" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="学科">
                            <el-select v-model="postForm.sub" placeholder="请选择" clearable style="width: 100%;"
                                :disabled="isEdits">
                                <el-option v-for="dict in dict.type.lab_sub" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                </el-row>

                <el-row :gutter="20">
                    <el-col :span="20">
                        <el-form-item label="章节内容">
                            <el-input v-model="postForm.chapterContent" placeholder="请输入" clearable
                                :disabled="isEdits"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>


                <el-row :gutter="20">
                    <el-col :span="10">
                        <el-form-item label="级部">
                            <el-input v-model="postForm.grade" placeholder="请输入" clearable :disabled="isEdits" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="学年">
                            <el-input v-model="postForm.schoolYear" placeholder="请输入" clearable :disabled="isEdits" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="20">
                        <el-form-item label="实验用品">
                            <el-input v-model="postForm.experimentUseGoods" type="textarea" placeholder="请输入"
                                clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="计划开始时间" prop="plannedStartTime">
                            <el-date-picker v-model="postForm.plannedStartTime" type="date" placeholder="选择"
                                value-format="yyyy-MM-dd" style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="10">
                        <el-form-item label="计划结束时间" prop="plannedEndTime">
                            <el-date-picker v-model="postForm.plannedEndTime" type="date" placeholder="选择"
                                value-format="yyyy-MM-dd" style="width: 100%;">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="实验室选择">
                            <el-checkbox-group v-model="postForm.schoolLabClassYearRelationList">
                                <el-checkbox v-for="classItem in labs" :key="classItem.labId" :label="classItem.labId"
                                    >
                                    {{ classItem.labName }}- {{ classItem.useState }}
                                </el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>

                    </el-col>
                </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer" style="text-align: center;">
                <el-button @click="save"> 保 存 </el-button>
                <el-button type="primary" @click="submitForm">提 交</el-button>
            </div>

        </el-dialog>

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

<script>


import {
    getLabClassYear,
    getLabList,
    getAllocationLab,
    getLabClassYearxq,

} from '@/api/smartSchool/laboratoryManagement/gradeExperimentapp'
import {

    getSemester

} from '@/api/smartSchool/laboratoryManagement/experimentalPlan'
export default {
    name: 'index',
    dicts: ['experiment_classify', 'lab_sub', 'declare_state'],
    data() {
        return {
            queryForm: {
                pageNum: 1,
                pageSize: 10,
                schoolYear: "",
                semester: "",
                experimentName: "",
                experimentClassify: "",

            },
            //实验室
            labs: [],
            schoolLabClassYearRelationList: [],
            //表格数据
            tableData: [

            ],
            isEdit: false,
            isEdits: false,
            postForm: {
                applyName: '',
                experimentClassify: '',
                experimentName: '',
                sub: '',
                chapterContent: '',
                grade: '',
                schoolYear: '',
                experimentUseGoods: '',
                plannedStartTime: '',
                plannedEndTime: '',
                schoolLabClassYearRelationList: [],
            },
            form: {
                applyName: '',
                experimentClassify: '',
                experimentName: '',
                sub: '',
                chapterContent: '',
                grade: '',
                schoolYear: '',
                experimentUseGoods: '',
                plannedStartTime: '',
                plannedEndTime: '',
                schoolLabClassYearRelationList: [],
            },
            total: 0,
            dialogTableVisible: false,
            open: false,
        }
    },
    created() {
        this.getSemesterAndList();
    },
    methods: {

        async getSemesterAndList() {
            await this.getSemester(); // 等待获取学年和学期信息
            this.getList(); // 获取数据列表
        },
        getSemester() {
            return new Promise((resolve, reject) => {
                getSemester()
                    .then(response => {
                        this.queryForm.semester = response.semester;
                        this.queryForm.schoolYear = response.schoolYear + '';
                        resolve(); // 成功获取学年和学期信息
                    })
                    .catch(error => {
                        console.log(error);
                        reject(error);
                    });
            });
        },
        getList() {
            getLabClassYear(this.queryForm)
                .then(response => {
                    this.tableData = response.rows;
                    console.log('response', response);
                    this.total = response.total;
                    this.loading = false;
                })
                .catch(error => {
                    this.loading = false;
                    console.log(error);
                });
        },

        //分配实验室
        handleAllocation(row) {
            this.loading = true;
            const id = row.id || this.ids;
            getLabClassYearxq(id).then(response => {
                this.postForm = response.data;
                // 清空已经选择的实验室
                this.selectedLabs = [];
                for (let i = 0; i < this.postForm.schoolLabClassYearRelationList.length; i++) {
                    const labId = this.postForm.schoolLabClassYearRelationList[i].labId;
                    this.selectedLabs.push(labId);
                }
                this.postForm.schoolLabClassYearRelationList = this.selectedLabs; // 仅将已经选择的实验室作为关联数据提交
                this.loading = false;
                const plannedStartTime = this.postForm.plannedStartTime
                const plannedEndTime = this.postForm.plannedEndTime
                const sub = this.postForm.sub
                getLabList(plannedStartTime, plannedEndTime, sub).then(response => {
                    const labs = response.data;
                    console.log(labs, 'qb');
                    const selectedLabs = this.postForm.schoolLabClassYearRelationList; // 获取已选择的实验室列表
                    console.log(selectedLabs, 'xz');

                    // 将已选择的实验室信息存储在新的数组中
                    const selectedLabInfo = labs.filter(lab => {
                        const isSelected = selectedLabs.some(selectedLab => selectedLab.labId === lab.labId);
                        if (isSelected) {
                            lab.isSelected = true;
                            return true;
                        }
                        return false;
                    });

                    // 更新 labs 数组，将已选择的实验室信息存储在对应实验室对象中
                    this.labs = labs.map(lab => {
                        const selectedLab = selectedLabInfo.find(selectedLab => selectedLab.labId === lab.labId);
                        if (selectedLab) {
                            lab.selectedLabInfo = selectedLab;
                        }
                        return lab;
                    }).map(lab => {
                        if (lab.useState === '使用中') {
                            lab.isDisabled = true;
                        }
                        return lab;
                    })
                    this.isEdits = true;
                    this.loading = false;
                });

            });
            this.dialogTableVisible = true;
        },

        //查看按钮操作
        handleLook(row) {
            this.open = true;
            const id = row.id || this.ids;
            getLabClassYearxq(id).then(response => {
                this.form = response.data;
                if (response.data.schoolLabClassYearRelationList) { // 判断 schoolLabClassYearRelationList 存在且不为空
                    this.schoolLabClassYearRelationList = response.data.schoolLabClassYearRelationList;
                    console.log('this.form.schoolLabClassYearRelationList', this.form.schoolLabClassYearRelationList);

                }
                this.form.schoolLabClassYearRelationList = [];
                for (let i = 0; i < this.schoolLabClassYearRelationList.length; i++) {
                    const labId = this.schoolLabClassYearRelationList[i].labId;
                    const labName = this.schoolLabClassYearRelationList[i].labName;
                    this.form.schoolLabClassYearRelationList.push(labId, labName);
                    console.log(this.form.schoolLabClassYearRelationList, '查看 ');
                }
                console.log('this.form', this.form);
                this.isEdit = true;
                this.loading = false
            })
        },
        resetQuery() {
            this.queryForm = {
                pageNum: 1,
                pageSize: 10,
                schoolYear: "",
                semester: "",
                experimentName: "",
                experimentClassify: "",

            },
                this.getList();
        },
        // 保存按钮
        save() {
            this.$refs['postForm'].validate(valid => {
                if (valid) {
                    if (this.postForm.id != null) {
                        const selectedLabs = []; // 临时数组
                        for (let i = 0; i < this.labs.length; i++) {
                            const labId = this.labs[i].labId;
                            const labName = this.labs[i].labName;
                            if (this.postForm.schoolLabClassYearRelationList.includes(labId)) { // 判断是否选中
                                selectedLabs.push({ labId: labId, labName: labName }); // 将选中的实验室push进临时数组
                            }
                        }

                        const params = {
                            id: this.postForm.id,
                            plannedStartTime: this.postForm.plannedStartTime,
                            plannedEndTime: this.postForm.plannedEndTime,
                            experimentUseGoods: this.postForm.experimentUseGoods,
                            declareState: '2',
                            schoolLabClassYearRelationList: selectedLabs, // 将临时数组赋值给params.schoolLabClassYearRelationList
                        };

                        getAllocationLab(params).then(response => {
                            this.$modal.msgSuccess('保存成功');
                            this.dialogTableVisible = false;
                            this.getList();
                        });
                    }
                }
            });
        },


        /** 提交按钮 */
        submitForm() {
            this.$refs['postForm'].validate(valid => {
                if (valid) {
                    if (this.postForm.id != null) {
                        const params = {
                            id: this.postForm.id,
                            plannedStartTime: this.postForm.plannedStartTime,
                            plannedEndTime: this.postForm.plannedEndTime,
                            experimentUseGoods: this.postForm.experimentUseGoods,
                            declareState: '3',
                            schoolLabClassYearRelationList: [],
                        };
                        for (let i = 0; i < this.labs.length; i++) {
                            const labId = this.labs[i].labId;
                            const labName = this.labs[i].labName;
                            if (this.postForm.schoolLabClassYearRelationList.includes(labId)) { // 判断是否选中
                                params.schoolLabClassYearRelationList.push({ labId: labId, labName: labName }); // 将选中的实验室push进数组
                            }
                        }
                        getAllocationLab(params).then(response => {
                            console.log(params, params);
                            this.$modal.msgSuccess('提交成功');
                            this.dialogTableVisible = false;
                            this.getList();
                        });
                    }
                }
            });
        },


        // 取消按钮
        cancel() {
            this.open = false;
        },

    },
}
</script>

<style lang="scss" scoped></style>
