<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>
    <!--倒计时-->
    <count-down v-if="detailData&&packageArr[packageActive]" :productId="detailData.id" :packageArr="packageArr" :day="packageArr[packageActive].day" :bindId="packageArr[packageActive].comboInfoList[packageTypeActive].bindId" :comboId="packageArr[packageActive].comboInfoList[packageTypeActive].id"></count-down>

    <div class="uni_text" v-if="initPackageArr">
      <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>
    <!-- <div class="package top_border">
      <p class="package_title">套餐类型/日期</p>
      <div class="package_box" v-if="packageArr.length>0">
        <div style="overflow:auto;">
          <div class="package_item" :class="packageActive==index?'active':''" v-for="(item, index) in packageArr" :key="index" @click="handlePackageDay(index)">
            <p class="date">{{ item.day }}</p>
            <p class="week">{{ item.week }}</p>
            <img class="select" src="@/assets/service/select.png" alt="" />
          </div>
        </div>
        <div class="package_item package_item_more" @click="checkDatePackage()" v-if="packageArr.length>5">
          <img class="more_icon" src="@/assets/service/more.png" alt="" />
          <p class="more_text">查看更多</p>
        </div>
      </div>
      <img class="notime" v-if="packageArr.length==0" src="@/assets/service/notime.png" alt="">
    </div> -->
    <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></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="Collection" v-if="packageArr.length > 0">
      <div class="box box1">
      </div>
      <div class="box box2">
        <span v-if="detailData.applyCount>=detailData.stockCount" class="disabled">已满团</span>
        <span v-else @click="checkDatePackage()">去订购</span>
      </div>
    </div>
    <van-dialog v-model="showTip" title="温馨提示" show-cancel-button confirm-button-color="#3385FF" cancel-button-color="#999" confirm-button-text="同意" cancel-button-text="再想想" @confirm="tipConfirm">
      <div class="show_tip_title" slot="title">
        <img src="@/assets/service/tip.png" alt="">
        <p>温馨提示</p>
      </div>
      <p class="show_tip">本研学课程由活动承接方提供，<b>“红色网上游——柯桥研学”</b>只提供课程展示，不参与任何经营性销售，也不进行任何政府引导购买行为，是否参加研学课程及选择服务内容，由学生和家长根据需要，自主决定、自愿报名，相关费用直接向研学活动承接方支付。</p>
      <van-checkbox class="tip_checkbox" v-model="tipChecked" shape="square">我已了解提示内容，不再提示该消息</van-checkbox>
    </van-dialog>
  </div>
</template>
<script>
import AbroadDes from './component/AbroadDetail/AbroadDes';
import AbroadBase from './component/AbroadDetail/AbroadBase';
import AbroadEvaluate from './component/AbroadDetail/AbroadEvaluate';
import CountDown from './component/AbroadDetail/CountDown';
import AbroadCoupon from './component/AbroadDetail/AbroadCoupon';
import './AbroadDetail.scss';
export default {
  name: "ServiceAbroadDetail",
  data () {
    return {
      courseId: "",
      detailData: "",
      packageData: [], //未处理过格式的套餐表
      packageActive: 0,
      packageTypeActive: 0,
      packageArr: [], //套餐时间价格
      initPackageArr: false,//packageArr已生成
      showCourseTable: true,
      unionId: '',
      centerNo: '',
      showTip: false,
      PackageQuery: '',
      tipChecked:false
    };
  },
  mounted () {
    localStorage.removeItem('useCard')
    this.courseId = this.$route.query.courseId;
    this.centerNo = localStorage.getItem('centerNo')
    this.GetCourseDetail();
  },
  methods: {
    // 点击套餐日期
    handlePackageDay (index) {
      this.packageActive = index;
      this.packageTypeActive = 0;//重置套餐类型选择
      //TODO 获取该日所包含的套餐
    },

    // 点击预约
    checkDatePackage () {
      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.PackageQuery = query
      const AbroadDetailTipChecked = localStorage.getItem('AbroadDetailTipChecked');
      if (AbroadDetailTipChecked) {
        this.$router.push({ name: "ServiceDatePackage", query: query });
      } else {
        this.showTip = true;
      }
    },
    tipConfirm () {
      if (this.tipChecked) {
        localStorage.setItem('AbroadDetailTipChecked', 1)
      }
      this.$router.push({ name: "ServiceDatePackage", query: this.PackageQuery });
    },
    // 获取产品详情
    GetCourseDetail () {
      if (!this.courseId) {
        this.$toast.fail('产品id缺失，请从正确的途径访问')
        return;
      }
      this.$toast.loading({
        message: "加载中...",
        duration: 0,
        forbidClick: true,
      });
      this.mgop({
        api: 'mgop.sz.hswsy.GetCourseDetail', // 必须
        host: 'https://mapi.zjzwfw.gov.cn/',
        dataType: 'JSON',
        type: 'POST',
        appKey: 'fuxgnukl+2001895516+edccpx', // 必须
        headers: {
          //   'isTestUrl': '1'
        },
        data: {
          "id": this.courseId,
          "cs": "绍兴市",
        },
        onSuccess: 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,
                id: detailData.id,
                marketPrice: detailData.marketPrice,
                price: detailData.price,
              })
            );
            this.getPackageData(); //获取套餐列表
          } else {
            let message = res.data.message;
            if (!message) {
              message = '产品不存在'
            }
            this.$toast.fail(message)
          }
        },
        onFail: err => {
          console.log('err', err)
        }
      });
    },

    // 获取套餐列表
    getPackageData () {
      let startDate = this.Moment().format("YYYY-MM-DD");
      let endDate = this.Moment().add(60, "days").format("YYYY-MM-DD");
      this.mgop({
        api: 'mgop.sz.hswsy.DateComboBindList', // 必须
        host: 'https://mapi.zjzwfw.gov.cn/',
        dataType: 'JSON',
        type: 'GET',
        appKey: 'fuxgnukl+2001895516+edccpx', // 必须
        headers: {
          //   'isTestUrl': '1'
        },
        data: {
          "productId": this.detailData.id,
          "startDate": startDate,
          "endDate": endDate,
        },
        onSuccess: 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();
          }
        },
        onFail: err => {
          console.log('err', err)
        }
      });
    },
    // 设置套餐价格
    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 = 999;
        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)
        }
        packageArr.push({
          day: packageDate.format("M/D"),
          date: packageDate.format("YYYY-MM-DD"),
          week: week,
          marketPrice: marketPrice,
          comboInfoList: comboInfoList,
        });
      }
      this.packageArr = packageArr;
      this.initPackageArr = true
    },
    // 联系客服
    contactService () {
      if (this.detailData.mobiles) {
        location.href = "tel://" + this.detailData.mobiles.split(",")[0];
      }
    },
    // 返回首页
    backHome () {
      this.$router.push({ name: "ServiceKQ" });
    },
  },
  components: {
    AbroadDes,
    AbroadBase,
    AbroadEvaluate,
    CountDown,
    AbroadCoupon
  }
};
</script>
