<template>
  <div class="mainPage flex-v" v-if="showPage">
    <div class="flex-item">
      <div class="content">
        <div class="banner">
          <div class="scrollImg">
            <img :src='courseDetail.CourseImg' class="cover" alt="">
            <!-- <swiper :options="swiperOption" ref="mySwiper">
              <swiper-slide class="swiper-slide" v-for="(item,index) in courseDetail.CourseImgs" :key="index">
                <img :src='item.ImgUrl' class="cover" alt="">
              </swiper-slide>
            </swiper> -->
          </div>
          <div>
            <span>{{courseDetail.CourseName}}</span>
            <div>
              <span>￥<em>{{courseDetail.Price}}</em>起/课时</span>
              <span>参与者<em>{{courseDetail.SignupNum}}</em>/{{courseDetail.MaxNum}}人</span>
            </div>
          </div>
        </div>
        <div class="subContent time">
          <h5>时间</h5>
          <span>{{returnDate(courseDetail.BeginDate)}}~{{returnDate(courseDetail.EndDate)}}</span>
          <div class="list flex-h">
            <div class="flex-item">
              <ul :class="{'show':showMoreCourse}">
                <li v-for="(item,index) in courseTimeList" :key="index">{{returnCourseTime(item.BeginDate,item.EndDate)}}</li>
              </ul>
              <a class="moreCourse" @click="triggerCourseTime" v-if="courseTimeList.length>4">
                {{showMoreCourse ? '收起' : '更多'}}
                <i v-if="!showMoreCourse" class="iconfont icon-jiantou-down"></i>
                <i v-if="showMoreCourse" class="iconfont icon-jiantou-up"></i>
              </a>
            </div>
          </div>
        </div>
        <div style="width:100%;height:.1rem;background:#ebf1f2;"></div>
        <div class="subContent address">
          <h5>地点</h5>
          <div class="flex-h">
            <div class="flex-item">
              <div class="img">
                <a @click="openMap">
                  <img v-if="courseDetail.CaseInfo !== undefined" :src="courseDetail.CaseInfo.CaseIcon" class="centerLabel cover" alt="">
                  <div class="flex-h">
                    <i class="iconfont icon-dingwei"></i>
                    <div class="flex-item">
                      <div>
                        <span v-if="courseDetail.CaseInfo !== undefined">{{courseDetail.CaseInfo.CaseName}}（{{courseDetail.CaseInfo.CaseAddress}}）</span>
                      </div>
                    </div>
                  </div>
                </a>
              </div>
            </div>
          </div>
        </div>
        <div class="subContent address">
          <h5 style="padding-bottom:.1rem">课程详情</h5>
          <div class="flex-l" style="margin: 0 .26rem">
            <img :src="item.ImgUrl" alt="" width="100%" v-for="(item,index) in detailImage" :key="index">
          </div>
        </div>
      </div>
    </div>
    <div class="flex-h">
      <div class="flex-item">
        <div>
          <span>总计￥<em>{{courseDetail.Price}}</em></span>
          <span>优惠券体验</span>
        </div>
      </div>
      <a @click="toBuy" :class="{gray: gray}">去购买</a>
    </div>
  </div>
</template>

<script>
import wxsdk from '../../../util/share'
import logo from '../../../common/icon/indexlogo.jpg'
import { swiper, swiperSlide } from 'vue-awesome-swiper'
import 'swiper/dist/css/swiper.css'
import { mapState, createNamespacedHelpers } from 'vuex'
const { mapActions: mapProjectActions, mapState: mapProjectState } = createNamespacedHelpers('majorProjects')
const wx = require('weixin-js-sdk')

