<template>
  <div class="home">
    <div class="tieshi" v-if="tieshi">
      <van-icon @click="tieshi = false" name="clear" />
      <router-link to="/Tips">
        <img src="../assets/ts_icon.png" alt="" />
      </router-link>
    </div>
    <div class="swipe">
      <img class="logo" src="../assets/logo.png" alt="logo" />
      <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white" v-if="swipeImgs">
        <van-swipe-item v-for="(image, index) in swipeImgs" :key="index">
          <img :src="image.imgUrl" @click="goBannerDetail(index)" />
        </van-swipe-item>
      </van-swipe>
    </div>
    <div class="content">
      <van-search
        v-model="searchValue"
        :placeholder="placeholder"
        @focus="placeholder = ''"
        @blur="placeholder = '搜索馆关键字、活动、研学旅行'"
        shape="round"
        @search="onSearch()"
      />
      <div class="type_box">
        <div @click="handleCourseMore()">
          <img src="@/assets/service/homeicon1.png" alt="" />
          <p>研学课程</p>
        </div>
        <!-- <div @click="handleBaseMore()">
          <img src="@/assets/service/homeicon2.png" alt="" />
          <p>研学基地</p>
        </div> -->
        <div @click="handleHot()">
          <img src="@/assets/service/homeicon3.png" alt="" />
          <p>热门榜单</p>
        </div>
        <div @click="handleNewMore()">
          <img src="@/assets/service/homeicon4.png" alt="" />
          <p>官方资讯</p>
        </div>
        <!-- <div @click="handleTeacher()">
          <img src="@/assets/service/homeicon5.png" alt="" />
          <p>研学导师</p>
        </div> -->
      </div>
      <div class="infomation_box">
        <img class="news" src="@/assets/service/news.png" @click="handleNewMore()" alt="" />
        <div class="line"></div>
        <van-swipe vertical class="new-swipe" :autoplay="5000" :show-indicators="false">
          <van-swipe-item v-for="(item, index) in NewList" :key="index">
            <p class="new_item" @click="handleNewDetail(item)">{{ item.title }}</p>
          </van-swipe-item>
        </van-swipe>
      </div>
      <!-- 精选课程 -->
      <div class="qxy_box">
        <div class="qyx_title">
          <div class="title">精选课程</div>
          <div @click="handleCourseMore()">
            <span class="more">更多</span>
            <van-icon class="more_icon" name="arrow" />
          </div>
        </div>
        <CourseList v-if="!loadingCourse" :list="CustomerCourseList"></CourseList>
        <van-empty v-else :image="require('@/assets/empty.png')" description="加载中..." />
      </div>
      <!-- 研学基地 -->
      <div class="qxy_box">
        <div class="qyx_title">
          <div class="title">研选基地</div>
          <div @click="handleBaseMore()">
            <span class="more">更多</span>
            <van-icon class="more_icon" name="arrow" />
          </div>
        </div>
        <van-tabs v-model="provinceActive" :ellipsis="false" ref="tabs" color="#4092FF" @change="provinceTabChange">
          <van-tab :title="item.label" v-for="(item, index) in provinceTabList" :key="index"> </van-tab>
        </van-tabs>
        <BaseList v-if="!loadingBase" :list="BaseList"></BaseList>
        <van-empty v-else :image="require('@/assets/empty.png')" description="加载中..." />
      </div>
      <!-- 研学游记 -->
      <div class="qxy_box">
        <div class="qyx_title">
          <div class="title">研学游记</div>
          <div @click="handleStoryMore()">
            <span class="more">更多</span>
            <van-icon class="more_icon" name="arrow" />
          </div>
        </div>
        <StoryList v-if="!loadingStory" :list="StoryList"></StoryList>
        <van-empty v-else :image="require('@/assets/empty.png')" description="加载中..." />
      </div>
      <about-des></about-des>
      <Tabbar active="service"></Tabbar>
      <div :is="background"></div>
    </div>
  </div>
</template>

