<template>
  <section class="homeTopContanier">
    <section class="homeWelcome">
      <div class="hwLeft">
          <span class="hwLTitle"><strong>{{$root.user.name}}，{{greetings}}</strong><em v-if="!bjzw"><span v-if='hiredDate'>您已入职{{hiredDateToNow}}，</span>感谢您的付出~</em></span>
          <span class="hwLAd"><img src="~@/assets/images/other/adicon.png"/><em @click="AnnouncementRedirect" v-if='getAnnouncementFirst.title'>{{getAnnouncementFirst.title}}</em><em v-else>暂无通知</em></span>
      </div>
      <div class="hwRight" v-if="homeTemplateBoradType!='rtpayTemplate'">
          <span class="hwRWt" v-if="city"><img :src="weatherImg"/></span>
          <span class="hwRDate"><em>{{nowDate}}</em><b>{{nowTime}}</b><i v-if="city">{{cityInfo.city}} {{cityInfo.weather}} {{cityInfo.temperature}}℃</i></span>
      </div>
    </section>
    <section class="homeAdvert" v-if='bannerArr.length'>
       <el-carousel :interval="5000" arrow="always" height="200">
                <el-carousel-item v-for="(item,index) in bannerArr" :key="index">
                <img :src="item.pic" @click="applidetaillink(item)"/>
                </el-carousel-item>
            </el-carousel>
    </section>
  </section>  
