<template>
  <div :class="classObj" class="app-wrapper">
    <div style=" width: 100%; height: 50px; background: #3F9B6A; position: fixed;top:0;left:0;z-index:1001;display: flex;flex-wrap: wrap; margin-bottom: 1px;padding:0 10px 0 20px;">
      <div style="width: 15%;margin-top: 8px;">
        <img src="../assets/images/logo2.png" alt="" style="height: 36px;width:180px; object-fit: contain;" />
      </div>
      <ul style="display: flex;flex-wrap: wrap;color: white;height: 100%;justify-content: space-around;font-size: 14px;text-align:center;">
        <li :class="index ==  ins ? 'topList':'weiList'" style="line-height: 55px;height: 100%" v-for="(item,ins) in msg" @click="clk(ins)">{{item}}</li>
      </ul>
      <div style="position: absolute;top:0px;right:50px;display: flex">
       <div style="border-radius:20px; width: 110px; height: 30px;margin-top: 11px;margin-right: 10px;background:rgba(255, 255, 255, 0.1);display: flex;flex-flow: row nowrap;justify-content: center;
       align-items: center;cursor: pointer;"  @click="gzt">
    <el-image src="https://028wlkj.cn:30021/public/static/logos/home-stable.png"  style="width90%; padding:10px 0;"></el-image>
 <!--          <img src="../../src/assets/images/home.png" alt="" style="height: 20px;object-fit: contain;width:17px;margin-right:6px;"/>
            <div style="color: #fff;line-height: 20px;font-size:14px">工作台</div> -->
        </div>

        <div class="right-menu">
          <el-dropdown
            class="avatar-container"
            trigger="click"
          >
            <div
              class="avatar-wrapper"
              style="margin-left: 20px"
            >
              <img
                :src="userAvatar"
                class="user-avatar"
              >
              <span class="user-name">{{ name }}</span>
            </div>
            <el-dropdown-menu
              slot="dropdown"
              class="user-dropdown"
            >

             <!-- <el-dropdown-item @click.native="changeHead">
                <span style="display: block">修改头像</span>
              </el-dropdown-item>
              <el-dropdown-item @click.native="changePwd">
                <span style="display: block">修改密码</span>
              </el-dropdown-item> -->

                <div
                  class="avatar-wrapper"
                  style="height:100px;padding:0 20px;display:flex;align-items:center;"
                >
                  <img
                    :src="userAvatar"
                    class="user-avatar"
                    style="width:56px;height:56px;border-radius: 50%"
                  >
                  <div class="drName" style="color:#000;font-size:16px;margin-left:20px;">{{ name }}</div>
                </div>

              <el-dropdown-item
                divided
                @click.native="logout"

              >
              <div
                  class="avatar-wrapper listTUI"
                  style="height:40px;display:flex;align-items:center;"
                >
                  <div>退出登录</div>
                </div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
<!--  修改头像  -->
    <el-dialog
      title="修改头像"
      :visible.sync="changeHeadObj.show"
      width="30%"
       :modal='false'
      :before-close="handleHeadClose"
    >
      <div class="center-content">
        <el-upload
          class="avatar-uploader"
          :data="dataObj"
          :action="action"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img
            v-if="changeHeadObj.data.image"
            :src="changeHeadObj.data.image"
            class="avatar"
            width="160"
            height="160"
          >
          <i
            v-else
            class="el-icon-plus avatar-uploader-icon"
          />
        </el-upload>
      </div>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="handleHeadClose">取 消</el-button>
        <el-button
          type="primary"
          @click="HandleChangeHeadSubmit"
        >确 定</el-button>
      </span>
    </el-dialog>
    <!--  修改密码  -->
    <el-dialog
      title="修改密码"
      :visible.sync="changePwdShow"
      width="30%"
      :before-close="handleClose"
      :modal='false'
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="密码"
          prop="password"
        >
          <el-input
            v-model="ruleForm.password"
            type="password"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="新密码"
          prop="newPassword"
        >
          <el-input
            v-model="ruleForm.newPassword"
            type="password"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item
          label="确认密码"
          prop="confirmPass"
        >
          <el-input
            v-model="ruleForm.confirmPass"
            type="password"
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="handleClose">取 消</el-button>
        <el-button
          type="primary"
          @click="confirmChangePwd"
        >确 定</el-button>
      </span>
    </el-dialog>




        </div>
              <!-- <div style="margin: 12px; 15px 0 10px">
          <el-badge :value="2" class="item">
           <img src="../../src/assets/images/msg1.png" alt="" style="height: 15px;object-fit: contain;margin: 8px 8px 0 12px;width:16px"/>
          </el-badge>
        </div> -->
        <!-- <div style="position: relative;margin-left:15px">
          <div class="user-profile">
            <div style="width: 30px;height: 30px;border-radius: 50%;background-color: #2d8a58;margin-right: 10px"></div>
         <div  @click="quit()">
           <span class="username">admin</span>
         </div>

          </div>
          <div v-if="quit1" class="yonghu">
            <div style="width: 100%;padding: 10px 0">修改密码</div>
            <div style="width: 100%;padding: 10px 0">退出登录</div>
          </div>
        </div> -->

      <!-- <sidebar-item
         v-for="(route, index) in routers"
         :key="index"
         class="tabLink"
         :item="route"
         :base-path="route.path"
       /> -->
