<template>
    <el-container class="wrapper">
        <el-scrollbar
            class="container-left"
            wrap-class="container-left-wrap"
            :class="{ 'slide-hide': isCollapse, 'slide-in-left': menuShow }"
        >
            <div class="logo">
                <!--图片logo-->
                <img
                    alt="element-logo"
                    style="width: 100px; height: 100px; margin: 15px 15px 0px 15px"
                    src="../../assets/logo.png"
                />
                <!--文字logo-->
                <span>医院供应商自助平台</span>
            </div>
            <el-menu
                class="menu"
                :default-active="onRoutes"
                :collapse="isCollapse"
                style="border: none"
                text-color="#696969"
                background-color="#F5F5F5"
                active-text-color="#B22222"
                unique-opened
                router
            >
                <sidebar-item
                    v-for="item in routers"
                    :key="item.path"
                    :item="item"
                ></sidebar-item>
            </el-menu>
        </el-scrollbar>
        <el-container
            class="container-box"
            v-bind:class="{ 'slide-hide': isCollapse, 'slide-in-left': menuShow }"
        >
            <el-header class="header">
                <div class="header-left">
                    <div
                        class="header-toggle"
                        @click="
                            menuShow = !menuShow;
                            showSideBar();
                            ">
                        <span></span>
                        <span></span>
                        <span></span>
                    </div>
                    <div
                        class="slide-toggle"
                        :class="{ 'slide-toggle-open': isCollapse }"
                        @click="toggleSideBar"
                    >
                        <span></span>
                        <span></span>
                        <span></span>
                    </div>
                </div>
                <div class="header-tabs-box">
                    <el-breadcrumb class="app-levelbar" separator="/">
                        <el-breadcrumb-item v-for="item in levelList" :key="item.path">
                            <span>{{ item.name }}</span>
                            <router-link>{{ item.name }}</router-link>
                        </el-breadcrumb-item>
                    </el-breadcrumb>
                    <!--                    <tags-view  />-->
                    <!--                    <el-card>-->
                    <!--                        <div class="header-tabs">-->
                    <!--                            <tabs-view v-on:listenChildParentMenuHide="menuShow = false"></tabs-view>-->
                    <!--                        </div>-->
                    <!--                    </el-card>-->

                </div>
                <div class="header-right">
                    <div>
                        <h3>
                    <span style=" margin-top: 2px ;
                          font-weight: bold;color: #303133;">{{ hospitalName }}</span>

                            <span
                                style="margin-top: 2px;margin-right: 18px;color: #2d8cf0;font-size: 12px;">({{
                                    curInv
                                }})</span>
                        </h3>
                    </div>

                    <el-dropdown trigger="click">
                        <!--<i class="el-icon-setting" style="margin-right: 15px"></i>-->
                        <div>
                            <span style=" font-size: 14px;
    font-weight: bold;
    color: #303133;">{{ title }}<i class="el-icon-arrow-down el-icon--right"></i></span>
                        </div>

                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item><span @click="changeInv">切换仓库</span></el-dropdown-item>
                            <el-dropdown-item><span @click="handlePassword">修改密码</span></el-dropdown-item>
                            <el-dropdown-item><span @click="loginOut">退出登录</span></el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </div>

                <!--新增界面-->
                <el-dialog
                    title="修改密码"
                    :close-on-click-modal="false"
                    :close-on-press-escape="false"
                    :visible.sync="passwordFormVisible"
                    width="85%"
                    top="5vh"
                >
                    <el-form
                        :model="passwordFormData"
                        :rules="passwordFormDataRules"
                        ref="passwordFormData"
                    >
                        <el-form-item label="原始密码" prop="oldPassword">
                            <el-input
                                type="password"
                                v-model="passwordFormData.oldPassword"
                                auto-complete="off"
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="新密码" prop="newPassword">
                            <el-input
                                type="password"
                                v-model="passwordFormData.newPassword"
                                auto-complete="off"
                            ></el-input>
                        </el-form-item>
                        <el-form-item label="确认密码" prop="check_new_password">
                            <el-input
                                type="password"
                                v-model="passwordFormData.check_new_password"
                                auto-complete="off"
                            ></el-input>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button
                            @click.native="passwordFormVisible = !passwordFormVisible"
                        >取消
                        </el-button
                        >
                        <el-button
                            type="primary"
                            @click.native="addSubmit('passwordFormData')"
                            :loading="passwordLoading"
                        >提交
                        </el-button
                        >
                    </div>
                </el-dialog>
            </el-header>
            <!--遮板-->
            <div
                class="main-mask"
                v-show="menuShow"
                @click="menuShow = !menuShow"
            ></div>

            <el-main class="main">
                <div class="content-box" :class="{ 'content-collapse': collapse }">
                    <v-tags>标签</v-tags>
                    <div class="content">
                        <transition name="move" mode="out-in">
                            <keep-alive :include="tagsList">
                                <router-view></router-view>
                            </keep-alive>
                        </transition>
                        <el-backtop target=".content"></el-backtop>
                    </div>
                </div>
            </el-main>
            <!--            <div-->
            <!--                style="-->
            <!--          position: absolute;-->
            <!--          bottom: 0;-->
            <!--          left: 50%;-->
            <!--          transform: translate(-50%, -50%);-->
            <!--        "-->
            <!--            >-->
            <!--                <a-->
            <!--                    href="http://www.beian.gov.cn/portal/registerSystemInfo"-->
            <!--                    style="color: #000000; font-size: 12px"-->
            <!--                >-->
            <!--                    技术支持：厦门高立新鹏软件科技有限公司&nbsp; &nbsp;闽公网安备35020302034269号&nbsp;-->
            <!--                </a>-->
            <!--                <a-->
            <!--                    href="http://beian.miit.gov.cn"-->
            <!--                    style="color: #000000; font-size: 10px"-->
            <!--                >闽ICP备17019234号</a-->
            <!--                >-->
            <!--            </div>-->
        </el-container>
        <el-dialog
            :title="selectMap[isSup]"
            :visible.sync="selInvVisible"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="40%"
            v-if="selInvVisible"
        >
            <el-form :model="userInfo">
                <el-row :gutter="20">

                    <el-col :span="4">
                        <div class="ao-text">
                            <span>仓库：</span>
                        </div>
                    </el-col>

                    <el-col :span="16">
                        <el-form-item prop="locStorageCode">
                            <el-select v-model="userInfo.locInvCode" placeholder="仓库信息" clearable
                                       @change="locCHange"
                            >
                                <el-option
                                    v-for="item in storageList"
                                    :key="item.name"
                                    :label="item.name"
                                    :value="item.code">
                                    <span style="float: left">{{ item.name }}</span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="4">
                        <div class="ao-text">
                            <span>分库：</span>
                        </div>
                    </el-col>
                    <el-col :span="16">
                        <el-form-item prop="locInvCode">
                            <el-select v-model="userInfo.locSubInvCode" placeholder="分库信息" clearable
                            >
                                <el-option

                                    v-for="item in subInvList"
                                    :key="item.name"
                                    :label="item.name"
                                    :value="item.code">
                                    <span style="float: left">{{ item.name }}</span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <div style="margin-top: 8px ;  color: #F71616;">
                    <span>提示：进入系统前请选择您默认所在仓库与分库&nbsp;</span>
                </div>
                <div style='text-align: center; margin-bottom: 10px;margin-top: 18px ;'>
                    <el-button type="primary" @click="submitInv" style="width: 150px">提交</el-button>
                    <!--                    <el-button type="primary" @click="closeDialog">取消</el-button>-->
                </div>
            </el-form>
        </el-dialog>
    </el-container>
