// 整体布局文件
<template>
<a-locale-provider :locale="zh_CN">
    <a-layout id="SubLayout">
    <Loader />
    <a-layout>
      <a-layout-sider v-model="collapsed" breakpoint="lg">
        <div id="logo" @click="showLogoConfigFormModal()" style="cursor: pointer;">
          <img class="logo-img" :src="logoConfig.logoImg" alt="" >
          <span v-show="!collapsed" class="logo-title" >{{logoConfig.logoName}}</span>
        </div>
        <SideMenu :menuMode="menuMode" ></SideMenu>
      </a-layout-sider>
      <a-layout  style="overflow:hidden">
        <a-layout-header  id="Header">
          <div class="headerWrapper">
              <a-icon class="trigger"
                :type="collapsed ? 'menu-unfold' : 'menu-fold'"
                @click="toggleSideCollapsed"
              />
              <NavBar class="navbar" />
              <a-dropdown class="navdropmenu">
                <span style="color:#1890ff;cursor:pointer; "> 
                  <a-icon type="user" /> {{username}} <a-icon type="down" />
                </span>
                <a-menu slot="overlay" @click="handleClick">
                  <!-- <a-menu-item key="1">个人中心</a-menu-item> -->
                  <a-menu-item key="changePwd" @click="showChangePwdModal">修改密码</a-menu-item>
                  <a-menu-item key="2">退出登录</a-menu-item>
                </a-menu>
              </a-dropdown>
            </div>
        </a-layout-header>
        <a-layout-content class="content">
            <router-view :key="$route.path"/>
        </a-layout-content>
      </a-layout>
    </a-layout>
    <ChangePassword @on-close='closeChangePwdModal' :resetPwdShow='isShowChangePwd'></ChangePassword>

    <a-modal title="资料上传" :visible="logoConfigFormvisible" @ok="handleSubmitLogoConfig" :confirmLoading="confirmLoading" @cancel="logoConfigFormvisible = false" okText="确认" cancelText="取消">
      <a-form :form="prjConfigForm">
        <a-form-item label="项目名" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <a-input v-decorator="['prjName', { rules: [{ required: true, message: '请输入项目名!' }] }]" />
        </a-form-item>

        <a-form-item label="图片" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <img @click="previewVisible = true" :src="logoConfigDatas.previewImage" alt="" width="105" height="105"  >
          <a-upload
            listType="picture-card"
            :fileList="fileList"
            :customRequest="(data) =>{handleUpload(data,fileList)}"
            @preview="handlePreview"
            :beforeUpload="beforeUpload"
            :accept="fileUpload.acceptTypes">
            <div v-if="fileList.length < 1">
              <a-icon type="cloud-upload" />
              <div class="ant-upload-text" style="fontSize:12px">图片仅支持jpg、png、jpeg格式</div>
            </div>
          </a-upload>
            <a-button @click="delImg">删除图片</a-button>
        </a-form-item>

         <!-- <a-form-item label="项目名" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
           <a-button @click="delImg">删除图片</a-button>
         </a-form-item> -->
      </a-form>
    </a-modal>
    <a-modal :visible="previewVisible" style="text-align:center" :width="600" :footer="null" @cancel="previewVisible = false">
      <img alt="项目logo" style="width: 80%;height:auto" :src="logoConfigDatas.previewImage" />
    </a-modal>
    </a-layout>
</a-locale-provider>
</template>
<script>
import SideMenu from '@/components/Layout/sidemenu'
import NavBar from '@/components/Layout/navbar'
import Loader from '@/components/Loader/loader'
// import zh_CN from 'ant-design-vue/lib/locale-provider/zh_CN'
import { permission } from '@/util/mixins'
import ChangePassword from '@/views/personal/changePassword'

