<template>
<a-locale-provider :locale="zh_CN">
  <a-layout id="SubLayout">
    <a-layout-sider v-model="collapsed" :trigger="null" breakpoint="lg" collapsible>
      <div id="logo" @click="showLogoConfigFormModal()" style="cursor: pointer;">
        <!-- <img class="logo-img" :src="logoConfig.logoImg" alt="" /> -->
        <img v-if="!!logoConfig.logoImg" class="logo-img" :src="logoConfig.logoImg" alt="" />
        <img v-else class="logo-img">
        <span v-show="!collapsed" class="logo-title" >{{logoConfig.logoName}}</span>
      </div>
      <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="collapsed = !collapsed" />
          <NavBar  class="navbar"/>
        </div>
        <div>
          <!-- <a-badge :count="0" showZero><a><a-icon type="bell" /></a></a-badge> -->
          <a-dropdown class="navdropmenu" style="margin-right:20px;">
            <span>
              <a-icon type="user" />
              <span class="name">{{username}}</span>
              <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="layout-content">
        <!-- 子项目在此加载 -->
        <div v-if="content" id="contentView" v-html="content" />
        <template v-else>
          <!-- 传统子项目在iframe中渲染 -->
          <iframe v-if="webviewSrc" :src="webviewSrc" frameborder="0" style="width:100%;height:96%;overflow:hidden;" />
          <!-- 本项目的子页面在此渲染 -->
          <router-view v-else :key="$route.path" />
        </template>

        <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-content>
    </a-layout>
  </a-layout>
</a-locale-provider>
</template>
<script>
import {mapState} from 'vuex'
import SideMenu from './sidemenu'
import NavBar from './navbar'
import zh_CN from 'ant-design-vue/lib/locale-provider/zh_CN'
import ChangePassword from '@/views/personal/changePassword'
import { permission, } from '@/util/mixins'

export default {
  mixins: [ permission, ],

  name: 'Layout',
  components: {
    SideMenu,
    NavBar,
    ChangePassword,
  },
  computed: {
    showChangePwd(){
      return this.isShowChangePwd
    },
    ...mapState([
      'content',
      'webviewSrc',
    ])
  }, 
  // mounted() {
  //   console.log('layout', this.content)
    
  // },
  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
    }, 
    $route(to, from) {  
      if( to.meta.openMode && (to.meta.openMode=='child') ){
        const astore = JSON.parse(sessionStorage.getItem('VuexStore')) 
        if (astore) astore.content = '' 
        sessionStorage.setItem('VuexStore', JSON.stringify(astore))
      } 
    },
  }, 
  created(){ 
    this.getLogo()  
    this.getInfo()
  },
  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
    //     if(!res.data || !res.data.content){
    //       userInfo = {}
    //       name = '' 
    //     }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)  
          
    //     }

    //   })
    // },
    getLogo(){
      this.$ajax.get({
        url: this.$api.GET_PROJECT,
      }).then(res => {  
        if (res.code==200) {
          const logConfig = this.$com.confirm(res, 'data.content', {})
          this.logoConfig.logoName = !logConfig.prjName?'':logConfig.prjName
          // this.logoConfig.logoImg = !logConfig.titleImg?'':logConfig.titleImg
          this.logoConfig.logoImg = !!logConfig?logConfig.titleImg:''
          this.logoConfigDatas.previewImage = this.logoConfig.logoImg
          document.title = this.logoConfig.logoName
        }
      })
    },
    handleClick({key}) {
      if (key == 1) {
        this.$router.push({path: '/person'})
      }
      if (key == 2) {
        this.$cookie.remove('token')
        this.$router.push({path: '/login'})
      }
    },
    handleSubmitLogoConfig() {
      this.prjConfigForm.validateFields((err) => {
        if (!err) {
          const 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
              const 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() {
      this.previewVisible = true
    },
    handleRemove() {
      this.fileList = []
    },
    beforeUpload(file) {
      const fileNameArr = file.name.split('.')
      const fileSuffix = fileNameArr[fileNameArr.length-1].toLowerCase()
      const isAccept = this.$com.oneOf(fileSuffix, this.fileUpload.acceptTypesArray)
      const 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) {
      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') {
          const data = this.$com.confirm(res, 'data.content', {})
          this.logoConfigDatas.file = !data.titleImg?'':data.titleImg
          this.logoConfigDatas.previewImage = !data.titleImg?'':data.titleImg
          this.fileList = []
        }
      })
    },  
    showLogoConfigFormModal() {
      this.logoConfigDatas.isDelImg = false
      this.logoConfigFormvisible = true
      this.$nextTick(function () {
        this.prjConfigForm.setFieldsValue({ prjName: this.logoConfig.logoName})
      })
    },
  },
}
</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:23px 16px 0 0}
#Header .navbar {float: left; line-height: 20px; margin-top:22px}
#Header .navdropmenu{float: right;}

#SubLayout .layout-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%} */
 
#contentView {
  width: 100%;
  height: 100%;
}
#contentView > div {
  width: 100%;
  height: 100%;
}
</style> 