</template>


<script>
import {mapGetters} from "vuex";
import SidebarItem from "./SidebarItem.vue";
import {password, userInfo} from "../../api/auth/login";
import {getAdminId} from "../../utils/auth";
import {getCompany} from "../../api/warehouse/company";
import vTags from "../components/Tags";
import bus from "./bus";
import store from "../../store/index";
import {filterAllByUser} from "@/api/basic/invWarehouse";
import {filterSubByInv} from "@/api/basic/invSubWarehouse";
import {updateInv} from "@/api/auth/authAdmin";
import {RECEIVE_LOCINVCODE} from "@/store/mutation-types";
import * as types from "../../store/mutation-types";
import axios from "axios";

export default {
    data() {
        let validatePass = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请输入密码"));
            } else {
                if (this.passwordFormData.check_new_password !== "") {
                    this.$refs.passwordFormData.validateField("check_new_password");
                }
                callback();
            }
        };
        let validatePass2 = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请再次输入密码"));
            } else if (value !== this.passwordFormData.newPassword) {
                callback(new Error("两次输入密码不一致!"));
            } else {
                callback();
            }
        };
        return {
            tagsList: [],
            collapse: false,
            menuShow: false,
            levelList: null,
            passwordLoading: false,
            passwordFormVisible: false,
            company: "",
            passwordFormData: {
                oldPassword: "",
                newPassword: "",
                check_new_password: "",
            },
            employName: "",
            name: "",
            passwordFormDataRules: {
                oldPassword: [
                    {
                        required: true,
                        message: "请输入原始密码",
                        trigger: "blur",
                    },
                ],
                newPassword: [
                    {
                        required: true,
                        message: "请输入新密码",
                        trigger: "blur",
                    },
                    {validator: validatePass, trigger: "blur"},
                ],
                check_new_password: [
                    {
                        required: true,
                        message: "请再次输入密码",
                        trigger: "blur",
                    },
                    {validator: validatePass2, trigger: "blur"},
                ],
            },
            userInfo: {},
            storageList: [],
            subInvList: [],
            selInvVisible: false,
            locInvName: "",
            locSubInvName: "",
            title: "",
            curInv: "",
            hospitalName: "",
            isSup: false,
            selectMap: {
                true: "请选择送货仓库和分库",
                false: "请选择当前仓库和分库",
            },
        };
    },
    components: {
        SidebarItem,
        vTags,

    },
    computed: {
        ...mapGetters({
            routers: "routers",
        }),
        onRoutes() {
            return this.$route.path;
        },
        username() {
            return this.$store.state.admin.employeeName + "（" + this.$store.getters.locInvName + "  " + this.$store.getters.locSubInvName + "）";
        },
        isCollapse() {
            return false;
        },
    },
    mounted() {
    },
    methods: {
        toggleSideBar() {
            this.$store.dispatch("ToggleSideBar");
        },
        showSideBar() {
            this.$store.dispatch("ShowSideBar");
        },
        getBreadcrumb() {
            let matched = this.$route.matched.filter((item) => item.name);
            const first = matched[0];
            if (first && (first.name !== "首页" || first.path !== "")) {
                matched = [{name: "首页", path: "/"}].concat(matched);
            }
            this.levelList = matched;
        },
        loginOut() {
            this.$confirm("此操作将退出系统, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    this.$store.dispatch("loginOut").then(() => {
                        location.reload(); // 为了重新实例化vue-router对象 避免bug
                    });
                })
                .catch(() => {
                    // this.$message({
                    //     type: "error",
                    //     message: "操作失败",
                    // });
                });
        },
        getCompanyData() {
            this.loading = true;
            let tquery = {
                customerId: store.getters.customerId,
            };
            getCompany(tquery).then((response) => {
                this.loading = false;
                this.company = response.data;
            });
        },
        getStorage() {
            this.storageList = [];
            filterAllByUser()
                .then((response) => {
                    if (response.code == 20000) {
                        this.storageList = response.data || [];
                        if (this.storageList != null && this.storageList.length == 1) {
                            this.userInfo.locInvCode = this.storageList[0].code;
                        }
                        this.findSubInvByInv();
                    }

                })
                .catch(() => {
                });
        },

        locCHange() {

            if (this.$isNotBlank(this.userInfo.locSubInvCode)) {
                this.userInfo.locSubInvCode = "";
            }
            this.findSubInvByInv();
        },

        findSubInvByInv() {
            this.subInvList = [];
            let query = {
                pcode: this.userInfo.locInvCode
            };
            filterSubByInv(query)
                .then((response) => {
                    this.subInvList = response.data || [];
                    if (this.subInvList != null && this.subInvList.length == 1) {
                        this.userInfo.locSubInvCode = this.subInvList[0].code;
                    }
                })
                .catch(() => {
                });
        },
        getUserInfo() {
            userInfo()
                .then((response) => {
                    if (response.code == 20000) {
                        this.userInfo = response.data;
                        this.curInv = "仓库:" + this.userInfo.locInvName + ";  分库:" + this.userInfo.locSubInvName + "  ";
                        this.title = this.userInfo.employeeName + "（" + this.userInfo.userName + "）";
                        if (this.userInfo.customerId == 110) {
                            this.isSup = false;
                        } else {
                            this.isSup = true;
                        }


                        if (this.$isBlank(this.userInfo.locInvCode) || this.$isBlank(this.userInfo.locSubInvCode)) {
                            this.selInvVisible = true;
                        } else {
                            this.$store.commit(types.RECEIVE_LOCINVCODE, this.userInfo.locInvCode);
                            this.$store.commit(types.RECEIVE_LOCSUBINVCODE, this.userInfo.locSubInvCode);
                            this.$store.commit(types.RECEIVE_LOCINVNAME, this.locInvName);
                            this.$store.commit(types.RECEIVE_LOCSUBINVNAME, this.locSubInvName);

                        }
                        this.getStorage();
                    }
                })
                .catch(() => {
                    this.customerId = "";
                });
        },


        // 显示修改密码界面
        handlePassword() {
            this.passwordFormVisible = true;
            this.passwordFormData = {
                oldPassword: "",
                newPassword: "",
                check_new_password: "",
            };
        },

        submitInv() {

            if (this.$isBlank(this.userInfo.locInvCode)) {
                this.$message.error("仓库不能为空！");
                return;
            }
            if (this.$isBlank(this.userInfo.locSubInvCode)) {
                this.$message.error("分库不能为空！");
                return;
            }
            updateInv(this.userInfo).then((res) => {
                if (res.code == 20000) {
                    this.$message.success("设置成功!");
                    this.selInvVisible = false;
                    this.getUserInfo();
                } else {
                    this.$message.error(res.message);
                }


            }).catch(() => {
                this.selInvVisible = false;
            });
        },

        closeDialog() {
            this.selInvVisible = false;
        },


        addSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.passwordLoading = true;
                    let data = Object.assign({}, this.passwordFormData);
                    data.adminId = getAdminId();
                    password(data)
                        .then((res) => {
                            this.passwordLoading = false;
                            if (res.code !== 20000) {
                                this.$message({
                                    message: res.message,
                                    type: "error",
                                });
                            } else {
                                this.$message({
                                    message: "修改成功",
                                    type: "success",
                                });
                                // 刷新表单
                                this.$refs["passwordFormData"].resetFields();
                                this.passwordFormVisible = false;
                                this.$store.dispatch("loginOut").then(() => {
                                    location.reload(); // 为了重新实例化vue-router对象 避免bug
                                });
                            }
                        })
                        .catch(() => {
                            // this.$message({
                            //     type: "error",
                            //     message: "操作失败",
                            // });
                        });
                }
            });
        },
        changeInv() {
            this.selInvVisible = true;
            userInfo().then((res) => {
                if (res.code === 20000) {
                    this.userInfo = res.data;
                }
            }).catch((error) => {
            });
        },
    },
    created() {
        this.getBreadcrumb();
        this.getCompanyData();
        // this.getStorage();
        // this.findSubInvByInv();
        this.getUserInfo();
        bus.$on("collapse-content", (msg) => {
            this.collapse = msg;
        });

        // 只有在标签页列表里的页面才使用keep-alive，即关闭标签之后就不保存到内存中了。
        bus.$on("tags", (msg) => {
            let arr = [];
            for (let i = 0, len = msg.length; i < len; i++) {
                msg[i].name && arr.push(msg[i].name);
            }
            this.tagsList = arr;
        });

        axios.get("./config.json").then(res => {
            // 基础地址
            this.hospitalName = res.data.hosp_name;
        });

    },
    watch: {
        $route() {
            this.getBreadcrumb();
        },
    },
};
</script>