<!--    <sidebar-item
        v-for="(route, index) in routers"
        :key="index"
        class="tabLink"
        :item="route"
        :base-path="route.path"
      /> -->

    </div>

    <div v-if="device==='mobile'&&sidebar.opened" class="drawer-bg" @click="handleClickOutside" />
    <sidebar class="sidebar-container"  ref="sidebar"  :mes="index" :list='listMune'/>
    <div class="main-container">
           <!-- <div :class="{'fixed-header':fixedHeader}">
             <navbar />
           </div> -->
      <app-main />
    </div>
  </div>
</template>

<script>
import { Navbar, Sidebar, AppMain } from './components'
import ResizeMixin from './mixin/ResizeHandler'
import { mapGetters } from 'vuex'
import SidebarItem from './components/Sidebar/SidebarItem'
import Breadcrumb from '@/components/Breadcrumb'
import Hamburger from '@/components/Hamburger'
import Screenfull from '@/components/Screenfull'
import Search from '@/components/HeaderSearch'
import { getToken, getUserAvatar, removeToken, setUserAvatar } from '@/utils/auth'
import { changePwd, changeHeader } from '@/api/user'
import { uploadUrl } from '@/utils/request'

export default {

  data() {
    const newPassFn = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入新密码'))
      } else {
        if (this.ruleForm.newPassword !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    const confirmPassFn = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      // msg:['招商服务系统'],
      msg:['招商服务系统','推广策划系统','在线商城系统','支付服务模块','票务'],
      listMune:[],
      list:[
           // ['问卷调查'],
        ['招商资源监测','商家管理','招商方案管理','招商租赁管理','广告服务','客服服务管理','系统设置','商铺租赁服务','问卷调查','招商过程管理','商户寻租管理','轮播图设置','平台活动','客服配置','优惠券管理'],
        ['品牌策划','活动策划','氛围策划','媒体推广'],
        ['订单管理','积分管理','消息中心','会员管理','评论管理','商品管理','库存管理','销售统计','平台活动'],
        ['联机交易'],
        ['渠道售票统计分析','销售额统计分析'],
      ],
      index:0,
      show:false,
      quit1:false,
      device:true,
      classObj:{},
      ArrLu:[],
      userAvatar: null,
      changePwdShow: false,
      changeHeadObj: {
        show: false,
        data: { image: null }
      },

      action: uploadUrl,
      headers: {
        'Authorization-admin': getToken()
      },
      dataObj: {
        folderId: 1
      },
      ruleForm: {
        password: '',
        newPassword: '',
        confirmPass: ''
      },
      name: localStorage.getItem('roleName'),
      rules: {
        password: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, validator: newPassFn, trigger: 'blur' }
        ],
        confirmPass: [
          { required: true, validator: confirmPassFn, trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    Navbar,
    Sidebar,
    AppMain
  },

  mixins: [ResizeMixin],
  computed: {

    sidebar() {
      return this.$store.state.app.sidebar
    },
    device() {
      return this.$store.state.app.device
    },
    fixedHeader() {
      return this.$store.state.settings.fixedHeader
      console.log(this.$store.state.settings)
    },
    classObj() {
      return {
        hideSidebar: !this.sidebar.opened,
        openSidebar: this.sidebar.opened,
        withoutAnimation: this.sidebar.withoutAnimation,
        mobile: this.device === 'mobile'
      }
    },


      // ...mapGetters(['sidebar', 'avatar', 'device'])
  },
  created() {
    this.userAvatar = getUserAvatar()
  },
  mounted(){
    // let res = JSON.parse(localStorage.getItem('user'));
    // this.ArrLu = res.menuList
    // let arrAll = this.findMatchingNames(this.ArrLu,this.msg)
    // let getAll =this.findMatchingValues(this.list,arrAll)



    let list1=[]
    let list2=[]
     let list3=[]
     let list4=[]
     let list5=[]
    this.routers.map(item=>{
      this.list[0].map(el=>{
        if(item.meta&&el.meta){
          if(el.meta){

            if(item.meta.title==el.meta.title){
              list1.push(item)
            }
          }
        }
        if(item.meta){
          if(item.meta.title==el){
            list1.push(item)
          }
        }
      })
      this.list[1].map(el=>{
        if(item.meta){
          if(item.meta.title==el){
            list2.push(item)
          }
        }
      })

      this.list[2].map(el=>{
        if(item.meta){
          if(item.meta.title==el){
            list3.push(item)
          }
        }
      })
      this.list[3].map(el=>{
        if(item.meta){
          if(item.meta.title==el){
            list4.push(item)
          }
        }
      })
      this.list[4].map(el=>{
        if(item.meta){
          if(item.meta.title==el){
            list5.push(item)
          }
        }
      })
    })

this.$nextTick(() => {
  this.listMune.push(list1)
  this.listMune.push(list2)
    this.listMune.push(list3)
     this.listMune.push(list4)
     this.listMune.push(list5)
});



    if(this.ArrLu){
     let arrAll =this.findMatchingValues(this.msg,this.ArrLu)
     arrAll.map(el=>{
         if(el.name == '招商服务系统'){
           let getAll =this.find(this.list[0],el.children)
           let All = getAll.filter((value) => value !== false)
this.$nextTick(() => {
this.listMune[0] = All
});
             // this.list[0] = All
             console.log(this.list[0])
         }else if(el.name == '推广策划系统'){
      let getAll =this.find(this.list[1],el.children)
           let All = getAll.filter((value) => value !== false)
           this.$nextTick(() => {
               this.listMune[1] = All
           });
           // this.list[1] = All
         }else if(el.name == '在线商城系统'){
      let getAll =this.find(this.list[2],el.children)
           let All = getAll.filter((value) => value !== false)
           this.$nextTick(() => {
               this.listMune[2] = All
           });
           // this.list[2] = All
         }else if(el.name == '支付服务模块'){
            let getAll =this.find(this.list[3],el.children)
                 let All = getAll.filter((value) => value !== false)
                 this.$nextTick(() => {
                     this.listMune[3] = All
                 });
         }else if(el.name == '票务'){
        let getAll =this.find(this.list[4],el.children)
             let All = getAll.filter((value) => value !== false)
             this.$nextTick(() => {
                 this.listMune[4] = All
             });
         }

       })

       }

    },

  methods: {

      // toggleSideBar() {
      //   this.$store.dispatch('app/toggleSideBar')
      // },
      // 更换头像
      changeHead() {
        this.changeHeadObj.show = true
        this.changeHeadObj.data.image = this.userAvatar
      },
      // 提交更换头像
      async HandleChangeHeadSubmit() {
        if (!this.changeHeadObj.data.image) return this.$message.error('请先上传头像')
        const postData = {
          avatar: this.changeHeadObj.data.image,
          name: '更换'
        }
        await changeHeader(postData)
        this.$message.success('更换成功')
        setUserAvatar(postData.avatar)
        this.userAvatar = postData.avatar
        this.handleHeadClose()
      },
      handleAvatarSuccess(data) {
        if (!data.data.url) return this.$message.error('上传失败，请稍后重试')
        this.changeHeadObj.data.image = data.data.url
      },
      handleHeadClose() {
        this.changeHeadObj.data.image = null
        this.changeHeadObj.show = false
      },
      changePwd() {
        this.ruleForm.newPassword = ''
        this.ruleForm.password = ''
        this.ruleForm.confirmPass = ''
        this.changePwdShow = true
      },
      // 修改密码
      confirmChangePwd() {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            const obj = {
              password: this.ruleForm.password,
              newPassword: this.ruleForm.newPassword
            }
            changePwd(obj).then(res => {
              if (res.code === '') {
                this.changePwdShow = false
                this.$message({
                  message: '修改成功，请重新登录！',
                  type: 'success'
                })
                this.$nextTick(() => {
                  this.$refs['ruleForm'].clearValidate()
                })
                setTimeout(() => {
                  localStorage.clear()
                  removeToken()
                  this.$router.push(`/login?redirect=${this.$route.fullPath}`)
                }, 2000)
              }
            }).catch(() => {
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      handleClose() {
        this.changePwdShow = false
        this.$nextTick(() => {
          this.$refs['ruleForm'].clearValidate()
        })
      },
      async logout() {
        localStorage.clear()
        removeToken()
        this.$router.push(`/login?redirect=${this.$route.fullPath}`)
      },

    gzt(){
      // window.location.href = 'https://admin-uat.028wlkj.com:1020/'
      window.location.href = 'https://admin.028wlkj.com:1020/application-manage'
    },
    findMatchingNames(List,msg){
       return List.filter((item) => msg.includes(item.name))
    },
    findMatchingValues(tree1, tree2) {
      let result = [];

      tree1.forEach((item1) => {
        tree2.forEach((item2) => {
          if (item1 === item2.name) {
            result.push(item2);
          }

          // if (item1.children && item1.children.length > 0 && item2.children && item2.children.length > 0) {
          //   const childrenResult = findMatchingValues(item1.children, item2.children);
          //   result = result.concat(childrenResult);
          // }
        });
      });

      return result;
    },
    find(tree1, tree2) {
      let result = [];

      tree1.forEach((item1) => {
        tree2.forEach((item2) => {
          if(item1.meta.title === item2.name){
            result.push(item2);
          }

          if (item1.children && item1.children.length > 0 && item2.children && item2.children.length > 0) {
            const childrenResult = find(item1.children, item2.children);
            result = result.concat(childrenResult);
          }
        });
      });

      return result;
    },


    quit(){
      if(!this.quit1){
        this.quit1 = true
      }else{
        this.quit1 = false
      }
    },
    clk(index){
      this.index = index

       if(this.ArrLu){
        let arrAll =this.findMatchingValues(this.msg,this.ArrLu)
        arrAll.map(el=>{
            if(el.name == '招商服务系统'){
              let getAll =this.find(this.list[0],el.children)
              let All = getAll.filter((value) => value !== false)
                 this.$nextTick(() => {
                     this.listMune[0] = All
                 });

            }else if(el.name == '推广策划系统'){
         let getAll =this.find(this.list[1],el.children)
              let All = getAll.filter((value) => value !== false)
 this.$nextTick(() => {
               this.listMune[1] = All
           });

            }else if(el.name == '在线商城系统'){
         let getAll =this.find(this.list[2],el.children)
              let All = getAll.filter((value) => value !== false)
               this.$nextTick(() => {
                   this.listMune[2] = All
               });
            }else if(el.name == '支付服务模块'){
              let getAll =this.find(this.list[3],el.children)
                   let All = getAll.filter((value) => value !== false)
                   this.$nextTick(() => {
                       this.listMune[3] = All
                   });
            }else if(el.name == '票务'){
              let getAll =this.find(this.list[4],el.children)
                   let All = getAll.filter((value) => value !== false)
                   this.$nextTick(() => {
                       this.listMune[4] = All
                   });
            }

          })

          }else{
            let list1=[]
            let list2=[]
            let list3=[]
            let list4=[]
            let list5=[]
            this.listMune = []
            this.list=[
              // ['问卷调查'],
              ['招商资源监测','商家管理','招商方案管理','招商租赁管理','广告服务','客服服务管理','系统设置','商铺租赁服务','问卷调查','招商过程管理','商户寻租管理','轮播图设置','平台活动','客服配置','优惠券管理'],
              ['品牌策划','活动策划','氛围策划','媒体推广'],
              ['订单管理',,'积分管理','消息中心','会员管理','评论管理','商品管理','库存管理','销售统计','平台活动'],
              ['联机交易'],
              ['渠道售票统计分析','销售额统计分析'],
            ],
              this.routers.map(item=>{
                this.list[0].map(el=>{
                  if(item.meta&&el.meta){
                    if(el.meta){
                      console.log(el.meta.title)
                      if(item.meta.title==el.meta.title){
                        list1.push(item)
                      }
                    }
                  }
                  if(item.meta){
                    if(item.meta.title==el){
                      list1.push(item)
                    }
                  }
                })
                this.list[1].map(el=>{
                  if(item.meta){
                    if(item.meta.title==el){
                      list2.push(item)
                    }
                  }
                })
                this.list[2].map(el=>{
                  if(item.meta){
                    if(item.meta.title==el){
                      list3.push(item)
                    }
                  }
                })
                this.list[3].map(el=>{
                  if(item.meta){
                    if(item.meta.title==el){
                      list4.push(item)
                    }
                  }
                })

                this.list[4].map(el=>{
                  if(item.meta){
                    if(item.meta.title==el){
                      list5.push(item)
                    }
                  }
                })
              })


            this.$nextTick(() => {
                       this.listMune.push(list1)
                       this.listMune.push(list2)
                         this.listMune.push(list3)
                           this.listMune.push(list4)
                          this.listMune.push(list5)
                       });

            this.list[0]=list1
            this.list[1]=list2
             this.list[2]=list3
             this.list[3]=list4
             this.list[4]=list5
          }
          console.log(this.listMune)

    },
    handleClickOutside() {
      this.$store.dispatch('app/closeSideBar', { withoutAnimation: false })
    }
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'routers'
    ]),
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
@import "~@/styles/variables.scss";

.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: 0;
  right: 0;
  z-index: 9;
  width: calc(100% - #{$sideBarWidth});
  transition: width 0.28s;
}

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

.mobile .fixed-header {
  width: 100%;
}

.sidebar-container{
  margin-top: 50px;
}
.main-container{
  // margin-top: 50px;
  position: fixed;
  right: 0;
  top: 50px;
}
.topList{
  position: relative;
  width: 100px;
  font-size: 14px;
}
.topList::after {
  content: '';
  position: absolute;
  left: 28px;
  right: 0;
  bottom: -4px;
  height: 8px;
  width: 50%;
  background: #fff;
  transform: scaleY(0.5);
  transform-origin: 0 0;
}
.weiList{
  position: relative;
  width: 100px;
  font-size: 14px;
}
.weiList::after {
  content: '';
  position: absolute;
  left: 28px;
  right: 0;
  bottom: -4px;
  height: 8px;
  width: 50%;
  background: #3f9B6A;
  transform: scaleY(0.5);
  transform-origin: 0 0;
}
::v-deep .el-badge__content.is-fixed.is-dot {
  left: -18px;
  top: 6px;
  width: 7px;
  height: 7px;
  border-radius: 50%;
}
.el-badge {
  ::v-deep .el-badge__content
  {
    margin-top:9px;
    margin-right: 7px;
  }
}

.user-profile {
  display: flex;
  align-items: center;
  margin-top: 10px;
}


.yonghu{
  text-align: center;
  width: 100px;
  background-color: #fff;
  position: absolute;
  top: 50px;
  left: 0;
}
.username{
  color:#fff
}
.breadcrumb-container {
    float: left;
  }

  .right-menu {
    float: right;
    height: 100%;
    line-height: 50px;

    &: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 0.3s;

        &:hover {
          background: rgba(0, 0, 0, 0.025);
        }
      }
    }

    .avatar-container {
      margin-right: 30px;

      .avatar-wrapper {
        margin-top: 5px;
        // padding:20px;
        position: relative;

        .user-avatar {
          cursor: pointer;
          width: 30px;
          height:30px;
          border-radius: 50%;
          margin-top:5px
        }

        .el-icon-caret-bottom {
          cursor: pointer;
          position: absolute;
          right: -20px;
          top: 25px;
          font-size: 12px;
        }
      }
    }
  }


.user-name {
  vertical-align: top;
  font-size: 14px;
  margin-left: 5px;
  margin-top: -4px;
  display: inline-block;
  color:#fff
}

.el-icon-plus {
  width: 160px;
  height: 160px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #a1a0a0;
  border-radius: 5px;
}

.center-content {
  display: flex;
  align-items: center;
  justify-content: center;
}
::v-deep .el-submenu__icon-arrow{
  position: absolute;
      top: 50%;
      right: 10px;
      margin-top: -7px;
}
.user-dropdown{
  width:340px;
}
.el-popper{
  margin-top:0px;
}
.el-dropdown-menu__item--divided:before{
  height:0px;
}
.drName:hover{
  color:#3f9b6a;
}
.el-dropdown-menu__item:focus, .el-dropdown-menu__item:not(.is-disabled):hover{
  background-color:#ecf5f0;
  color:#3f9b6a;
}
.el-menu{
   padding:12px 0;
 }
</style>