<script>
import CourseList from '@/views/Service/component/c_CourseList.vue'
import BaseList from '@/views/Service/component/c_BaseList.vue'
import StoryList from '@/views/GrowUp/c_StoryList.vue'
import Tabbar from '@/components/c_Tabbar.vue'
import Background from '../components/Background.vue'
import AllLoveGo from '../components/AllLoveGo.vue'
import AboutDes from './aboutDes.vue'
import './home.scss'
// const userData = require('@/views/data.json')
export default {
  components: {
    CourseList,
    BaseList,
    StoryList,
    Tabbar,
    Background,
    AllLoveGo,
    AboutDes,
  },
  data() {
    return {
      placeholder: '搜索馆关键字、活动、研学旅行',
      tieshi: true,
      navActive: 1,
      swipeImgs: '',
      StudyBaseList: '',
      AreaList: [],
      areaActive: 0,
      recommendList: [],
      recommendPage: 1,
      recommendCount: 0,
      CourseTypeList: '',
      tabActive: 0,
      tabBodyList: [],
      tabBodyPage: 1,
      tabBodyCount: 0,
      background: '',
      selectCity: false,
      cityList: [],

      userInfo: '',
      searchValue: '',
      loadingCourse: true,
      loadingBase: true,
      loadingStory: true,
      NewList: [], //资讯列表
      CustomerCourseList: [], //精选活动
      BaseList: [], //基地列表
      StoryList: [], //游记列表
      provinceTabList: [
        { label: '推荐', text: '', value: 0, id: '' },
        { label: '越城', text: '越城区', value: 2, id: '' },
        { label: '柯桥', text: '柯桥区', value: 1, id: '' },
        { label: '上虞', text: '上虞区', value: 4, id: '' },
        { label: '诸暨', text: '诸暨区', value: 3, id: '' },
        { label: '嵊州', text: '嵊州区', value: 5, id: '' },
        { label: '新昌', text: '新昌区', value: 5, id: '' },
      ],
      provinceActive: 0,
    }
  },
  mounted() {
    ZWJSBridge.onReady(() => {
      ZWJSBridge.setTitle({
        title: '绍兴研学',
      })
    })
    this.checkAuth()
    //二次回退
    const sUserAgent = window.navigator.userAgent.toLowerCase()
    const bIsAlipayMini = sUserAgent.indexOf('miniprogram') > -1 && sUserAgent.indexOf('alipay') > -1
    if (bIsAlipayMini) {
      console.log('我来自支付宝,popstate')
      window.addEventListener('popstate', this.listenerPopstate, true)
    } else {
      console.log('我来自浙里办,popstate')
      window.addEventListener('popstate', this.listenerPopstate, true)
    }
    this.GetNewList() // 获取资讯
    this.GetBannerList()
    this.getCustomerCourseList() //精选活动
    this.GetBaseList() //研学基地
    this.GetStoryList() //研学游记
  },
  //销毁监听
  destroyed() {
    console.log('销毁支付宝监听')
    window.removeEventListener('popstate', this.listenerPopstate, true)
  },
  methods: {
    //支付宝二次回退方法，addEventListener和removeEventListener一定要调用方法，不然无效
    listenerPopstate() {
      ZWJSBridge.close()
    },
    maidian() {
      if (this.centerNo) {
        this.$zwlogPvGlobal({ loadTime: new Date() })
        this.$nextTick(() => {
          this.$zwlogPvGlobal({ responseTime: new Date() })
        })
      }
    },
    checkAuth() {
      let centerNo = localStorage.getItem('centerNo')
      let centerNoTime = localStorage.getItem('centerNoTime')
      let nowTime = new Date().getTime()
      // alert(centerNo+'-'+nowTime + '-' + centerNoTime + '=' + (nowTime - centerNoTime))
      // 超过10分钟重新授权获取
      if (!centerNoTime || nowTime - centerNoTime > 600000) {
        centerNo = ''
      }
      let ticket = this.common.getUrlParam('ticket') //浙里办app访问
      let ticketId = this.common.getUrlParam('ticketId') //浙里办微信小程序访问
      if (centerNo) {
        // ZWJSBridge.alert({
        //   message: '有中台编号：' + centerNo,
        // })
        this.centerNo = centerNo
        this.maidian()
        this.getUserInfo()
      } else if (ticket && ticket.indexOf('debug') == -1) {
        // ZWJSBridge.alert({
        //   message: '有ticket：' + ticket,
        // })
        this.getCenterByTicket(ticket)
      } else if (ticketId && ticketId.indexOf('debug') == -1) {
        // ZWJSBridge.alert({
        //   message: '有ticketId：' + ticketId,
        // })
        this.getCenterByTicketId(ticketId)
        localStorage.setItem('isWechat', 1)
      } else {
        const sUserAgent = window.navigator.userAgent.toLowerCase()
        const dtdreamweb = sUserAgent.indexOf('dtdreamweb') > -1
        const miniprogram = sUserAgent.indexOf('miniprogram') > -1 && sUserAgent.indexOf('alipay') > -1
        if (dtdreamweb) {
          // alert('浙里办')
          window.location.href = `https://puser.zjzwfw.gov.cn/sso/mobile.do?action=oauth&scope=1&servicecode=8301b7fe71594245b97560ff841db1f2`
        } else if (miniprogram) {
          // alert('支付宝')
          window.location.href = `https://puser.zjzwfw.gov.cn/sso/alipay.do?action=ssoLogin&servicecode=8301b7fe71594245b97560ff841db1f2`
        } else {
          // alert('非浙里办渠道访问，显示测试用户数据')
          console.log('非浙里办渠道访问，显示测试用户数据', userData)
          // this.centerNo = '2022031508525674030748540013076'
          // localStorage.setItem('centerNo', '2022031508525674030748540013076')
          localStorage.setItem('centerNoTime', new Date().getTime())
          let userInfo = JSON.stringify(userData)
          localStorage.setItem('userInfo', userInfo)
          this.getUserInfo()
        }
      }
    },
    // 通过ticket获取centerNo
    getCenterByTicket(ticket) {
      this.yxAxios.get(`${this.proxyUrl}/api/third/getCenterNoSxPrivate?ticket=${ticket}`).then((res) => {
        console.log('通过ticket获取centerNo成功:', res)
        if (res.data.code == 200) {
          this.centerNo = res.data.message
          this.maidian()
          localStorage.setItem('centerNo', res.data.message)
          let nowTime = new Date().getTime()
          localStorage.setItem('centerNoTime', nowTime)
          this.getUserInfo()
        } else {
          this.reLoad()
        }
      })
    },
    // 通过ticketId获取centerNo
    getCenterByTicketId(ticketId) {
      this.yxAxios.get(`${this.proxyUrl}/api/third/getCenterNoSxPrivate?ticket=${ticketId}`).then((res) => {
        console.log('通过ticket获取centerNo成功:', res)
        if (res.data.code == 200) {
          this.centerNo = res.data.message
          this.maidian()
          localStorage.setItem('centerNo', res.data.message)
          let nowTime = new Date().getTime()
          localStorage.setItem('centerNoTime', nowTime)
          this.getUserInfo()
        } else {
          this.reLoad()
        }
      })
    },
    reLoad() {
      console.log('reload')
      const sUserAgent = window.navigator.userAgent.toLowerCase()
      const dtdreamweb = sUserAgent.indexOf('dtdreamweb') > -1
      const miniprogram = sUserAgent.indexOf('miniprogram') > -1 && sUserAgent.indexOf('alipay') > -1
      if (localStorage.getItem('reloadCount') == 2) {
        localStorage.setItem('reloadCount', 1)
        ZWJSBridge.confirm({
          title: '警告',
          buttonLabels: ['重新载入'],
          message: '用户身份验证失败，请重新加载',
        }).then((res) => {
          if (dtdreamweb) {
            // alert('浙里办')
            window.location.href = `https://puser.zjzwfw.gov.cn/sso/mobile.do?action=oauth&scope=1&servicecode=8301b7fe71594245b97560ff841db1f2`
          } else if (miniprogram) {
            // alert('支付宝')
            window.location.href = `https://puser.zjzwfw.gov.cn/sso/alipay.do?action=ssoLogin&servicecode=8301b7fe71594245b97560ff841db1f2`
          }
        })
      } else {
        localStorage.setItem('reloadCount', 2)
        if (dtdreamweb) {
          // alert('浙里办')
          window.location.href = `https://puser.zjzwfw.gov.cn/sso/mobile.do?action=oauth&scope=1&servicecode=8301b7fe71594245b97560ff841db1f2`
        } else if (miniprogram) {
          // alert('支付宝')
          window.location.href = `https://puser.zjzwfw.gov.cn/sso/alipay.do?action=ssoLogin&servicecode=8301b7fe71594245b97560ff841db1f2`
        }
      }
    },
    // 获取用户信息
    getUserInfo() {
      this.yxAxios.get(`${this.proxyUrl}/user/info/getPortalUserByNum?userNum=${localStorage.getItem('centerNo')}`).then((res) => {
        console.log('获取用户信息getPortalUserByNum:', res)
        if (res.data.code == 200) {
          localStorage.setItem('userInfo', JSON.stringify(res.data.data.userInfo))
          this.userInfo = res.data.data.userInfo
        }
      })
    },
    // 获取资讯
    GetNewList() {
      this.yxAxios.post(`${this.proxyUrl}/manage/info/content/listWithNoContent`, { pageNum: 1, pageSize: 5 }).then((res) => {
        let NewList = res.data.rows
        console.log('资讯列表：', NewList)

        this.NewList = NewList
      })
    },
    // 精选课程
    getCustomerCourseList() {
      this.yxAxios
        .post(`${this.yanxueUrl}/api/SchoolManage/SchoolCourseListV2`, {
          labelIdList: [],
          ageType: 0, //适应对象
          days: 0, //线路天数
          isSelfSupport: '', //是否支持定制
          provinceName: '', //省份
          cityName: '', //城市
          // areaName: areaName, //区
          startPrice: -1,
          endPrice: -1,
          stype: 1,
          pageIndex: 1,
          pageSize: 4,
        })
        .then((res) => {
          let CustomerCourseList = res.data.data.data
          console.log('精选课程:', CustomerCourseList)
          for (let i in CustomerCourseList) {
            CustomerCourseList[i].course_labels = CustomerCourseList[i].course_labels?.split(',')
            if (CustomerCourseList[i].startDate) {
              CustomerCourseList[i].week = this.formatWeek(this.Moment(CustomerCourseList[i].startDate).format('d'))
              CustomerCourseList[i].startDate = this.Moment(CustomerCourseList[i].startDate).format('YYYY.M.D')
              CustomerCourseList[i].endDate = this.Moment(CustomerCourseList[i].endDate).format('YYYY.M.D')
            }
          }
          this.CustomerCourseList = CustomerCourseList
          this.loadingCourse = false
        })
    },
    // 获取研学基地
    GetBaseList() {
      this.yxAxios
        .post(`${this.yanxueUrl}/api/SchoolManage/SchoolStudyBaseList`, {
          provinceName: '浙江省',
          cityName: '绍兴市',
          areaName: this.provinceTabList[this.provinceActive].text,
          levelName: '',
          type: 0,
          StartPeopleCount: '-1',
          EndPeopleCount: '-1',
          stype: 0,
          pageIndex: 1,
          pageSize: 6,
        })
        .then((res) => {
          let BaseList = res.data.data.data
          console.log('基地列表：', BaseList)

          for (let i in BaseList) {
            BaseList[i].baseLabel = BaseList[i].baseLabel?.split(',')
          }
          this.BaseList = BaseList
          this.loadingBase = false
        })
    },

    // 改变地区
    provinceTabChange() {
      this.BaseList = []
      this.GetBaseList()
    },
    // 获取研学游记
    GetStoryList() {
      this.yxAxios.get(`${this.yanxueUrl}/api/StudiesWap/GetMyStoryList?pageIndex=1&pageSize=6`).then((res) => {
        let StoryList = res.data.data.items
        console.log('游记列表：', StoryList)

        this.StoryList = StoryList
        this.loadingStory = false
      })
    },

    handleNewDetail(item) {
      if (item.linkUrl) {
        this.yxAxios.post(`${this.proxyUrl}/manage/info/content/addReadNum`, { id: item.id }).then((res) => {
          if (res.data.code == 200) {
            location.href = item.linkUrl
          } else {
            this.$toast.fail(res.data.message)
          }
        })
      } else {
        this.$router.push({ name: 'ArticleDetail', query: { id: item.id } })
      }
    },
    // 点击研学导师
    handleTeacher() {
      this.$router.push({ name: 'Teacher' })
    },
    // 热门榜单
    handleHot() {
      this.$router.push({ name: 'RankingList' })
    },
    // 点击资讯更多
    handleNewMore() {
      this.$router.push({ name: 'Article' })
    },
    // 点击精选课程更多
    handleCourseMore() {
      this.$router.push({ name: 'SelectionCourse' })
    },
    // 点击研学基地更多
    handleBaseMore() {
      this.$router.push({ name: 'SelectionBase' })
    },
    // 点击研学游记更多
    handleStoryMore() {
      this.$router.push({ name: 'StoryList' })
    },
    goBannerDetail(index) {
      // var t = this.swipeImgs[index].type
      // if (t == 1) {
      //   window.location.href = this.swipeImgs[index].linkUrl
      // } else {
      //   this.$router.push({
      //     path: '/BannerDetail',
      //     query: { id: this.swipeImgs[index].id },
      //   })
      // }
    },

    GetBannerList() {
      this.http
        .GetBannerList({
          city: this.projectCity,
        })
        .then((res) => {
          if (res.status == 1) {
            this.swipeImgs = res.data
          }
        })
    },
    onSearch() {
      if (this.searchValue != '') {
        this.$router.push({ name: 'SearchResult', query: { search: this.searchValue } })
      } else {
        this.$toast('请输入搜索内容')
      }
    },

    // 获取用户信息
    // getUserInfo() {
    //   let userInfo = sessionStorage.getItem('userInfo')
    //   if (userInfo) {
    //     this.userInfo = JSON.parse(userInfo)

    //     this.showData = true
    //     this.GetStoryList()
    //   } else {
    //     this.$toast.loading({
    //       message: '加载中...',
    //       duration: 0,
    //       forbidClick: true,
    //     })
    //     this.yxAxios.get(`${this.proxyUrl}/api/wx/wx1305e88d2bc74073/getUserInfo?unionId=${this.unionId}`).then((res) => {
    //       this.$toast.clear()
    //       if (res.data.data) {
    //         this.showData = true
    //         this.userInfo = res.data.data
    //         this.GetStoryList()
    //         sessionStorage.setItem('userInfo', JSON.stringify(res.data.data))
    //       } else {
    //         console.log('getUserInfo失败')
    //         this.showData = true
    //       }
    //     })
    //   }
    // },
    formatWeek(week) {
      return week == 1
        ? '周一'
        : week == 2
        ? '周二'
        : week == 3
        ? '周三'
        : week == 4
        ? '周四'
        : week == 5
        ? '周五'
        : week == 6
        ? '周六'
        : week == 0
        ? '周日'
        : ''
    },
  },
}
</script>
<style lang="stylus" scoped>
.bottomText {
  text-align: center;
  font-size: 1.2rem;
  color: #ccc;

  p {
    margin: 0;
  }
}

