<template>
    <div class="app-container">
        <el-form :model="queryForm" ref="queryForm" size="small" :inline="true">
            <el-form-item label="仪器名称">
                <el-input v-model="queryForm.instrumentName" style="width: 100%" placeholder="请输入" clearable></el-input>
            </el-form-item>
            <el-form-item label="仪器分类">
                <treeselect v-model="queryForm.instrumentTypeId" :options="equiList" :normalizer="normalizer"
                    placeholder="选择分类编码" clearable style="width: 192px" noOptionsText="暂无数据" />
            </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" :gutter="8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleOption(0)">新增</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%" @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="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-column align="center" fixed="right" label="操作">
                <template slot-scope="{ row }">
                    <div>
                        <el-button type="text" size="small" @click="handleOption(2, row)">查看</el-button>
                        <el-button type="text" size="small" @click="handleOption(1, row)">编辑</el-button>
                        <el-button type="text" size="small" @click="handleDelete(row)">删除</el-button>
                        <el-button @click="handleOut(row)" type="text" size="small">出库</el-button>
                        <el-button @click="handleIn(row)" type="text" size="small">入库</el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!--仪器新增 弹窗 -->
        <el-dialog title="详细信息" :visible.sync="dialogTableVisible" width="30%" show-close>
            <el-form :model="form" ref="form" :rules="rules" size="small" label-width="108px">
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="仪器名称" prop="instrumentName">
                            <el-input v-model="form.instrumentName" placeholder="请输入" clearable
                                :disabled="nowType == 2 ? true : false"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="仪器分类" prop="instrumentTypeName">
                            <treeselect v-model="form.instrumentTypeName" :options="equiList" :normalizer="normalizer"
                                placeholder="选择" clearable style="width: 100%" noOptionsText="暂无数据" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="仪器型号" prop="instrumentModel">
                            <el-input v-model="form.instrumentModel" placeholder="请输入" clearable
                                :disabled="nowType == 2 ? true : false"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" placeholder="请输入" type="textarea" clearable
                                :disabled="nowType == 2 ? true : false"></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="仪器库存" :visible.sync="open" width="30%" show-close>
            <el-form :model="form" ref="form" size="small" label-width="108px">
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="仪器名称">
                            <el-input v-model="postForm.instrumentName" :disabled="true"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="旧库存数量">
                            <el-input v-model="postForm.instrumentNum" :disabled="true"> </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="变动类型">
                            <el-select v-model="postForm.variationType" clearable placeholder="请选择" :disabled="true">
                                <el-option v-for="dict in dict.type.variation_type" :key="dict.value" :label="dict.label"
                                    :value="dict.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="变动数量">
                            <el-input v-model="postForm.variationNum" @input="updateNewStockNum"></el-input>
                        </el-form-item>

                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="新库存数量">
                            <el-input v-model="postForm.newStockNum" :disabled="true"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="20">
                        <el-form-item label="备注">
                            <el-input v-model="postForm.remark" placeholder="请输入" type="textarea" clearable
                                :disabled="isEdit"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <div slot="footer">
                <el-button type="primary" @click="submitInventory">确定</el-button>
                <el-button @click="cancel">取 消</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 {
    addInst,//新增仪器
    editInst,//修改仪器
    getListyq,//查看仪器列表
    getInstxq,
    deleteInst,
    getListrk,
    getInstrumentDetail
} from '@/api/smartSchool/InstrumentDrugAdministration/instrumentManagement'
import {
    getList,//查看列表
} from '@/api/smartSchool/InstrumentDrugAdministration/instrumentClassification'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
    name: 'instrumentManagement',
    components: { Treeselect },
    dicts: ['variation_type'],
    data() {
        return {
            queryForm: {
                pageNum: 1,
                pageSize: 10,
                instrumentName: "",
                instrumentTypeId: null,
            },
            //表格数据
            tableData: [

            ],
            isEdit: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            equiList: [],
            // 列表
            assetsList: [],
            tablekc: [],
            title: '',
            // 弹窗
            form: {
                instrumentName: "",
                instrumentTypeId: "",
                instrumentTypeName: null,
                instrumentModel: "",
                instrumentNum: "",
                remark: "",
            },
            postForm: {
                instrumentId: "",
                variationType: "",
                oldStockNum: "",
                newStockNum: "",
                remark: "",
            },
            // 总计
            total: 0,
            rules: {
                instrumentName: [
                    { required: true, message: "仪器名称不能为空", trigger: "blur" }
                ],
                instrumentTypeId: [
                    { required: true, message: "仪器分类不能为空", trigger: "blur" }
                ],
                instrumentTypeName: [
                    { required: true, message: "仪器类名不能为空", trigger: "blur" }
                ],
                instrumentModel: [
                    { required: true, message: "仪器型号不能为空", trigger: "blur" }
                ],
                instrumentNum: [
                    { required: true, message: "仪器数量不能为空", trigger: "blur" }
                ],
                remark: [
                    { required: true, message: "备注不能为空", trigger: "blur" }
                ],

            },
            //仪器新增/修改弹窗
            dialogTableVisible: false,
            // 库存弹窗
            open: false,
            nowType: 0, // 0新增、1编辑、2查看
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true
        }
    },
    created() {
        this.getListequ();
        this.getList();
    },
    methods: {
        // 搜索
        getList() {
            this.loading = true
            getListyq({ ...this.queryForm }).then(res => {
                if (res.code == 200) {
                    this.total = res.total;
                    this.tableData = res.rows;
                    console.log(this.tableData);
                    this.loading = false
                }
            })
        },
        //查询表单数据
        getListequ() {
            this.loading = true;
            getList(this.queryForm).then(response => {
                this.equiList = this.handleTree(response.rows, "id", 'parentId', 'children');
                console.log('this.tableData', this.tableData);
                this.loading = false;
            })
        },
        /** 转换分类编码数据结构 */
        normalizer(node) {
            console.log(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,
                instrumentName: "",
                instrumentTypeId: null,
            },
                this.getList();
        },

        // 0新增、1编辑、2查看
        handleOption(type, item) {
            this.collectionForm = {
                id: '',
                instrumentName: "",
                instrumentTypeId: "",
                instrumentTypeName: null,
                instrumentModel: "",
                instrumentNum: "",
                remark: "",
            }
            this.nowType = type;
            if (type != 0) {
                const id = item.id;
                getInstxq(id).then(res => {
                    if (res.code == 200) {
                        Object.keys(this.form).forEach(key => {
                            if (res.data[key]) {
                                this.$set(this.form, key, res.data[key]);
                            }
                        });

                    }

                })
            }
            this.dialogTableVisible = true
        },
        // 计算新库存数量
        updateNewStockNum() {
            const variationNum = parseFloat(this.postForm.variationNum);
            const instrumentNum = parseFloat(this.postForm.instrumentNum);

            if (this.postForm.variationType === '2') {
                // 入库操作，新库存等于旧库存加上变动数量
                this.postForm.newStockNum = isNaN(variationNum) || isNaN(instrumentNum) ? 0 : variationNum + instrumentNum;
            } else if (this.postForm.variationType === '1') {
                // 出库操作，新库存等于旧库存减去变动数量
                this.postForm.newStockNum = isNaN(variationNum) || isNaN(instrumentNum) ? 0 : instrumentNum - variationNum;
            }
        },

        // 入库
        handleIn(row) {
            this.open = true;
            const id = row.id;
            getInstxq(id).then(res => {
                if (res.code == 200) {
                    this.postForm = res.data;
                    this.postForm.variationType = '2';
                    this.loading = false;
                    this.isEdit = true;
                    // 初始化新库存数量
                    this.updateNewStockNum();
                }
            })
        },

        // 出库
        handleOut(row) {
            this.open = true;
            const id = row.id;
            getInstxq(id).then(res => {
                if (res.code == 200) {
                    this.postForm = res.data;
                    console.log(this.postForm);
                    this.postForm.variationType = '1';
                    console.log(this.postForm);
                    this.loading = false
                    // 初始化新库存数量
                    this.updateNewStockNum();
                }
            })
        },
        // 入库/出库提交
        submitInventory() {
            if (!this.postForm.variationNum || isNaN(this.postForm.variationNum)) {
                this.$message.error('请输入正确的变动数量！');
                return;
            }
            const postData = {
                instrumentId: this.postForm.id,
                variationType: this.postForm.variationType,
                oldStockNum: this.postForm.instrumentNum,
                newStockNum: this.postForm.newStockNum,
                remark: this.postForm.remark,
            };
            getInstrumentDetail(postData).then(res => {
                if (res.code == 200) {
                    this.$message.success('操作成功！');
                    this.open = false;
                    this.getList();
                } else {
                    this.$message.error(res.msg);
                }
            })
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        // 仪器确定
        submitparentForm: function () {
            const useId = this.form.useId
            this.form.useName = useId == '' ? '' : this.equiList.find(item => item.userId == useId).userName
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.id != null) {
                        editInst(this.form).then(response => {
                            console.log('this.form', this.form);
                            this.$modal.msgSuccess("修改成功");
                            this.dialogTableVisible = false;
                            this.getList();
                            this.enuqLeader();

                        });
                    } else {
                        addInst(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.dialogTableVisible = false;
                            this.getList();

                        });
                    }
                }
            });
        },
        reset() {
            // 这里需要重置对话框表单
            this.form = {
                id: null,
                instrumentName: null,
                instrumentTypeId: '',
                instrumentTypeName: null,
                instrumentModel: null,
                instrumentNum: null,
                remark: null,

            };
        },
        //取消按钮
        cancel() {
            this.dialogTableVisible = false;
            this.open = false;
            this.reset();
        },
        //删除按钮操作
        handleDelete(row) {
            if (row) {
                // 单个删除
                this.$modal.confirm('是否确认删除选中数据？').then(() => {
                    this.$modal.loading('正在处理数据，请稍等...');
                    return deleteInst(row.id);
                }).then(response => {
                    this.$modal.closeLoading();
                    this.$modal.msgSuccess("删除成功");
                    this.getList();
                }).catch(error => {
                    this.$modal.closeLoading();
                });
            } 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 => deleteInst(id));
                    return Promise.all(deletePromises);
                }).then(response => {
                    this.$modal.closeLoading();
                    this.$modal.msgSuccess("删除成功");
                    this.getList();
                }).catch(error => {
                    this.$modal.closeLoading();
                });
            }
        }


    }
}
</script>

<style scoped></style>
