<template>
  <div :class="classObj" class="app-wrapper">
    <div class="top_container">
      <div class="content">
        <div class="logo">
          <img class="img" src="@/assets/images/default_logo.png" />
        </div>
        <div class="right-menu">
          <template v-if="device !== 'mobile'">
            <!-- <search id="header-search" class="right-menu-item" />
          <el-tooltip content="项目文档" effect="dark" placement="bottom">
            <Doc class="right-menu-item hover-effect" />
          </el-tooltip>
          <el-tooltip content="全屏缩放" effect="dark" placement="bottom">
            <screenfull id="screenfull" class="right-menu-item hover-effect" />
          </el-tooltip>
          <el-tooltip content="布局设置" effect="dark" placement="bottom">
            <size-select id="size-select" class="right-menu-item hover-effect" />
          </el-tooltip> -->

            <i class="left_icon el-icon-search" />
            <i class="left_icon el-icon-warning-outline" />
            <i class="left_icon el-icon-bell" />
          </template>
          <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="hover">
            <div class="avatar-wrapper">
              <img :src="logo || Avatar" class="user-avatar">
              <span class="shop_name">{{ shopName }}</span>
              <i class="el-icon-caret-bottom" />
            </div>
            <el-dropdown-menu slot="dropdown">
              <!-- <span style="display:block;" @click="show = true">
              <el-dropdown-item>
                布局设置
              </el-dropdown-item>
            </span> -->
              <router-link to="/shop/shop/shop_configuration">
                <el-dropdown-item>
                  店铺配置
                </el-dropdown-item>
              </router-link>
              <span @click="dialogVisible = true">
                <el-dropdown-item>
                  修改密码
                </el-dropdown-item>
              </span>
              <span style="display:block;" @click="open">
                <el-dropdown-item divided>
                  退出登录
                </el-dropdown-item>
              </span>
              <!-- <span style="display:block;" @click="goFullScreen">
                <el-dropdown-item divided>
                  全屏
                </el-dropdown-item>
              </span> -->
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <el-dialog title="修改密码" modal-append-to-body append-to-body :visible.sync="dialogVisible" width="400px">
        <el-form ref="form" :model="form" :rules="rules">
          <el-form-item label="旧密码" prop="oldPass">
            <el-input :type="ip1Type" v-model="form.oldPass" placeholder="请输入旧密码">
              <i slot="suffix"
                :class="`el-input__icon ${ip1Type == 'text' ? 'el-icon-view' : 'el-icon-remove-outline'}`"
                @click.stop="changeInputType('ip1Type')"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="新密码" prop="newPass">
            <el-input :type="ip2Type" v-model="form.newPass" placeholder="请输入新密码">
              <i slot="suffix"
                :class="`el-input__icon ${ip2Type == 'text' ? 'el-icon-view' : 'el-icon-remove-outline'}`"
                @click.stop="changeInputType('ip2Type')"></i>
            </el-input>
          </el-form-item>
          <el-form-item label="确认新密码" prop="rnewPass">
            <el-input :type="ip3Type" v-model="form.rnewPass" placeholder="请再次输入新密码">
              <i slot="suffix"
                :class="`el-input__icon ${ip3Type == 'text' ? 'el-icon-view' : 'el-icon-remove-outline'}`"
                @click.stop="changeInputType('ip3Type')"></i>
            </el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" :loading="formLoading" @click="submitHandle">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <div>
      <div v-if="device === 'mobile' && sidebar.opened" class="drawer-bg" @click="handleClickOutside" />
      <sidebar class="sidebar-container" />
      <div :class="{ hasTagsView: needTagsView }" class="main-container">
        <div :class="{ 'fixed-header': fixedHeader }">
          <navbar />
          <tags-view v-if="needTagsView" />
        </div>
        <app-main />
        <right-panel v-if="showSettings">
          <settings />
        </right-panel>
      </div>
      <!--  防止刷新后主题丢失  -->
      <Theme v-show="false" ref="theme" />
    </div>
  </div>
</template>