<style type="text/scss" lang="scss">
@import "../../styles/mixin";

.el-header {
    /*background-color: #eef1f6;*/
    color: #333;
    padding: 0 10px;
}

.el-aside {
    color: #333;
}

.el-main {
    position: relative;
    padding: 0 10px 10px;
    background-color: #fff;
    margin-left: 7px;
    margin-top: 5px;
}

.main-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 200%;
    z-index: 100;
    background-color: #000;
    opacity: 0.3;
}

.move-enter-active,
.move-leave-active {
    transition: opacity 0.5s;
}

.move-enter,
.move-leave {
    opacity: 0;
}

.wrapper {
    height: 100%;
    overflow-y: hidden;
    background-color: #f5f7f9;
}

.container-box {
    height: 100%;
    transition: -webkit-transform 0.3s ease-in-out;
    transition: transform 0.3s ease-in-out, -webkit-transform 0.3s ease-in-out;
    overflow-y: auto;
}

.container-left {
    background-color: #f5f5f5;
    transition: left 0.23s ease-in-out;
    height: 100%;
    flex: 0 0 auto;
}

.container-left-wrap {
    overflow-x: hidden !important;
}

.container-left .svg-icon {
    font-size: 20px;
    margin-right: 5px;
}

.container-left:not(.slide-hide) {
    width: 200px;
}