export default {
  name: '',
  data () {
    return {
      logo,
      gray: false,
      swiperOption: {
        observer: true,
        autoplay: {
          disableOnInteraction: false,
        }
      },
      showMoreCourse: false, // 显隐更多课程时间
      courseTimeList: [], // 课程时间
      detailImage: [],
      showPage: false,
      topImage: ''
    }
  },
  computed: {
    ...mapState({
      orgid: x => x.app.orgId,
      fiveA: x => x.index.fiveA,
      banner: x => x.index.banner,
      message: x => x.index.message,
      project: x => x.index.project,
      cms: x => x.index.cms,
      user: x => x.userCenter.userInfo
    }),
    ...mapProjectState({
      courseDetail: x => x.courseDetail
    }),
    MySwiper () {
      return this.$refs.mySwiper.swiper
    },
  },
  components: {
    swiper,
    swiperSlide,
  },
  created () {
    this.getCourseDetailInfo({ id: this.$route.query.id }).then((res) => {
      var arr = res.CourseDetail
      if (arr === null) {
        arr = []
      }
      this.courseDetail.CourseImgs = this.courseDetail.CourseImgs || []
      // this.topImage = this.courseDetail.CourseImgs.length > 0 ? this.courseDetail.CourseImgs[0].ImgUrl : ""
      if (this.courseDetail.CourseImgs.length > 0) {
        this.courseDetail.CourseImgs.sort(this.getSortFun('asc', 'Sort'))
        this.detailImage = this.courseDetail.CourseImgs
      }
      // console.log(this.detailImage)
      this.courseTimeList = arr.sort(function (a, b) { return new Date(a.BeginDate).getTime() > new Date(b.BeginDate).getTime() ? 1 : -1 })
      let nowDate = Date.now()
      let endData = new Date(this.courseDetail.EndDate).getTime()
      if (nowDate > endData) {
        this.gray = true
      }
      if (this.courseDetail.SignupNum >= this.courseDetail.MaxNum) {
        this.gray = true
      }
      // console.log(JSON.stringify(res))
      this.showPage = true
    })
  },
  methods: {
    ...mapProjectActions([
      'getCourseDetailInfo',
      'placeCourseOrderBefore',
    ]),
    getSortFun (order, sortBy) {
      var ordAlpah = (order == 'asc') ? '>' : '<'
      var sortFun = new Function('a', 'b', 'return a.' + sortBy + ordAlpah + 'b.' + sortBy + '?1:-1')
      return sortFun
    },
    returnCourseTime (val, endVal) { // 返回课时时间
      val = new Date(val)
      endVal = new Date(endVal)
      return this.returnNum(val.getMonth() + 1) + '/' + this.returnNum(val.getDate()) + ' 周' + '日一二三四五六'.split('')[new Date(val).getDay()] + ' ' + this.returnNum(val.getHours()) + ':' + this.returnNum(val.getMinutes()) + '~' + this.returnNum(endVal.getHours()) + ':' + this.returnNum(endVal.getMinutes())
    },
    returnNum (val) {
      return val > 9 ? val : '0' + val
    },
    returnDate (val) {
      val = new Date(val)
      return val.getFullYear() + '年' + this.returnNum(val.getMonth() + 1) + '月' + this.returnNum(val.getDate()) + '日'
    },
    triggerCourseTime () { // 显隐更多课程时间
      this.showMoreCourse = !this.showMoreCourse
    },
    toBuy () {
      if (this.gray) {
        this.$toast('该课程已过期或参与人数已满')
        return
      }
      let nowDate = Date.now()
      let endData = new Date(this.courseDetail.EndDate).getTime()
      if (nowDate > endData) {
        this.$toast('该课程已过期')
      } else {
        this.placeCourseOrderBefore({
          order: {
            CourseId: this.courseDetail.CourseId,
            CaseId: this.courseDetail.CaseId,
            CustomerId: this.user.CustomerId,
            Price: this.courseDetail.Price
          },
          customercouponid: ''
        }).then((res) => {
          // console.log(JSON.stringify(res))
          this.$router.push({ name: 'placeOrderForCourse', query: { id: this.courseDetail.CourseId, ordersid: res.OrdersId } })
        })
      }
    },
    openMap () {
      wxsdk({ url: encodeURIComponent(window.location.href.split('#')[0]) }, {
        title: '城的空间',
        desc: '城的空间',
        link: `${window.location.origin}${window.location.pathname}#/mainPage/indexPage`,
        thu_image: `https://spaceofcheng.oss-cn-beijing.aliyuncs.com/indexlogo.jpg?x-oss-process=style/wxicon`
      }).then(() => {
        let result = this.courseDetail.CaseInfo.Coordinate.split(",")
        let latitude = parseFloat(result[0])
        let longitude = parseFloat(result[1])
        wx.openLocation({
          latitude: latitude, // 纬度，浮点数，范围为90 ~ -90
          longitude: longitude, // 经度，浮点数，范围为180 ~ -180。
          name: this.courseDetail.CaseInfo.CaseName, // 位置名
          // address: '', // 地址详情说明
          // scale: 1, // 地图缩放级别,整形值,范围从1~28。默认为最大
          // infoUrl: '' // 在查看位置界面底部显示的超链接,可点击跳转
        })
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" scoped>
@import 'page.scss';
</style>
