<template>
    <div class="app-container">
        <!-- 搜索条件 -->
        <el-form :model="queryForm" ref="queryForm" size="small" :inline="true" label-width="68px">
            <el-form-item label="申请人">
                <el-input v-model="queryForm.borrowBy" placeholder="请输入" clearable></el-input>
            </el-form-item>
            <el-form-item label="借用学科">
                <el-select v-model="queryForm.borrowSub" 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-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-row class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain size="mini" icon="el-icon-plus" @click="handAdd()">新增
                </el-button>
                <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleDelete()">批量删除</el-button>
            </el-col>
        </el-row>
        <!-- 表格 -->
        <el-table stripe :data="tableData" border style="width: 98%; margin-left: 15px"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column align="center" type="index" label="序号" width="55" />
            <el-table-column align="center" prop="borrowBy" label="申请人" />
            <el-table-column align="center" prop="borrowState" label="借用状态">
                <template slot-scope="{ row }">
                    <div>{{ selectDictLabel(dict.type.borrow_state, row.borrowState) }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="schoolTeacherBorrowDetailList" label="借用明细">
                <template slot-scope="{ row }">
                    <div v-for="detail in row.schoolTeacherBorrowDetailList" :key="detail.id">
                        {{ detail.instrumentName }}
                    </div>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="borrowSub" label="借用学科">
                <template slot-scope="{ row }">
                    <div>{{ selectDictLabel(dict.type.lab_sub, row.borrowSub) }}</div>
                </template>
            </el-table-column>
            <el-table-column align="center" prop="applyTime" label="申请时间" />
            <el-table-column align="center" prop="borrowTime" label="借用时间" />
            <el-table-column align="center" prop="returnTime" label="归还时间" />
            <el-table-column align="center" prop="remark" label="备注" />
            <el-table-column align="center" fixed="right" label="操作">
                <template slot-scope="scope">
                    <el-button @click="handleLook(scope.row)" type="text" size="small">详情</el-button>
                    <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 详情弹窗 -->
        <el-dialog :title="title" :visible.sync="dialogxq" width="40%" show-close>
            <el-form :model="form" ref="form" size="small" label-width="110px" :disabled="isEdit">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="申请人">
                            <el-input v-model="form.borrowBy" placeholder="请输入" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="借用状态">
                            <el-select v-model="form.borrowState" placeholder="请选择" clearable style="width: 100%;">
                                <el-option v-for="dict in dict.type.borrow_state" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="借用学科">
                            <el-select v-model="form.borrowSub" 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-col :span="12">
                        <el-form-item label="申请时间">
                            <el-input v-model="form.applyTime" placeholder="请输入" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="借用时间">
                            <el-input v-model="form.borrowTime" placeholder="请输入" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="归还时间">
                            <el-input v-model="form.returnTime" placeholder="请输入" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="借用明细">
                            <el-table stripe :data="tableDatamx" border>
                                <el-table-column align="center" type="index" label="序号" width="55" />
                                <el-table-column align="center" prop="instrumentName" label="仪器名称" />
                                <el-table-column align="center" prop="instrumentModel" label="仪器型号" />
                                <el-table-column align="center" prop="instrumentNum" label="借用数量" />
                            </el-table>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="备注">
                            <el-input v-model="form.remark" placeholder="请输入" type="textarea" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-dialog>
        <!-- 新增弹窗 -->
        <el-dialog :title="title" :visible.sync="dialogxz" width="40%" show-close>
            <el-form :model="postForm" ref="postForm" size="small" label-width="110px">
                <el-row>
                    <el-col>
                        <el-form-item label="借用人">
                            <el-input v-model="postForm.borrowBy" placeholder="请输入" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="借用学科">
                            <el-select v-model="postForm.borrowSub" 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>
                    <el-col>
                        <el-form-item label="借用明细">
                            <el-col :span="1.5" style="margin-bottom: 5px">
                                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handOpenAdd()">新增
                                </el-button>
                            </el-col>
                            <el-table stripe :data="tableDataxz" border>
                                <el-table-column align="center" type="index" label="序号" width="55" />
                                <el-table-column align="center" prop="instrumentName" label="仪器名称" />
                                <el-table-column align="center" prop="instrumentModel" label="仪器型号" />
                                <el-table-column align="center" prop="instrumentNum" label="可借用数量" />
                                <el-table-column align="center" prop="borrowNum" label="借用数量">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.borrowNum" size="mini"></el-input>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="备注">
                            <el-input v-model="postForm.remark" placeholder="请输入" type="textarea" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <div slot="footer">
                <el-button type="primary" @click="submitparentForm">确定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <!-- 借用明细弹窗 -->
        <el-dialog :title="title" :visible.sync="dialogmx" width="50%" show-close>
            <el-form :model="formmx" ref="formmx" size="small" label-width="70px">
                <el-row>
                    <el-col :span="8">
                        <el-form-item label="仪器名称">
                            <el-input v-model="formmx.instrumentName" placeholder="请输入" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="仪器分类">
                            <treeselect v-model="formmx.instrumentTypeId" :options="equiList" :normalizer="normalizer"
                                placeholder="选择分类编码" clearable style="width: 100%" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="2">
                        <el-form-item>
                            <el-button type="primary" plain icon="el-icon-search" size="mini"
                                @click="getListtc">搜索</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item label="借用明细">
                            <el-table stripe :data="tablejymx" border @selection-change="handleSelectionChangemx">
                                <el-table-column type="selection" width="55"></el-table-column>
                                <el-table-column align="center" type="index" label="序号" width="55" />
                                <el-table-column align="center" prop="instrumentName" label="仪器名称" />
                                <el-table-column align="center" prop="instrumentTypeName" label="仪器分类" />
                                <el-table-column align="center" prop="instrumentModel" label="仪器型号" />
                                <el-table-column align="center" prop="instrumentNum" label="可借用数量" />
                            </el-table>
                        </el-form-item>

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

            <div slot="footer">
                <el-button type="primary" @click="submiopenForm">确定</el-button>
                <el-button @click="cancelmx">取 消</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 {
    getTeacherBorrow,
    addTeacherBorrow,
    getTeacherBorrowlist,//查看列表
    getTeacherBorrowlxq,
    deleteTeacherBorrow,
} from '@/api/smartSchool/InstrumentDrugAdministration/instrumentBorrowManagement/teacherBorrowing'
import {
    getList,//查看列表
} from '@/api/smartSchool/InstrumentDrugAdministration/instrumentClassification'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
    name: 'teacherBorrowing',
    components: { Treeselect },
    dicts: ['lab_sub', 'borrow_state'],
    data() {
        return {
            queryForm: {
                pageNum: 1,
                pageSize: 10,
                borrowBy: "",
                borrowSub: "",
            },
            //表格数据
            tableData: [

            ],
            //查看详情
            tableDatamx: [

            ],
            //借用明细
            tablejymx: [

            ],
            //新增
            tableDataxz: [],
            title: '',
            // 详情弹窗
            form: {},
            //新增弹窗
            postForm: { // 新增弹窗表单数据
                borrowBy: '', // 借用人
                borrowSub: '', // 借用学科
                remark: '', // 备注
                tableDataxz: [],
            },
            //借用明细弹窗
            formmx: {},
            equiList: [],
            isEdit: false,
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总计
            total: 0,
            single: false, // 添加 single 属性并设置初始值
            multiple: false,
            dialogxq: false, //详情弹窗
            dialogxz: false, //新增弹窗
            dialogmx: false, // 借用明细新增
            selectedRows: [] // 存储用户选择的行
        }
    },
    created() {
        this.getList();
        this.getListequ();

    },
    methods: {
        // 搜索
        getList() {
            this.loading = true
            getTeacherBorrowlist({ ...this.queryForm }).then(res => {
                if (res.code == 200) {
                    this.total = res.total;
                    this.tableData = res.rows;
                    console.log(this.tableData);
                    this.loading = false
                }
            })
        },
        getListtc() {
            this.loading = true;
            let params = {};
            if (this.tablejymx.some(item => item.id)) {
                params = {
                    instrumentName: this.formmx.instrumentName,
                    instrumentTypeId: this.formmx.instrumentTypeId,
                    ids: this.ids // 使用选中的 id
                };
            } else {
                params = {
                    instrumentName: this.formmx.instrumentName,
                    instrumentTypeId: this.formmx.instrumentTypeId
                };
            }

            getTeacherBorrow(params)
                .then(res => {
                    if (res.code === 200) {
                        this.tablejymx = res.rows;
                        console.log(this.tablejymx);
                        this.loading = false;
                    }
                });
        },
        //查询表单数据
        getListequ() {
            this.loading = true;
            getList(this.queryForm).then(response => {
                this.equiList = this.handleTree(response.rows, "id", 'parentId', 'children');
                this.loading = false;
            })
        },
        /** 转换分类编码数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.id,
                label: node.instrumentTypeName,
                children: node.children
            };
        },
        // 重置
        resetQuery() {
            this.queryForm = {
                pageNum: 1,
                pageSize: 10,
                borrowBy: "",
                borrowSub: "",
            },
                this.getList();
        },
        // 新增
        handAdd() {
            this.reset();
            const userName = this.$store.state.user;
            console.log(userName);
            this.postForm.borrowBy = userName.name
            console.log(this.postForm.borrowBy);
            this.dialogxz = true
            this.title = '教师借用新增'
        },

        //删除按钮操作
        handleDelete(row) {
            if (row) {
                // 单个删除
                this.$modal.confirm('是否确认删除选中数据？').then(() => {
                    this.$modal.loading('正在处理数据，请稍等...');
                    return deleteTeacherBorrow(row.id);
                }).then(response => {
                    this.$modal.closeLoading();
                    this.$modal.msgSuccess("删除成功");
                    this.getList();
                })
            } else {
                // 批量删除
                if (!this.ids || this.ids.length === 0) {
                    this.$modal.warning("请选择要删除的数据");
                    return;
                }
                this.$modal.confirm('是否确认删除选中数据？').then(() => {
                    this.$modal.loading('正在处理数据，请稍等...');
                    const deletePromises = this.ids.map(id => deleteTeacherBorrow(id));
                    console.log(deletePromises);
                    return Promise.all(deletePromises);
                }).then(response => {
                    this.$modal.closeLoading();
                    this.$modal.msgSuccess("删除成功");
                    this.getList();
                }).catch(error => {
                    this.$modal.closeLoading();
                });
            }
        },
        reset() {
            this.postForm.borrowBy = ''; // 重置借用人字段
            this.postForm.borrowSub = ''; // 重置借用学科字段
            this.postForm.remark = ''; // 重置备注字段
            this.tableDataxz = []; // 清空数组
        },
        // 详情
        handleLook(row) {
            console.log(row);
            this.dialogxq = true;
            getTeacherBorrowlxq(row.id).then(res => {
                if (res.code == 200) {
                    this.form = res.data;
                    this.tableDatamx = res.data.schoolTeacherBorrowDetailList;
                    console.log(this.tableDatamx);
                    this.isEdit = true;
                    this.loading = false
                }
            })
            this.title = '教师借用详情'
        },
        // 教师借用确定
        submitparentForm() {
            const borrowDetails = [];
            for (let i = 0; i < this.tableDataxz.length; i++) {
                const item = this.tableDataxz[i];
                if (item && item.id) {
                    borrowDetails.push({
                        instrumentId: item.id,
                        borrowNum: item.borrowNum // 借用数量字段
                    });
                }
            }
            this.postForm.schoolTeacherBorrowDetailList = borrowDetails;
            this.$refs["postForm"].validate(valid => {
                if (valid) {
                    addTeacherBorrow(this.postForm).then(response => {
                        console.log('this.postForm', this.postForm);
                        this.$modal.msgSuccess("新增成功");
                        this.dialogxz = false;
                        this.getList();
                    });
                }
            });
        },

        //取消按钮
        cancel() {
            this.reset();
            this.dialogxz = false;
        },
        cancelmx() {
            this.dialogmx = false;
        },
        // 借用明细新增
        handOpenAdd() {
            this.dialogmx = true;
            this.getListtc();
            this.title = '借用明细新增'

        },

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

        // 多选
        handleSelectionChangemx(selection) {
            if (selection.length > 0) {
                selection.forEach(selectedItem => {
                    const newItem = { ...selectedItem };
                    this.tableDataxz.push(newItem);
                });
            }
            this.ids = selection.map(item => item.id);
            this.single = selection.length === 1;
            this.multiple = !selection.length;
        },

        // 借用明细新增按钮
        submiopenForm() {
            // 先清空this.tableDataxz，然后将选中的项重新添加到this.tableDataxz中
            this.tableDataxz = [];
            this.tableDataxz = this.tableDataxz.concat(this.tablejymx.filter(item => this.ids.includes(item.id)));
            this.dialogmx = false;
        },


    }
}
</script>

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