<template>
  <div class="abroad_detail">
    <div class="header">
      <van-swipe class="my-swipe" indicator-color="white" v-if="detailData.coverList && detailData.coverList.length > 0">
        <van-swipe-item v-for="n in detailData.coverList" :key="n.id">
          <video
            v-if="n.cover_url.indexOf('.mp4') > -1"
            id="video"
            :src="n.cover_url"
            poster=""
            controls="controls"
            windowlessvideo="true"
            playsinline="true"
            webkit-playsinline="true"
            x5-playsinline="true"
            x-webkit-airplay="allow"
            width="100%"
            height="260px"
            type="video/mp4"
          ></video>
          <img v-if="n.cover_url.indexOf('.mp4') == -1" :src="n.cover_url" />
        </van-swipe-item>
      </van-swipe>
      <img v-else src="@/assets/service/defCoure.jpg" alt="" />
    </div>

    <div class="uni_text" v-if="initPackageArr">
      <div class="course_price" v-if="packageArr.length > 0">
        <span v-if="$route.query.bindId">¥ {{ bottomBoxData.showPrice }}</span>
        <span v-else>¥ {{ detailData.showPrice }}</span
        ><span class="redmini">起{{ detailData.unitName ? '/' : '' }}{{ detailData.unitName }}</span
        ><span class="tint">{{ detailData.productPrice }}</span>
      </div>
      <div class="course_price_free" v-else>
        <span>{{ detailData.price > 0 ? '¥' : '' }} {{ detailData.price == 0 || detailData.price == '免费' ? '' : detailData.price }}</span>
        <!-- <span class="des" v-if="BindType != 2">正在排期</span> -->
      </div>
      <!-- 优惠券 -->
      <abroad-coupon v-if="detailData && centerNo" :detailDataId="detailData.id" :centerNo="centerNo"></abroad-coupon>

      <p class="course_name">{{ detailData.course_name }}</p>
      <p class="course_info">{{ detailData.course_info }}</p>
      <p class="address" v-if="detailData.provinceAddress">
        <van-icon name="location" class="icon" />
        {{ detailData.provinceAddress + detailData.cityAddress + detailData.areaAddress + ' ' + detailData.addressDetail }}
      </p>
      <!-- 商品评价 -->
      <abroad-evaluate v-if="courseId" :courseId="courseId"></abroad-evaluate>
      <!-- 商品标签 -->
      <div class="tag_box">
        <template v-for="(tag, index) in detailData.course_labels">
          <span class="tag" v-if="tag != ''" :key="index">{{ tag }}</span>
        </template>
      </div>
    </div>
    <package v-if="courseId" :courseId="courseId" :packageArr="packageArr"></package>
    <p class="tip">如有特殊需求请联系【客服】</p>
    <div class="package top_border" v-if="packageArr.length > 0 && packageArr[packageActive].comboInfoList.length > 1">
      <div class="package_box">
        <div style="overflow: auto">
          <div
            class="package_item package_item_type"
            :class="packageTypeActive == index ? 'active' : ''"
            v-for="(item, index) in packageArr[packageActive].comboInfoList"
            :key="index"
            @click="packageTypeActive = index"
          >
            <p class="price">
              <span class="index">套餐{{ index + 1 }}</span
              ><span>¥</span>{{ item.actualPrice }}
            </p>
            <p class="name">{{ item.comboName }}</p>
            <img class="select" src="@/assets/service/select.png" alt="" />
          </div>
        </div>
      </div>
      <!-- 套餐说明 -->
      <p class="package_des" v-if="packageArr[packageActive] && packageArr[packageActive].comboInfoList[packageTypeActive].comboDescrption">
        套餐说明<br />{{ packageArr[packageActive].comboInfoList[packageTypeActive].comboDescrption }}
      </p>
    </div>
    <!-- 商品详情 -->
    <abroad-des v-if="detailData" :detailData="detailData"></abroad-des>
    <!-- 基地信息 -->
    <abroad-base v-if="detailData" :baseId="detailData.baseId"></abroad-base>

    <div class="Collection2">
      <div class="box">
        <div class="btn" @click="handleShare"></div>
        <div class="btn" @click="handleContact"></div>
      </div>
    </div>
    <!-- <div class="Collection" v-if="detailData">
      <ShareBox type="button" :detailData="detailData" v-if="showShareBox" @hiddenShare="showShareBox=false" @showShareDes="showShareDes=true"></ShareBox>
      <div class="box box1">
        <div class="icon icon_service" @click="backHome">
          <p>
            <van-icon name="wap-home-o" />
          </p>
          <p>首页</p>
        </div>
        <div class="icon icon_service" @click="handleService">
          <p>
            <van-icon name="service-o" />
          </p>
          <p>客服</p>
        </div>
      </div>
      <bottom-btn
        ref="bottomBtn"
        :bottomBoxData="bottomBoxData"
        :packageArrLength="packageArr.length"
        @handleNext="checkDatePackage()"
        @handleShare="handleShare"
        :bindId="bindId"
      ></bottom-btn>
    </div> -->
    <div class="share_mask" v-if="showShareDes" @click="showShareDes = false">
      <img class="share_des" src="@/assets/home/share.png" alt="" />
    </div>
  </div>