</template>
<script>
import {getNowFormatDateCN,currDateTimeHMS,getNowFormatDate,diffDate} from '@/utils/global.js'
export default {
    inject:['addTab'],
    data(){
        return{
           city:'',
           cityInfo:{},
           weatherImg:'',
           network: true,
           sun:require('@/assets/images/other/sun.png'),
           cloud:require('@/assets/images/other/cloud.png'),
           cloudy:require('@/assets/images/other/cloudy.png'),
           dust:require('@/assets/images/other/dust.png'),
           haze:require('@/assets/images/other/haze.png'),
           hail:require('@/assets/images/other/hail.png'),
           rain:require('@/assets/images/other/rain.png'),
           rainsnow:require('@/assets/images/other/rainsnow.png'),
           ray:require('@/assets/images/other/ray.png'),
           snow:require('@/assets/images/other/snow.png'),
           nowDate:'',
           nowTime:'',
           timer: "",//定义一个定时器的变量,
           greetings:'',//问候语
           hiredDateToNow:'',
           hiredDate:'',
           getAnnouncementFirst:{title:''},
           bannerArr:[], //广告
           homeTemplateBoradType:localStorage.getItem('homeTemplateBoradType')||'payTemplate',
           bjzw:null,
        }
    },
    created() {
        console.log(this.$root.user)
        this.network = __network__
        if(this.network){
            this.getLocation();   
        }
        this.timer=setInterval(()=>{
                this.nowDate=getNowFormatDateCN()
                this.nowTime=currDateTimeHMS()
                this.greetingsStr() //问候语                                        
        },1000)       
       this.employeesInfo()//在职员工信息
       this.getAnnouncementList()//获取工作台3.0公告

       this.AppMarketBannerlist()//广告列表       
       
    },
    mounted() {
       if(location.hostname.indexOf('bj.baibaodun.cn')>-1){//北京政务外网隐藏您已入职一行字符
           this.bjzw=true
       }else{
           this.bjzw=false
       }
    },
    beforeDestroy(){
       if (this.timer) {
            clearInterval(this.timer); // 在Vue实例销毁前，清除我们的定时器
        }
    },
    methods: {
        greetingsStr(){
            let HH=this.nowTime.split(":")[0]
            if(HH>='0'&&HH<='05'){
                this.greetings='凌晨好！'
            }else if(HH>='06'&&HH<='11'){
                this.greetings='上午好！'
            }else if(HH>='12'&&HH<='13'){
                this.greetings='中午好！'
            }else if(HH>='14'&&HH<='17'){
                this.greetings='下午好！'
            }else if(HH>='18'&&HH<='23'){
                this.greetings='晚上好！'
            }
        },
        employeesInfo(){
            let data={
                organizationId:localStorage.getItem("domainId")||'',
                id:localStorage.getItem("employeeId")||''
            }
            this.$api.v3employeesInfoApi(data,{
                onSucess: response => {
                   if(response.data.data){
                       this.hiredDate=response.data.data.hiredDate
                       console.log(this.hiredDate)
                       this.hiredDateToNow=diffDate(response.data.data.hiredDate,getNowFormatDate())
                   }
                }
            })
        },
        getAnnouncementList(){
            let data={
                organizationId:localStorage.getItem("domainId")||'',
                id:localStorage.getItem("employeeId")||''
            }
            this.$api.getAnnouncement({
                onSucess: response => {
                   if(response.data.data){
                      console.log(response.data.data)
                      if(response.data.data.datas.length){
                         this.getAnnouncementFirst=response.data.data.datas[0]
                      }else{
                         this.getAnnouncementFirst={} 
                      }
                   }
                }
            })
        },
        AnnouncementRedirect(){
             var param={
               id:"ad",
               name:'公告',
               linkType:'ad',
                actionContent:"",
                notice:this.notice,
                icon:"",
                key:""
             }
             this.addTab(param)
        },
        getLocation(){
            let self = this;
            AMap.plugin('AMap.Geolocation', function () {
                var geolocation = new AMap.Geolocation({
                // 是否使用高精度定位，默认：true
                enableHighAccuracy: true,
                // 设置定位超时时间，默认：无穷大
                timeout: 10000
                });
        
                geolocation.getCurrentPosition();
                AMap.event.addListener(geolocation, 'complete', onComplete);
                AMap.event.addListener(geolocation, 'error', onError);
        
                function onComplete (data) {
                    // data是具体的定位信息
                    console.log('定位成功信息：', data.addressComponent.city);
                    self.city = data.addressComponent.city;
                    AMap.plugin('AMap.Weather', function() {
                        console.log(self.city)
                        var weather = new AMap.Weather();
                            weather.getLive(self.city, function(err, data) {
                            if (!err) {
                                console.log(data)
                                self.cityInfo=data
                                if(data.weather.indexOf('晴')>-1){
                                    self.weatherImg=self.sun
                                }else if(data.weather.indexOf('云')>-1){
                                    self.weatherImg=self.cloud
                                }else if(data.weather.indexOf('阴')>-1){
                                    self.weatherImg=self.cloudy
                                }else if(data.weather.indexOf('沙')>-1){
                                    self.weatherImg=self.dust
                                }else if(data.weather.indexOf('雾')>-1){
                                    self.weatherImg=self.haze
                                }else if(data.weather.indexOf('霾')>-1){
                                    self.weatherImg=self.haze
                                }else if(data.weather.indexOf('雹')>-1){
                                    self.weatherImg=self.hail
                                }else if(data.weather=='雨夹雪'){
                                    self.weatherImg=self.rainsnow
                                }else if(data.weather=='雷雨'){
                                    self.weatherImg=self.ray
                                }else if(data.weather.indexOf('雪')>-1){
                                    self.weatherImg=self.snow
                                }else if(data.weather.indexOf('雨')>-1){
                                    self.weatherImg=self.rain
                                }else{
                                    self.weatherImg=self.cloud
                                }
                            }
                        })
                    }) 
                }
        
                function onError (data) {
                    // 定位出错
                    console.log('定位失败错误：', data);
                    self.city=''//定位失败隐藏
                    // 调用IP定位
                    self.getLngLatLocation();
                }
            });           
        },
        getLngLatLocation () {// 通过IP获取当前位置
            AMap.plugin('AMap.CitySearch', function () {
                var citySearch = new AMap.CitySearch();
                citySearch.getLocalCity(function (status, result) {
                if (status === 'complete' && result.info === 'OK') {
                    // 查询成功，result即为当前所在城市信息
                    console.log('通过ip获取当前城市：', result);
                    // 逆向地理编码
                    AMap.plugin('AMap.Geocoder', function () {
                    var geocoder = new AMap.Geocoder({
                        // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                        city: result.adcode
                    });
        
                    var lnglat = result.rectangle.split(';')[0].split(',');
                    geocoder.getAddress(lnglat, function (status, data) {
                        if (status === 'complete' && data.info === 'OK') {
                        // result为对应的地理位置详细信息
                        console.log(data);
                        }
                    });
                    });
                }
                });
            });
        },

        AppMarketBannerlist(){//广告列表
            // let options={
            //      target:document.querySelector(".homeAdvert"),                 
            //      text: '加载中...',
            //      spinner: 'el-icon-loading',
            // }
            // const loading = Loading.service(options);//开始加载
            this.$api.AppMarketBannerlistApi({},{                
                onSucess: response => {
                //    this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
                //        loading.close();//关闭加载
                //    });
                   console.log('banner______________',response.data.data.data)
                   if(response.data.data.data){
                       let Arry=[]
                       response.data.data.data.forEach(item=>{
                           var obj={}
                               obj.name=item.items['__f1dc2wtiu1VnfSPzQse'].value //标题
                               obj.pic=item.items['__cMLE2QENXQjNp1sWHE6'].value&&JSON.parse(item.items['__cMLE2QENXQjNp1sWHE6'].value)[0].path //图片
                               obj.appid=item.items['__qPv375wKiySlNqrRlEi'].value //应用id-跳转到详情页面
                               obj.imgsort=item.items['__XkErrW7l1lWDQVE29vq'].value //图片排序
                           Arry.push(obj)    
                       })
                       this.bannerArr=Arry
                       console.log(this.bannerArr)
                   }
                }
            })
        },
        applidetaillink(obj){//进入详情
           var param={
            id:"applicationMarket",
            name:'应用市场',
            linkType:'applicationMarket',
            actionContent:"",
            icon:"-1",
            key:""
          }
          this.addTab(param)//监听传递给父元素---重要父子传递         
        }, 

    },
}
</script>
<style lang="scss" scoped>
.commBoxBg{
     background: #FFFFFF;
     box-shadow: 0px 2px 6px -4px rgba(0, 0, 0, 0.12), 0px 0px 16px 0px rgba(0, 0, 0, 0.08);
     border-radius: 8px;
}
.homeTopContanier{
    display: flex;
    width: 100%;
    .homeWelcome{
        display: flex;
        padding: 25px 37px 10px 16px;
        flex:1;
        @extend .commBoxBg;
        height: 115px;    
        box-sizing: border-box;
        .hwLeft{
        flex:1;
        padding-right:48px;
        display: flex;
        flex-direction: column;
        overflow: hidden;
        white-space: nowrap;
        .hwLTitle{
            strong{font-size: 20px;color: #3c4766;}
            em{font-size: 14px;margin-left:12px;}
        }
        .hwLAd{
            background: rgba(15, 113, 255, 0.04);
            margin-top: 20px;
            display: flex;
            align-items: center;
            img{
                width: 24px;height: 24px;  
                margin:0 8px;             
            }
            em{
                color: #808191;
                overflow: hidden;
                text-overflow: ellipsis;
                width: 80%;
                cursor: pointer;
            }
        }
        }
        .hwRight{      
            padding-left:48px;
            border-left:1px solid #E9E9E9;
            display: flex;
            align-items: center;
            .hwRWt{
            img{width: 68px; height:69px;}           
            }
            .hwRDate{
                display: flex;
                flex-direction: column;
                text-align: center;
                color: #000;
                font-size: 14px;
                margin-left:16px;
            }
        }
    }
    .homeAdvert{
        @extend .commBoxBg;
        width: 690px;
        height: 115px;
        margin-left:20px;
        z-index: 0;//修改层级
        img{height: 115px;width: 690px;cursor: pointer;border-radius: 8px;}
        .el-carousel__container{height: 115px!important;}    
    }
}
</style>