export default {
  name: 'Layout',
  components: {
    NavBar,
    Loader,
    SideMenu,
    ChangePassword,
  },
  computed: {
    menuMode() {
      return this.collapsed ? 'vertical' : 'inline'
    },
    showChangePwd(){
      return this.isShowChangePwd
    },
  },
  data(){
    return{
      isShowChangePwd: false,
      collapsed: false,
      zh_CN,
      username: '',
      logoConfig: {
        logoName: '',
        logoImg: ''
      },
      logoConfigDatas: {
        isDelImg: false,
        previewImage: '',
        file: ''
      },
      // 模态框
      logoConfigFormvisible: false,
      confirmLoading: false,
      // form
      formLayout: 'horizontal',
      prjConfigForm: this.$form.createForm(this),
      //上传
      previewVisible: false,
      fileList: [],
      fileUpload: {
        acceptTypes: '.jpg,.jpeg,.png',
        acceptTypesArray: ['jpg', 'jpeg', 'png']
      },
      postParams: {},
    }
  },
  watch: {
    '$store.state.userName': {
      handler: function(val) {
        this.username = val
      },
      deep: true
    },
  },
  methods: {
    showChangePwdModal(){
      this.isShowChangePwd = true
    },
    closeChangePwdModal(){
      this.isShowChangePwd = false
    },
    getInfo() {
      this.$ajax.get({
        url: this.$api.GET_USER_INFO,
      }).then(res => {
        // 本地存储用户基本信息 

        let userInfo = res.data.content, name, oldSysAuthCode, isAllPerm = false
        if(!res.data || !res.data.content){
          userInfo = {}
          name = ''
          oldSysAuthCode = []
        }else{
          userInfo = res.data.content
          name = userInfo.username = res.data.content.name||res.data.content.phone
          this.$store.commit('SET_USERINFO', userInfo)
          this.$cookie.set('userName', name)
          this.$store.commit('SET_USERNAME', name)
          isAllPerm = userInfo.isAllPerm
        }

      })
    },
    getLogo(){
      this.$ajax.get({
        url: this.$api.GET_PROJECT,
      }).then(res => {
        if (res.code==200) {
          let logConfig = this.$com.confirm(res, 'data.content', {})
          this.logoConfig.logoName = !logConfig.prjName?'':logConfig.prjName
          this.logoConfig.logoImg = !logConfig.titleImg?'':logConfig.titleImg
          this.logoConfigDatas.previewImage = this.logoConfig.logoImg
          document.title = this.logoConfig.logoName
        }
      })
    },
    toggleSideCollapsed(){
      this.collapsed = !this.collapsed
    },
    handleClick({key}) {
      if (key == 1) {
        this.$router.push({name: 'person'})
      }
      if (key == 2) {
        this.$cookie.remove('token')
        this.$router.replace({name: 'login'})
      }
    },
    calcBackTopTarget() {
      // 获取返回顶部按钮的dom依据
      this.$nextTick(() => {
        const dom1 = document.querySelector('.portalDetailContentBody')
        const dom2 = document.querySelector('#appContent')
        if (!dom1 && !dom2) return
        this.showBacktop = false
        this.$nextTick(() => {
          if (dom1) {
            this.backTopTarget = () => dom1
          } else {
            dom2.scrollTo(0, 0)
            this.backTopTarget = () => dom2
          }
          this.showBacktop = true
        })
      })
    },
    //
    //
    // 模态框
    showLogoConfigFormModal() {
      this.logoConfigDatas.isDelImg = false
      this.logoConfigFormvisible = true
      this.$nextTick(function () {
        this.prjConfigForm.setFieldsValue({ prjName: this.logoConfig.logoName})
      })
    },
    handleSubmitLogoConfig() {
      this.prjConfigForm.validateFields((err, values) => {
        if (!err) {
          let postParams = {
            'file': this.logoConfigDatas.file,
            'prjName': this.prjConfigForm.getFieldValue('prjName'),
            'isDelImg': this.logoConfigDatas.isDelImg,
          }
          this.$ajax.post({
            url: this.$api.POST_PROJECT,
            params: postParams,
            contentType: 'application/x-www-form-urlencoded'
          }).then(res => {
            if (res.code == '200') {
              this.logoConfigFormvisible = false
              let logConfig = this.$com.confirm(res, 'data.content', {})
              this.logoConfig.logoName = !logConfig.prjName?'':logConfig.prjName
              this.logoConfig.logoImg = !logConfig.titleImg?'':logConfig.titleImg
              this.logoConfigDatas.previewImage = this.logoConfig.logoImg
              document.title = this.logoConfig.logoName
            }else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
    delImg(){
      this.fileList = []
      this.logoConfig.logoImg = ''
      this.logoConfigDatas.previewImage = ''
      this.logoConfigDatas.isDelImg = true
    },
    handlePreview(file) {
      this.previewVisible = true
    },
    handleRemove(file) {
      this.fileList = []
    },
    beforeUpload(file) {
      let fileNameArr = file.name.split('.')
      let fileSuffix = fileNameArr[fileNameArr.length-1].toLowerCase()
      let isAccept = this.$com.oneOf(fileSuffix, this.fileUpload.acceptTypesArray)
      let isLt5M = file.size / 1024 / 1024 < 5
      let message = ''
      if(!isAccept){
        message += !isAccept?('文件格式限定为'+this.fileUpload.acceptTypes+'；'):''
      }
      if(!isLt5M){
        message += !islt200m?'一寸照需小于5M；':''
      }
      if(isAccept && isLt5M){
        return true
      }else{
        this.$modal.error({
          title: '上传文件验证未通过',
          content: message,
          okText: '确认',
          cancelText: '取消',
        })
        return false
      }
    },
    handleUpload(data, fileList) {
      const formData = new FormData()
      formData.append('file', data.file)
      data.onProgress()
      this.$ajax.post({
        url: this.$api.UPLOAD_TEMP,
        params: formData
      }).then(res => {
        if (res.code === '200') {
          let data = this.$com.confirm(res, 'data.content', {})
          this.logoConfigDatas.file = !data.titleImg?'':data.titleImg
          this.logoConfigDatas.previewImage = !data.titleImg?'':data.titleImg
          this.fileList = []
        }
      })
    },
  },
  created(){

    this.getLogo()
 
    this.getInfo() 

    /** 持久化存储vuex 使其页面刷新后数据不丢失 */
    //在页面加载时读取sessionStorage里的状态信息
    if (sessionStorage.getItem('VuexStore')) {
      this.$store.replaceState(Object.assign({}, this.$store.state, JSON.parse(sessionStorage.getItem('VuexStore'))))
    }
    //在页面刷新时将vuex里的信息保存到sessionStorage里
    window.addEventListener('beforeunload', () => {
      sessionStorage.setItem('VuexStore', JSON.stringify(this.$store.state))
    })
  }
}
</script>
<style scoped>
#Header {background:#fff; padding: 0}
</style>
<style>
#SubLayout{
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  width: 100%;
  height: 100%;
  overflow: hidden;
  overflow-x: hidden;
}
#logo { height: 64px; background: #00284e; width: 100%; text-align: left}
#logo .logo-img{   margin :12px 0px 12px 5px; display: inline-block; width: 38px; height:38px; background: url('../../assets/images/logo.png'); background-size:100%
 }
#logo .logo-title{white-space: nowrap;
overflow: hidden;
width: 100%;
text-overflow: ellipsis;color: #fff; font-size: 14px; line-height: 64px ;font-weight:700;padding-left: 0px;}

#Header .headerWrapper { padding: 0 1rem}
#Header .trigger{ float: left; font-size: 18px; line-height: 20px; margin:24px 16px 0 0}
#Header .navbar {float: left; line-height: 20px; margin-top:22px}
#Header .navdropmenu{float: right;}

#SubLayout .content{
  overflow-y: auto;
  padding: 0 0 14px 0;
  background-position: 95% 10%;
  background-size: 20%;
  height: 100%;
}
#SubLayout .contentWrapper { padding: 24px; background:#fff; min-height: 98%}
</style>
