<template>
  <div style="height: 100%">
    <el-container style="height: 100%; border: 1px solid #eee">
      <el-aside :width="menuWith" style="background-color: rgb(238, 241, 246)">
        <el-scrollbar style="width: 100%">
          <el-menu
            :collapse="isCollapse"
            class="el-menu-vertical-demo"
            background-color="#545c64"
            text-color="#fff"
            active-text-color="#66b1ff">
            <i v-if="isCollapse" @click="handleOpen" class="hideIcon el-icon-s-unfold"></i>
            <i v-else @click="handleClose" class="hideIcon el-icon-s-fold"></i>
            <el-submenu v-for="(item,index) in menu" :key="item.id" :index="item.id">
              <template slot="title">
                <i :class="item.iconImg"></i>
                <span>{{ item.name }}</span>
              </template>
              <div v-for="(it,index) in item.child" :key="it.id">
                <el-menu-item v-if="it.child.length === 0" :index="it.id">{{ it.name }}</el-menu-item>
                <el-submenu v-else v-for="itChild in it.child" :key="itChild.id" :index="it.id">
                  <template slot="title">{{ it.name }}</template>
                  <el-menu-item :index="itChild.id">{{ itChild.name }}</el-menu-item>
                </el-submenu>
              </div>
            </el-submenu>
          </el-menu>
        </el-scrollbar>
      </el-aside>

      <!-- 系统头部 -->
      <el-container>
        <el-header style="text-align: right; font-size: 12px;background-color: #a9b3a9">
          <el-dropdown>
            <div style="margin-top: 5px">
              <el-avatar :size="50" class="imgTitle">
                <img :src="avatarURL"/>
              </el-avatar>
              <span class="nameClass">
                {{ userInfo.name }}
              </span>
            </div>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="editAvatar">修改头像</el-dropdown-item>
              <el-dropdown-item @click.native="updatePwd">修改密码</el-dropdown-item>
              <el-dropdown-item @click.native="updateUserInfo">修改用户信息</el-dropdown-item>
              <el-dropdown-item @click.native="loginOut">登出系统</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-header>
        <el-main>
          <router-view/>
        </el-main>
      </el-container>
    </el-container>

    <!-- 修改头像模态框 -->
    <el-dialog title="修改头像" :visible.sync="editAvatarDialog" width="30%">
      <el-row type="flex" justify="center">
        <div class="cropper">
          <vueCropper
            ref="cropper"
            :img="option.img"
            :outputSize="option.size"
            :outputType="option.outputType"
            :info="option.info"
            :full="option.full"
            :canMove="option.canMove"
            :canMoveBox="option.canMoveBox"
            :original="option.original"
            :autoCrop="option.autoCrop"
            :autoCropWidth="option.autoCropWidth"
            :autoCropHeight="option.autoCropHeight"
            :fixedBox="option.fixedBox"
            @realTime="realTime"></vueCropper>
        </div>
        <div class="previewBox">
          <div :style="previews.div" class="preview">
            <img :src="previews.url" :style="previews.img">
          </div>
          <el-row type="flex" justify="center">
            <el-upload
              action=""
              :show-file-list="false"
              :auto-upload="false"
              :on-change="uploadImg">
              <el-button size="mini" type="primary">更换头像</el-button>
            </el-upload>
          </el-row>
          <br>
          <el-row>
            <el-button icon="el-icon-plus" circle size="mini"
                       @click="changeScale(1)"></el-button>
            <el-button icon="el-icon-minus" circle size="mini"
                       @click="changeScale(-1)"></el-button>
            <el-button icon="el-icon-download" circle size="mini"
                       @click="down('blob')"></el-button>
            <el-button icon="el-icon-refresh-left" circle size="mini"
                       @click="rotateLeft"></el-button>
            <el-button icon="el-icon-refresh-right" circle size="mini"
                       @click="rotateRight"></el-button>
          </el-row>
        </div>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveEditAvatar">确 定</el-button>
        <el-button @click="editAvatarDialog = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 密码模态框 -->
    <el-dialog
      title="修改密码"
      :closeOnClickModal="pwdCloseOnClickModal"
      :visible.sync="pwdAddAndEditDialogFormVisible"
      :before-close="pwdAddAndEditClose" width="30%">
      <el-form ref="pwdEditElForm" :model="pwdFormData" class="form">
        <el-form-item prop="oldPassword" label="旧密码：" :label-width="formLabelWidth">
          <el-input v-model="pwdFormData.oldPassword" placeholder="请输入旧密码" style="width:90%" show-password
                    clearable autosize></el-input>
        </el-form-item>
        <el-form-item prop="password" label="新密码：" :label-width="formLabelWidth">
          <el-input v-model="pwdFormData.password" placeholder="请输入新密码" style="width:90%" show-password
                    clearable autosize></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPwd">确 定</el-button>
        <el-button @click="pwdAddAndEditDialogFormVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 用户信息模态框 -->
    <el-dialog
      :title="title"
      :closeOnClickModal="closeOnClickModal"
      :visible.sync="addAndEditDialogFormVisible"
      :before-close="handleDialogClose" width="30%">
      <el-form ref="addAndEditElForm" :model="addAndEditFormData" class="form">
        <el-form-item prop="name" label="用户名：" :label-width="formLabelWidth">
          <el-input v-model="addAndEditFormData.name" placeholder="请输入用户名" style="width:90%" type="text" clearable
                    autosize></el-input>
        </el-form-item>
        <el-form-item prop="classId" label="班级：" :label-width="formLabelWidth">
          <el-select v-model="addAndEditFormData.classId" placeholder="请选择班级" style="width:90%" clearable autosize>
            <el-option v-for="item in classIds" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="idCard" label="身份证号：" :label-width="formLabelWidth">
          <el-input v-model="addAndEditFormData.idCard" placeholder="请输入身份证号" style="width:90%" type="number" min="0"
                    clearable autosize></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="电话：" :label-width="formLabelWidth">
          <el-input v-model="addAndEditFormData.phone" placeholder="请输入电话" style="width:90%" type="number" min="0"
                    clearable autosize></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleConfirmEvent('addAndEditElForm')">确 定</el-button>
        <el-button @click="handleDialogClose">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {VueCropper} from 'vue-cropper'

  export default {
    name: 'manager',
    components: {VueCropper},
    data() {
      return {
        userInfo: [],
        stu: [],
        tableData: [],
        isCollapse: true,
        menuWith: '64px',
        // 模态框相关
        title: '',
        closeOnClickModal: false,
        addAndEditDialogFormVisible: false,
        addAndEditFormData: {
          name: '',
          classId: '',
          oldPassword: '',
          password: '',
          phone: '',
          idCard: ''
        },
        formLabelWidth: '120px',
        classIds: [],
        // 菜单数组
        menu: [],
        // 修改密码相关
        pwdFormData: {
          oldPassword: '',
          password: ''
        },
        pwdCloseOnClickModal: false,
        pwdAddAndEditDialogFormVisible: false,

        // 头像相关参数
        avatarURL: require("@/assets/img/w1.png"),
        editAvatarDialog: false,
        previews: {},
        option: {
          img: '', // 裁剪图片的地址
          info: true, // 裁剪框的大小信息
          outputSize: 1, // 剪切后的图片质量（0.1-1）
          full: true, // 输出原图比例截图 props名full
          outputType: 'png', // 裁剪生成额图片的格式
          canMove: true,  // 能否拖动图片
          original: false,  // 上传图片是否显示原始宽高
          canMoveBox: true,  // 能否拖动截图框
          autoCrop: true, // 是否默认生成截图框
          autoCropWidth: 100,
          autoCropHeight: 100,
          fixedBox: true // 截图框固定大小
        },
      }
    },
    created() {
      this.init();
    },
    methods: {
      init() {
        // 从vuex中获取用户信息，找不到去本地缓存中找
        let userInfo = this.$store.state.userInfo;
        if (userInfo === null) {
          let item = localStorage.getItem("userInfo");
          userInfo = JSON.parse(item);
        }
        this.userInfo = userInfo;
        // 获取菜单
        let routes = this.$store.state.routes;
        if (routes.length === 0) {
          let item = localStorage.getItem("routers");
          if (item === undefined) {
            this.api.getApi('/menu/get/treeMenu').then(res => {
              if (res.data !== undefined) {
                this.menu = res.data;
                this.$store.commit("initRoutes", res.data);
              }
            })
          } else {
            this.menu = JSON.parse(item);
          }
        } else {
          this.menu = this.$store.state.routes;
        }
      },

      // 点开菜单
      handleOpen() {
        this.isCollapse = false
        this.menuWith = '218px';
      },

      // 关闭菜单
      handleClose() {
        this.isCollapse = true
        // 这里为了解决背景灰色框执行太快，体验不好问题
        setTimeout(() => {
          this.menuWith = '64px';
        }, 250);
      },

      // 修改用户头像
      editAvatar() {
        this.editAvatarDialog = true
        this.option.img = this.avatarURL
      },

      // 修改用户密码
      updatePwd() {
        this.pwdAddAndEditDialogFormVisible = true;
      },

      // 提交修改的密码
      submitPwd() {
        let param = {
          id: this.userInfo.id,
          oldPwd: this.pwdFormData.oldPassword,
          newPwd: this.pwdFormData.password
        }
        this.api.getApi("/updatePwd", param).then(e => {
          console.log(e);
        })
      },

      // 关闭密码弹框
      pwdAddAndEditClose() {
        this.pwdAddAndEditDialogFormVisible = false;
      },

      // 修改用户信息
      updateUserInfo() {
        // 查找班级信息
        this.api.getApi("/stu/class/get/treeData").then(e => {
          this.classIds = e.data;
        })
        this.title = "修改用户信息";
        this.addAndEditDialogFormVisible = true;
        this.$set(this.addAndEditFormData, 'name', this.userInfo.name);
        this.$set(this.addAndEditFormData, 'classId', this.userInfo.classId);
        this.$set(this.addAndEditFormData, 'phone', this.userInfo.phone);
        this.$set(this.addAndEditFormData, 'idCard', this.userInfo.idCard);
      },

      // 提交修改的用户信息
      handleConfirmEvent() {
        this.addAndEditDialogFormVisible = false;
        let parma = this.addAndEditFormData;
        this.api.postApi("/manager/stu/update", parma).then(res => {

        });


      },

      // 取消提交修改的用户信息
      handleDialogClose() {
        this.addAndEditDialogFormVisible = false;
      },

      // 退出系统
      loginOut() {
        this.api.getApi("/logout").then(e => {
          if (e.data.code === 200) {
            this.$store.commit("removeState")
            this.$router.push("/login");
            localStorage.removeItem("Authorization");
          }
        });
      },

      /**用户头像相关方法*/
      // 保存头像修改
      saveEditAvatar() {
        this.editAvatarDialog = false
        this.finish('blob')
      },
      // 放大/缩小
      changeScale(num) {
        num = num || 1;
        this.$refs.cropper.changeScale(num);
      },
      // 左旋转
      rotateLeft() {
        this.$refs.cropper.rotateLeft();
      },
      // 右旋转
      rotateRight() {
        this.$refs.cropper.rotateRight();
      },
      // 保存上传图片
      finish(type) {
        if (type === 'blob') {
          this.$refs.cropper.getCropBlob((data) => {
            this.avatarURL = window.URL.createObjectURL(data)
            // todo 访问接口保存到数据库写这儿!


          })
        } else {
          this.$refs.cropper.getCropData((data) => {
            // todo 访问接口保存到数据库写这儿!


          })
        }
      },
      // 实时预览函数
      realTime(data) {
        this.previews = data
      },
      // 下载图片
      down(type) {
        var aLink = document.createElement('a')
        aLink.download = 'author-img'
        if (type === 'blob') {
          this.$refs.cropper.getCropBlob((data) => {
            aLink.href = window.URL.createObjectURL(data)
            aLink.click()
          })
        } else {
          this.$refs.cropper.getCropData((data) => {
            aLink.href = data;
            aLink.click()
          })
        }
      },
      // 更换头像--上传本地图片
      uploadImg(file) {
        var _this = this;
        var reader = new FileReader();
        reader.onload = (e) => {
          let data;
          if (typeof e.target.result === 'object') {
            // 把Array Buffer转化为blob 如果是base64不需要
            data = window.URL.createObjectURL(new Blob([e.target.result]))
          } else {
            data = e.target.result
          }
          _this.option.img = data
        }
        reader.readAsArrayBuffer(file.raw);
      },
    }
  }
</script>

<style scoped>
  .el-menu-vertical-demo:not(.el-menu--collapse) {
    width: 200px;
    min-height: 400px;
  }

  .nameClass {
    color: #133cce;
    float: right;
    margin-top: 15px;
    margin-left: 8px;
    font-family: '微软雅黑 Light', sans-serif;
    font-size: 18px;
  }

  .hideIcon {
    font-size: 30px;
    color: #e7efee;
    margin: 10px 35%;
  }

  .imgTitle {
    /*margin-top: 6px;*/
  }

  /*用户头像修改*/
  .previewBox {
    text-align: center;
    margin-left: 60px;
  }

  .preview {
    width: 150px;
    height: 150px;
    margin: 0px auto 20px auto;
    border-radius: 50%;
    border: 1px solid #ccc;
    background-color: #ccc;
    overflow: hidden;
  }

  .cropper {
    width: 260px;
    height: 260px;
  }
</style>