.container-left.slide-hide {
    .logo img {
        display: none;
    }

    .logo span {
        display: inline-block;
    }
}

.menu {
    width: 100% !important;
}

/*.menu::-webkit-scrollbar{*/
/*display: none;*/
/*}*/

.header {
    position: relative;
    text-align: left;
    font-size: 12px;
    line-height: $header-height;
    border-bottom: 1px solid #d8dce5;
    background-color: #fff;
}

.logo {
    display: block;
    width: 100%;
    line-height: 80px;
    text-align: center;
    color: #fff;
    transition: display 0.7s ease-in-out;

    img {
        vertical-align: middle;
    }

    span {
        display: none;
    }
}

.header-left {
    display: inline-block;
    height: $header-height;
    overflow: hidden;
}

.header-tabs-box {
    display: inline-block;
    height: $header-height;
    max-width: 60%;
    overflow: hidden;
}

.header-right {
    display: flex;
    height: 100%;
    margin-left: 10px;
    float: right;

    .el-dropdown {
        display: flex;
        cursor: pointer;
    }

    span {
        display: inline-block;
        @include text-overflow;
    }

    i {
        line-height: $header-height;
        margin-top: 2px;
    }
}

.app-levelbar {
    margin-left: 20px;
    line-height: 57px !important;
}