<script>
import RightPanel from '@/components/RightPanel'
import { AppMain, Navbar, Settings, Sidebar, TagsView } from './components'
import ResizeMixin from './mixin/ResizeHandler'
import { mapState, mapGetters } from 'vuex'
import Theme from '@/components/ThemePicker'
import Cookies from 'js-cookie'
import Avatar from '@/assets/images/avatar.png'
import { updatePass } from '@/api/login.js'
import { encrypt } from '@/utils/rsaEncrypt'
export default {
  name: 'Layout',
  components: {
    AppMain,
    Navbar,
    RightPanel,
    Settings,
    Sidebar,
    TagsView,
    Theme
  },
  mixins: [ResizeMixin],
  data() {
    const validateNewPass = (rule, value, callback) => {
      if (!this.form.newPass) {
        callback(new Error(' '))
      } else if (this.form.newPass === this.form.oldPass) {
        callback(new Error('请输入与旧密码不同的新密码'))
      } else {
        callback()
      }
    }
    const validateRnewPass = (rule, value, callback) => {
      if (!this.form.rnewPass) {
        callback(new Error(' '))
      } else if (this.form.rnewPass !== this.form.newPass) {
        callback(new Error('两次密码输入不一致'))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      Avatar: Avatar,
      logo: localStorage.getItem('logo'),
      shopName: localStorage.getItem('shopName'),
      ip1Type: 'password',
      ip2Type: 'password',
      ip3Type: 'password',
      formLoading: false,
      form: {
        oldPass: '',
        newPass: '',
        rnewPass: ''
      },
      rules: {
        oldPass: [
          {
            required: true,
            message: ' ',
            trigger: 'blur'
          }
        ],
        newPass: [
          {
            required: true,
            validator: validateNewPass,
            trigger: 'blur'
          }
        ],
        rnewPass: [
          {
            required: true,
            validator: validateRnewPass,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  computed: {
    ...mapState({
      sidebar: state => state.app.sidebar,
      device: state => state.app.device,
      showSettings: state => state.settings.showSettings,
      needTagsView: state => state.settings.tagsView,
      fixedHeader: state => state.settings.fixedHeader
    }),
    ...mapGetters([
      'sidebar',
      'device',
      'user',
      'baseApi'
    ]),
    classObj() {
      return {
        hideSidebar: !this.sidebar.opened,
        openSidebar: this.sidebar.opened,
        withoutAnimation: this.sidebar.withoutAnimation,
        mobile: this.device === 'mobile'
      }
    }
  },
  mounted() {
    if (Cookies.get('theme')) {
      this.$refs.theme.theme = Cookies.get('theme')
      this.$store.dispatch('settings/changeSetting', {
        key: 'theme',
        value: Cookies.get('theme')
      })
    }
  },
  methods: {
    // 修改密码框类型
    changeInputType(key) {
      if (this[key] == 'text') {
        this[key] = 'password'
      } else {
        this[key] = 'text'
      }
    },
    handleClickOutside() {
      this.$store.dispatch('app/closeSideBar', { withoutAnimation: false })
    },
    // 提交修改密码
    submitHandle() {
      this.$refs.form.validate(async vaild => {
        if (vaild) {
          try {
            this.formLoading = true
            const res = await updatePass({
              loginType: localStorage.getItem('loginType'),
              oldPass: encrypt(this.form.oldPass),
              newPass: this.form.newPass
            })
            this.$notify.success('修改成功，请重新登陆')
            setTimeout(() => {
              this.logout()
            }, 1000)
          } catch (error) {
            this.formLoading = false
            console.log(error);
          }
        }
      })
    },
    goFullScreen() {
      if (document.documentElement.requestFullscreen) {
        document.documentElement.requestFullscreen();
      } else if (document.documentElement.mozRequestFullScreen) { /* Firefox */
        document.documentElement.mozRequestFullScreen();
      } else if (document.documentElement.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
        document.documentElement.webkitRequestFullscreen();
      } else if (document.documentElement.msRequestFullscreen) { /* IE/Edge */
        document.documentElement.msRequestFullscreen();
      }
    },
    open() {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        localStorage.setItem('logoutHandle', true)
        this.logout()
      })
    },
    logout() {
      this.$store.dispatch('LogOut').then(() => {
        location.reload()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/mixin.scss";
@import "~@/assets/styles/variables.scss";
$top-c-h: 60px;

.top_container {
  height: $top-c-h;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10;
  background-color: #F5F5F5;

  .content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: $top-c-h - 10px;
    background-color: #fff;
    padding: 0 20px;

    .logo {
      .img {
        display: block;
        width: 123px;
        height: auto
      }
    }

    .right-menu {
      display: flex;
      align-items: center;

      .left_icon {
        font-size: 18px;
        margin-right: 30px;
      }

      &:focus {
        outline: none;
      }

      .right-menu-item {
        display: inline-block;
        padding: 0 8px;
        height: 100%;
        font-size: 18px;
        color: #5a5e66;
        vertical-align: text-bottom;

        &.hover-effect {
          cursor: pointer;
          transition: background .3s;

          &:hover {
            background: rgba(0, 0, 0, .025)
          }
        }
      }

      .avatar-container {
        display: flex;
        align-items: center;

        .avatar-wrapper {
          position: relative;
          display: flex;
          align-items: center;

          .user-avatar {
            cursor: pointer;
            width: 40px;
            height: 40px;
            border-radius: 50%;
          }

          .el-icon-caret-bottom {
            font-size: 12px;
            margin-left: 6px;
          }

          .shop_name {
            font-size: 16px;
            margin-left: 10px;
          }
        }
      }
    }
  }
}

.app-wrapper {
  @include clearfix;
  position: relative;
  height: 100%;
  width: 100%;

  &.mobile.openSidebar {
    position: fixed;
    top: 0;
  }
}

.drawer-bg {
  background: #000;
  opacity: 0.3;
  width: 100%;
  top: 0;
  height: 100%;
  position: absolute;
  z-index: 999;
}

.fixed-header {
  position: fixed;
  top: $top-c-h;
  right: 0;
  z-index: 9;
  width: calc(100% - #{$sideBarWidth});
  transition: width 0.28s;
  padding: 0;
}

.hideSidebar .fixed-header {
  width: calc(100% - 54px)
}

.mobile .fixed-header {
  width: 100%;
}
</style>