</template>
<script>
import AbroadDes from './AbroadDes'
import AbroadBase from './AbroadBase'
import AbroadEvaluate from './AbroadEvaluate'
import CountDown from './CountDown'
import AbroadCoupon from './AbroadCoupon'
import Package from './c_Package'
import ShareBox from './c_ShareBox'
import BottomBtn from '../component/c_BottomBtn'
import wx from 'weixin-js-sdk'
import './AbroadDetail.scss'
export default {
  name: 'ServiceAbroadDetailNext',
  components: {
    AbroadDes,
    AbroadBase,
    AbroadEvaluate,
    CountDown,
    AbroadCoupon,
    BottomBtn,
    Package,
    ShareBox,
  },
  data() {
    return {
      courseId: '',
      courseTypeLableId: '',
      BindType: '', //普通出行1 定制出行2
      bindId: '',
      inviteCode: '', //达人邀请码
      orderId: '', //集体定制id
      isShowpic: false, //是否显示达人邀请码邀请图标
      detailData: '',
      bottomBoxData: '', //底部成团状态
      packageData: [], //未处理过格式的套餐表
      packageActive: 0,
      packageTypeActive: 0,
      packageArr: [], //套餐时间价格
      initPackageArr: false, //packageArr已生成
      showCourseTable: true,
      showCustomized: false, //我要定制弹窗
      AagentUser: '', //代理人联系方式
      unionId: '',
      appId: 'wx1305e88d2bc74073',
      centerNo: '',
      copyUrl: '', //达人分享链接
      showShareDes: false,
      nowDate: '', //当前时间
      codeStep: 0, //邀请码进度
      expectMoney: '', //预计赚多少钱
      feeFlag: 1, //0达人,1志愿者
      showShareBox: false, //分享框
      baseDetailData: '',
    }
  },
  mounted() {
    this.nowDate = this.Moment().format('YYYY-MM-DD  HH:mm:ss')
    console.log(this.nowDate)
    localStorage.removeItem('useCard')

    this.courseId = this.$route.query.courseId
    this.bindId = this.$route.query.bindId
    this.BindType = this.$route.query.BindType
    this.entrance = this.$route.query.entrance
    this.inviteCode = this.$route.query.inviteCode
    this.orderId = this.$route.query.orderId
    this.ProgramType = this.$route.query.ProgramType
    this.productSceneId = this.$route.query.productSceneId
    this.DateComboType = this.$route.query.DateComboType
    this.ZZCTCanBuy = this.$route.query.ZZCTCanBuy
    this.courseTypeLableId = this.$route.query.courseTypeLableId
    if (this.inviteCode) {
      this.codeStep = 1
    }

    localStorage.setItem('prePage', 'ServiceAbroadDetailNext')
    localStorage.setItem(
      'prePageQuery',
      JSON.stringify({
        courseId: this.courseId,
        bindId: this.bindId,
        entrance: this.entrance,
        inviteCode: this.inviteCode,
        BindType: this.BindType,
        orderId: this.orderId,
        ProgramType: this.ProgramType,
        productSceneId: this.productSceneId,
        DateComboType: this.DateComboType,
        ZZCTCanBuy: this.ZZCTCanBuy,
      })
    )

    this.unionId = localStorage.getItem('unionId')
    this.getUserInfo()

    this.GetCourseDetail()
    if (this.entrance == 'school') {
      this.getAgentInfoBySchool() //校代联系方式
    } else {
      this.getAagentUser() //代理人联系方式
    }
  },
  methods: {
    // 点击套餐日期
    handlePackageDay(index) {
      this.packageActive = index
      this.packageTypeActive = 0 //重置套餐类型选择
      this.getDateInfoById()
      //TODO 获取该日所包含的套餐

      this.setShare()
    },
    // 点击去定制
    handleCustomMade() {
      this.$router.push({ name: 'CustomMade', query: { courseId: this.courseId } })
    },
    // 获取用户信息
    getUserInfo() {
      let userInfo = localStorage.getItem('userInfo')
      if (userInfo) {
        userInfo = JSON.parse(userInfo)
        this.centerNo = userInfo.centerNo
      } else {
        this.$toast.loading({
          message: '加载中...',
          duration: 0,
          forbidClick: true,
        })
        this.yxAxios.get(`${this.proxyUrl}/api/wx/${this.appId}/getUserInfo?unionId=${this.unionId}`).then((res) => {
          this.$toast.clear()
          if (res.data.data) {
            this.centerNo = res.data.data.centerNo
            localStorage.setItem('userInfo', JSON.stringify(res.data.data))

            if (res.data.data.schoolNames || res.data.data.schoolNames == [] || res.data.data.schoolNames == 'null') {
              localStorage.setItem('schoolNames', JSON.stringify(res.data.data.schoolNames))
              this.$store.commit('changeSchool', res.data.data.schoolNames)
              if (!localStorage.getItem('schoolNamesChoose')) {
                localStorage.setItem('schoolNamesChoose', JSON.stringify(res.data.data.schoolNames[0]))
              }
            } else {
              localStorage.setItem('schoolNames', [])
              this.$store.commit('changeSchool', [])
            }
          }
        })
      }
    },

    // 点击预约
    checkDatePackage() {
      // if (this.packageArr[0].date == date) {
      //   if (this.detailData.applyCount >= this.detailData.stockCount && this.packageArr[0].date == date) {
      //     this.$toast('已满团')
      //     return;
      //   }
      // }
      const tagIndex = this.packageArr[this.packageActive].comboInfoList[this.packageTypeActive].tagIndex
      console.log(this.packageArr[this.packageActive])
      let query = { date: this.packageArr[this.packageActive].date, Index1: tagIndex[0], Index2: tagIndex[1] }
      this.$router.push({ name: 'ServiceDatePackage', query: query })
    },
    // 获取产品详情
    GetCourseDetail() {
      if (!this.courseId) {
        this.$toast.fail('产品id缺失，请从正确的途径访问')
        return
      }
      this.$toast.loading({
        message: '加载中...',
        duration: 0,
        forbidClick: true,
      })
      this.yxAxios.get(`${this.yanxueUrl}/api/StudiesWap/GetCourseDetail?id=${this.courseId}&cs=绍兴市`).then((res) => {
        this.$toast.clear()
        if (res.data.data && res.data.data.id !== 0) {
          let detailData = res.data.data
          console.log('产品详情：', detailData)
          detailData.course_labels = detailData.course_labels?.split(',')
          this.detailData = detailData
          localStorage.setItem(
            'showCourseData',
            JSON.stringify({
              course_name: detailData.course_name,
              course_img: detailData.coverList[0].cover_url,
              id: detailData.id,
              marketPrice: detailData.marketPrice,
              price: detailData.price,
              baseId: detailData.baseId,
              course_labels: detailData.course_labels,
            })
          )
          if (this.orderId) {
            localStorage.setItem(
              'customizedOrder',
              JSON.stringify({
                courseId: detailData.id,
                orderId: this.orderId,
                dateComboBindId: detailData.dateComboBindId,
                isSkipPay: detailData.isSkipPay,
              })
            )
          }
          this.getPackageData() //获取套餐列表
          this.getPeriod()
          this.setShare()
          this.GetBaseDetail(detailData.baseId)
        } else {
          let message = res.data.message
          if (!message) {
            message = '产品不存在'
          }
          this.$toast.fail(message)
        }
      })
    },
    // 获取产品详情
    GetBaseDetail(baseId) {
      this.yxAxios.get(`${this.yanxueUrl}/api/Manage/GetOneBase?id=${baseId}`).then((res) => {
        this.$toast.clear()
        if (res.data.status == 1) {
          this.baseDetailData = res.data.data
        } else {
          this.$toast.fail(res.data.message)
        }
      })
    },
    // 根据选择的档期显示成团状态
    getDateInfoById() {
      const productId = this.detailData.id
      const bindId = this.packageArr[this.packageActive]?.comboInfoList[this.packageTypeActive].bindId
      const comboId = this.packageArr[this.packageActive]?.comboInfoList[this.packageTypeActive].id
      if (!bindId || !comboId) {
        return
      }
      // this.getExpectMoney(comboId)
      // console.log(productId, bindId, comboId)
      this.yxAxios
        .get(`${this.yanxueUrl}/api/Product/DateInfo/ById?productId=${productId}&bindId=${bindId}&comboId=${comboId}`)
        .then((res) => {
          // console.log(res.data)
          if (res.data.status == 1) {
            let data = res.data.data
            // console.log(data.clusterTime)
            data.clusterTime = this.Moment(new Date(data.clusterTime.replace(/\-/g, '/')))
              .add(1, 'days')
              .subtract(1, 'seconds')
              .format('YYYY/MM/DD HH:mm:ss')
            data.periodOfValidity = this.Moment(new Date(data.periodOfValidity.replace(/\-/g, '/')))
              .add(1, 'days')
              .subtract(1, 'seconds')
              .format('YYYY/MM/DD HH:mm:ss')
            this.bottomBoxData = data
          } else {
            this.$toast('获取成团状态失败')
          }
        })
    },
    setShare() {
      // 设置分享
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      this.$emit('getWxConfig', {
        title: `${this.detailData?.course_name}`, // 分享标题
        desc: '', // 分享描述
        link: location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: 'https://payment.myjxt.com/share_qxy.png', // 分享图标
      })
    },
    // 获取套餐列表
    getPackageData() {
      let startDate = this.Moment().format('YYYY-MM-DD')
      let endDate = this.Moment().add(3, 'month').format('YYYY-MM-DD')
      let bindId = this.bindId
      let ProgramType = this.ProgramType
      let params = {
        productId: this.detailData.id,
        startDate: startDate,
        endDate: endDate,
        BindType: this.BindType ? this.BindType : 1,
      }
      if (bindId !== 'undefined' && bindId != '') {
        params.bindId = bindId
      }
      if (ProgramType !== 'undefined' && ProgramType != '') {
        params.ProgramType = ProgramType
      }
      this.yxAxios.post(`${this.yanxueUrl}/api/Product/DateComboBindList/ByTime/List`, params).then((res) => {
        console.log('套餐列表:', res.data.data)
        if (res.data.data) {
          let allPackage = res.data.data
          let usefulPackage = []
          for (let i in allPackage) {
            if (allPackage[i]?.comboList?.length > 0) {
              usefulPackage.push(allPackage[i])
            }
          }
          this.packageData = usefulPackage
          localStorage.setItem('packageData', JSON.stringify(usefulPackage))
          this.setPackageArr()
        }
      })
    },
    // 设置套餐价格
    setPackageArr() {
      console.log('含套餐的日期：', this.packageData)
      let packageArr = []
      for (let i in this.packageData) {
        let packageDate = this.Moment(new Date(this.packageData[i]?.dayName.replace(/\-/g, '/')))
        let week = packageDate.format('d')
        week =
          week == 1
            ? '周一'
            : week == 2
            ? '周二'
            : week == 3
            ? '周三'
            : week == 4
            ? '周四'
            : week == 5
            ? '周五'
            : week == 6
            ? '周六'
            : week == 0
            ? '周日'
            : ''
        let comboInfoList = []
        let comboList = JSON.parse(JSON.stringify(this.packageData[i]?.comboList))
        // 为套餐添加下标
        let marketPrice = 9999
        for (let j in comboList) {
          // 添加商品已报名数量，过期请删除start
          if (this.$route.query.bindId == 3816) {
            comboList[j].applyCount = comboList[j].applyCount + 521
          }
          // 添加商品已报名数量，过期请删除end
          for (let k in comboList[j].comboInfoList) {
            comboList[j].comboInfoList[k].tagIndex = [j, k]
            comboList[j].comboInfoList[k].bindId = comboList[j].id
            if (comboList[j].comboInfoList[k].actualPrice < marketPrice) {
              marketPrice = comboList[j].comboInfoList[k].actualPrice
            }
          }
          comboInfoList.push(...comboList[j].comboInfoList)
        }
        packageArr.push({
          day: packageDate.format('M/D'),
          date: packageDate.format('YYYY-MM-DD'),
          week: week,
          marketPrice: marketPrice,
          comboInfoList: comboInfoList,
        })
      }
      this.packageArr = packageArr
      console.log('111', packageArr)
      this.initPackageArr = true
      this.getDateInfoById()
    },
    // 获取代理人联系方式
    getAagentUser() {
      let schoolName = localStorage.getItem('schoolNamesChoose') ? JSON.parse(localStorage.getItem('schoolNamesChoose')) : ''
      if (!schoolName) {
        schoolName = JSON.parse(localStorage.getItem('userInfo'))?.schoolNames[0]
      }
      this.yxAxios
        .post(`${this.proxyUrl}/manage/agentUser/list`, {
          schoolName: schoolName?.schoolName,
          type: 2,
        })
        .then((res) => {
          if (res.data.rows.length > 0) {
            let data = res.data.rows
            let AagentUser = data[0]
            for (let i in data) {
              if (data[i].mainLinkman == 1) {
                AagentUser = data[i]
              }
            }
            console.log('代理人联系方式:', AagentUser)
            this.AagentUser = AagentUser
          }
        })
    },
    // 获取校代联系方式（通过我的学校栏目进入）
    getAgentInfoBySchool() {
      let schoolRecommendShowStudent = localStorage.getItem('schoolRecommendShowStudent')
        ? JSON.parse(localStorage.getItem('schoolRecommendShowStudent'))
        : ''
      let schoolName = schoolRecommendShowStudent.schoolName
      this.yxAxios.get(`${this.proxyUrl}/api/agent/getAgentInfoBySchool?schoolName=${schoolName}`).then((res) => {
        if (res.data.data.length > 0) {
          let data = res.data.data
          let AagentUser = data[0]
          for (let i in data) {
            if (data[i].mainLinkman == 1) {
              AagentUser = data[i]
            }
          }
          console.log('代理人联系方式:', AagentUser)
          this.AagentUser = AagentUser
        }
      })
    },
    // 点击客服
    handleService() {
      this.$refs.bottomBtn.active = 1
      this.$refs.bottomBtn.showCustomized = true
    },
    // 返回首页
    backHome() {
      this.$router.push({ name: 'Home' })
    },
    // 获取可使用行程套餐
    getPeriod() {
      let date = this.Moment().format('YYYY-MM-DD')
      let weekOfday = this.Moment().format('E') // 计算今天是这周第几天
      // 如果为限时团购，就传星期三的日期
      if (this.$route.query.ProgramType == 1) {
        let TGMSTabActive = localStorage.getItem('TGMSTabActive')
        if (TGMSTabActive == 1) {
          date = this.Moment()
            .add(weekOfday == 7 ? 3 : 10 - weekOfday, 'days')
            .format('YYYY-MM-DD')
        } else {
          date = this.Moment()
            .add(weekOfday == 7 ? -4 : 3 - weekOfday, 'days')
            .format('YYYY-MM-DD')
        }
      }
      let param = {
        productId: this.detailData.id,
        state: '1',
        pageIndex: 1,
        pageSize: 999,
        date: date,
      }
      if (this.$route.query.productSceneId) {
        param.productSceneId = this.$route.query.productSceneId
      }
      if (this.$route.query.DateComboType) {
        param.DateComboType = this.$route.query.DateComboType
      }
      if (this.$route.query.ProgramType) {
        param.ProgramType = this.$route.query.ProgramType
      }
      if (this.$route.query.ZZCTCanBuy) {
        param.ZZCTCanBuy = this.$route.query.ZZCTCanBuy
      }
      this.yxAxios.post(`${this.yanxueUrl}/api/Product/ProductScene/List`, param).then((res) => {
        let data = res.data.data.data
        let periodArr = []
        for (let i in data) {
          if (data[i].groupPeriodActivityList) {
            // 如果是直通车产品，不显示常规拼团套餐
            if (this.$route.query.ProgramType && data[i].dateBindTypeName == '常规拼团') {
            } else {
              periodArr.push(data[i])
            }
          }
        }
        this.periodArr = periodArr.sort(this.sortUpDate)
        this.getExpectMoney()
        // this.periodArr = periodArr
        console.log('套餐列表:', periodArr)
      })
    },
    //获取达人推广 预计赚钱
    getExpectMoney() {
      if (!localStorage.getItem('talentData')) {
        return
      }
      const expertLevel = JSON.parse(localStorage.getItem('talentData')).expertLevel
      this.feeFlag = JSON.parse(localStorage.getItem('talentData')).feeFlag
      if (this.feeFlag == 1) {
        return
      } //0达人(显示),1志愿者(不显示)
      const userInfo = JSON.parse(localStorage.getItem('userInfo'))
      let query = {
        courseId: this.courseId,
        loginPhone: userInfo.phone,
        shareId: this.periodArr[0].groupPeriodActivityList.id,
      }
      this.yxAxios.post(`${this.proxyUrl}/user/settle/getProductFee`, query).then((res) => {
        if (res.data.code) {
          this.expectMoney = res.data.data
        } else {
          this.$toast.fail(res.data.message)
        }
      })
    },
    // 分享
    handleShare() {
      // this.yxAxios.post(`https://zlyx.shunzhi.net/api/BaseManage/ZlCourseShareRecord`,{
      this.yxAxios.post(`https://zlyx.shunzhi.net/api/BaseManage/ZlCourseShareRecord`, {
        courseId: this.courseId,
        courseTypeLableId: this.courseTypeLableId,
        baseName: this.baseDetailData.baseName,
        courseName: this.detailData.course_name,
        location: this.detailData.address,
        area: this.detailData.areaAddress,
      })
      this.showShareDes = true
    },
    // 点击联系方式
    handleContact() {
      let mobile = this.baseDetailData.mobile[0]
      if (mobile) {
        ZWJSBridge.phoneCall({
          corpId: mobile,
        })
          .then((res) => {
            console.log(res)
          })
          .catch((err) => {
            console.log(err)
          })
      } else {
        this.$toast('暂无联系方式')
      }
    },
  },
}
</script>
<style lang="scss">
.elder {
  .abroad_detail .uni_text .address,.abroad_detail .uni_text .rate > span,.package .period_nodata,.abroad_detail .package .package_title,.abroad_detail .tip,.abroad_detail .cardCont .day_tag,.abroad_detail .cardCont table td,.abroad_detail .tag_item .tag_title,.abroad_detail .tag_item .tag_text,.abroad_detail .base .center .address,.abroad_detail .base .center .tag {
    font-size: 36px !important;
  }
}
</style>