/*宽屏时出现*/
.slide-toggle {
    display: inline-block;
    height: $header-height;
    line-height: $header-height;
    text-align: center;
    cursor: pointer;
}

.slide-toggle span {
    display: inline-block;
    width: 2px;
    height: 12px;
    background-color: rgba(135, 141, 153, 0.8);
    margin-left: 5px;
}

.slide-toggle-open span {
    display: block;
    margin-left: 4px;
    margin-top: 4px;
    width: 16px;
    height: 2px;
}

.slide-toggle-open {
    padding-top: 17px;
}

@media screen and (min-width: 768px) {
    .main-mask {
        display: none;
    }
}

/*.slide-hide {*/
/*width: 64px !important;*/
/*}*/

@media screen and (max-width: 768px) {
    .main {
        overflow-y: scroll !important;
        -webkit-overflow-scrolling: touch;
    }

    .slide-hide.slide-in-left {
        -webkit-transform: translate3d(64px, 0, 0) !important;
        transform: translate3d(64px, 0, 0) !important;
    }
    .container-left.slide-hide.slide-in-left {
        left: -64px;
        width: 64px;
    }
    .container-left.slide-in-left {
        left: 0;
    }
    .container-left {
        margin-right: 0;
        opacity: 1;
        position: absolute !important;
        top: 0;
        left: -225px;
        z-index: 10;
        padding: 0;
    }

    .container-box.slide-in-left {
        min-width: 0;
        opacity: 1;
        -webkit-transform: translate3d(187px, 0, 0);
        transform: translate3d(187px, 0, 0);
        overflow: initial;
    }
    .header-toggle {
        display: block;
        /*background-color: #26a2ff;*/
        border-radius: 4px;
        /*border: 1px solid #fff;*/
        height: 40px;
        margin: 10px 0;
        padding: 2px 6px;
        outline: none;
        width: 40px;
        z-index: 10;
    }

    .header-toggle span {
        display: block;
        width: 100%;
        height: 4px;
        margin: 5px auto;
        background-color: rgba(135, 141, 153, 0.8);
    }

    .logo {
        display: none;
    }
    .slide-toggle {
        display: none;
    }
}
</style>
