<template>
  <div class="abroad_detail">
    <div class="uni_text">
      <p class="course_name">{{ detailData.activityLabel ? detailData.activityLabel : detailData.course_name }}</p>
      <p class="course_count">阅读量：{{ detailData.read_count }}</p>
      <!-- 商品标签 -->
      <div class="tag_box">
        <span class="tag" v-if="detailData.areaAddress"><van-icon name="location" class="icon" /> {{ detailData.areaAddress }}</span>
        <template v-for="(tag, index) in detailData.course_labels">
          <span class="tag" v-if="tag != ''" :key="index">{{ tag }}</span>
        </template>
      </div>
    </div>
    <!--达人-->
    <!-- <div class="fixedInvite" v-if="isShowpic">
      <div @click="handleCode" v-if="codeStep == 1" class="moneyCss">
        <div class="boxMon">
          <div class="moneyFont">¥ {{ expectMoney }}</div>
          <img src="@/assets/copartner/receiveNew3.png" />
        </div>
      </div>
      <div @click="handleInvite" v-if="codeStep == 2" class="moneyCss">
        <div class="boxMon">
          <div class="moneyFont">¥ {{ expectMoney }}</div>
          <img src="@/assets/copartner/shareTaskNew3.png" />
        </div>
      </div>
    </div> -->
    <!-- 商品详情 -->
    <abroad-des v-if="detailData" :detailData="detailData"></abroad-des>
    <!-- 基地信息 -->
    <!-- <abroad-base v-if="detailData" :baseId="detailData.baseId"></abroad-base> -->

    <div class="Collection" v-if="detailData">
      <bottom-btn-left :centerNo="centerNo" :courseId="courseId"></bottom-btn-left>
      <div class="box box2">
        <div class="box_btn">
          <span @click="toNext()">参加活动</span>
        </div>
      </div>
    </div>
    <van-action-sheet v-model="showCustomized" cancel-text="取消" close-on-click-action>
      <div class="customized">
        <p class="customized_title">添加微信联系</p>
        <img class="customized_code" :src="AagentUser.qrCodeUrl || require('@/assets/service/customized_code2.png')" alt="" />
        <span class="customized_code_des">关注本活动专属定制专员</span>
        <div class="customized_line"></div>
        <div class="customized_flex">
          <div>
            <p class="customized_title">客服热线</p>
            <p class="customized_phone">{{ AagentUser.phone || '4008262468' }}</p>
          </div>
          <img class="customized_phone_icon" src="@/assets/service/phone.png" alt="" />
        </div>
      </div>
    </van-action-sheet>
  </div>
</template>
<script>
import AbroadDes from './AbroadDes'
import BottomBtnLeft from '../component/c_BottomBtnLeft'
import wx from 'weixin-js-sdk'
import './AbroadDetail.scss'
export default {
  name: 'ServiceAbroadDetail',
  components: {
    AbroadDes,
    BottomBtnLeft,
  },
  data() {
    return {
      courseId: '',
      BindType: '', //普通出行1 定制出行2
      bindId: '',
      inviteCode: '', //达人邀请码
      orderId:'',//集体定制id
      isShowpic: false, //是否显示达人邀请码邀请图标
      detailData: '',
      packageData: [], //套餐表
      packageActive: 0,
      packageTypeActive: 0,
      showCourseTable: true,
      showCustomized: false, //我要定制弹窗
      AagentUser: '', //代理人联系方式
      unionId: '',
      appId: '',
      centerNo: '',
      copyUrl: '', //达人分享链接
      nowDate: '', //当前时间
      codeStep: 0, //邀请码进度
      expectMoney: '', //预计赚多少钱
    }
  },
  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', 'ServiceAbroadDetail')
    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,
        courseTypeLableId:this.courseTypeLableId
      })
    )
    if (process.env.NODE_ENV === 'production' && this.common.isWeiXin()) {
      let openId = localStorage.getItem('openId' )
      if (!openId) {
        this.$router.push({ name: 'Authorize'  })
        return
      }
      this.unionId = localStorage.getItem('unionId')
      this.getUserInfo()
    } else {
      this.unionId = this.TestUnionId
      this.getUserInfo()
    }
    this.GetCourseDetail()
  },
  methods: {
    // 点击去定制
    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', [])
            }
          }
        })
      }
    },

    // 点击预约
    toNext() {
      location.href = location.href.replace('abroad_detail', 'abroad_detail_next')
    },
    // 获取产品详情
    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,
              baseId: detailData.baseId,
              marketPrice: detailData.marketPrice,
              price: detailData.price,
              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.setCourseVisit() //调用浏览量
          this.setShare()
        } else {
          let message = res.data.message
          if (!message) {
            message = '产品不存在'
          }
          this.$toast.fail(message)
        }
      })
    },
    setCourseVisit() {
      this.yxAxios.post(`${this.yanxueUrl}/api/BaseManage/CourseVisit`, {
        courseId: this.courseId,
        userId: this.centerNo,
        inviteCode: this.inviteCode,
      })
    },
    setShare() {
      // 设置分享
      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(60, 'days')
        .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 packageData = []
          for (let i in allPackage) {
            if (allPackage[i]?.comboList?.length > 0) {
              packageData.push(allPackage[i])
            }
          }
          this.formatPackage(packageData)
        }
      })
    },
    // 设置套餐价格
    formatPackage(packageData) {
      for (let i in packageData) {
        let packageDate = this.Moment(packageData[i]?.dayName, 'YYYY-MM-DD')
        let week = packageDate.format('d')
        // console.log(week)
        week =
          week == 1
            ? '周一'
            : week == 2
            ? '周二'
            : week == 3
            ? '周三'
            : week == 4
            ? '周四'
            : week == 5
            ? '周五'
            : week == 6
            ? '周六'
            : week == 0
            ? '周日'
            : ''
        let comboInfoList = []
        let comboList = packageData[i].comboList
        // 为套餐添加下标
        let marketPrice = 9999
        for (let j in comboList) {
          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)
        }
        packageData[i].day = packageDate.format('M/D')
        packageData[i].date = packageDate.format('YYYY-MM-DD')
        packageData[i].week = week
        packageData[i].marketPrice = marketPrice
        // packageData.comboInfoList = comboInfoList
      }
      this.packageData = packageData
      console.log('格式处理后的套餐列表:', packageData)
      localStorage.setItem('packageData', JSON.stringify(packageData))
    },
  },
}
</script>