.home {
.tieshi{
			position: fixed;
			right: 20px;
			bottom: 25%;
			z-index: 1000;
			padding: 20px 20px 0 0;
			i{
				position: absolute;
				top: 0;
				right: 0;
				font-size: 3.6rem;
				z-index: 100;
				color: #c2c2c2;
			}
			img{
				width :160px;
			}
		}
  .swipe {
    position: relative;

    .logo {
      width: 25%;
      position: absolute;
      top: 20px;
      left: 20px;
      z-index: 100;
    }

    .scan {
      position: absolute;
      right: 20px;
      top: 20px;
      z-index: 100;
      color: white;
      font-size: 2.6rem;

      .tishi {
        position: absolute;
        left: -90px;
        bottom: -30px;
        width: 112px;
      }
    }

    img {
      width: 100%;
    }
  }


}
</style>
<style lang="scss">
// 长辈版
.elder {
  .home .infomation_box .new_item {
    font-size: 36px;
  }
  .home .type_box p {
    font-size: 34px;
  }
  .home .qxy_box .qyx_title {
    .title {
      font-size: 44px;
    }
    .more {
      font-size: 38px;
    }
  }
  .abroad .uni_item_mini {
    .course_content {
      .title {
        font-size: 36px;
      }
      .des {
        font-size: 34px;
      }
    }
    .img_box .bottom {
      font-size: 32px;
    }
  }
  .van-tab {
    font-size: 36px;
  }
}
</style>
