<template>
  <div class="page">
    <van-nav-bar
      :title="title"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    ></van-nav-bar>
    <div id="linkCode" style="display: none;" :data-clipboard-text="giveLink">
      {{ giveLink }}
    </div>
    <div class="courseContent">
      <scroller
        ref="recordScroller"
        :on-infinite="getMoreList"
        :list="recordList"
        noDataText="没有更多..."
      >
        <courseList :dataList="courseInfo" :showNum="2"></courseList>
        <div class="record">
          <p>名额变动明细</p>
          <div class="recordList">
            <div
              class="recordLi"
              v-for="(item, index) in recordList"
              :key="index"
            >
              <div class="flex-name-num">
                <p>{{ item.subjectName }}</p>
                <span>{{
                  Number(item.amount) > 0 ? `+${item.amount}` : item.amount
                }}</span>
              </div>
              <p>{{ item.content }}</p>
              <span>{{ item.createTime }}</span>
            </div>
          </div>
        </div>
      </scroller>
    </div>
    <div class="courseShare" @click="comfirmCode">
      <span>赠送课程给好友(当前剩余：{{ courseDetail.amount }}套)</span>
    </div>
    <van-share-sheet
      v-model="showShare"
      title="立即赠送给好友"
      :options="options"
      @select="onSelect"
      :aria-label="giveLink"
      class="linkCodeShare"
    />
    <van-overlay :show="showGive" @click="showGive = false">
      <div class="wrapper" @click.stop>
        <div class="tit">赠送课程给好友<div class="cancle" @click="showGive = false"><van-icon name="cross" /></div></div>
        <div class="msg">请提醒好友尽快点击链接领取课程份额。链接分享后，1小时内有效。</div>
        <div class="copy">
          <p><van-icon name="info-o" /> 链接分享后，1小时内有效</p>
          <van-button style="padding: 0 1rem;border-radius: 0.4rem;" color="#26A2FF"  @click="getCourseCode">复制链接</van-button>
        </div>
      </div>
    </van-overlay>
  </div>
</template>
<script>
import { getCourseRecordList, createCourseCode } from "../api";
import Clipboard from "clipboard";
import axios from "axios";
import courseList from "../components/courseList.vue";
export default {
  name: "",
  components: { courseList },
  props: [],
  data() {
    return {
      showShare: false,
      canReq: true,
      loading: false,
      finished: false,
      activeTab: 0,
      title: "课程详情",
      giveLink: "",
      noDate: false,
      showGive:false,
      options: [
        // { name: '微信', icon: 'wechat' },
        { name: "复制链接", icon: "link" }
        // { name: '二维码', icon: 'qrcode' },
      ],
      page: {
        cur: 1,
        total: 0,
        size: 10
      },
      courseDetail: {
        id: 0, //资产id
        userId: 0, //用户id
        subjectId: 0, //课程id
        subjectName: "",
        subjectThumb: "", //缩略图
        subjectPrice: 0, //课程价格
        sectionsNum: 0, //章节数
        subjectEnable: 1, //是否上架
        amount: 0, //剩余名额
        statistics: {
          saleAmount: 0, //已卖出
          transferOutAmount: 0, //已转入
          transferInAmount: 0 //已转出
        }
      },
      recordList: []
    };
  },
  computed: {
    courseInfo() {
      let list = [];
      if (this.courseDetail && this.courseDetail.userId != 0) {
        list.push(this.courseDetail);
      }
      return list;
    }
  },
  created() {
    this.init();
  },
  methods: {
    // 分享课程方式选择
    onSelect(option) {
      if (option.name == "复制链接") {
        this.showGive = true;
        this.showShare = false;
        // this.$dialog
        //   .confirm({
        //     title: "赠送课程给好友",
        //     message: "请提醒好友尽快点击链接领取课程份额。链接分享后，1小时内有效"
        //   })
        //   .then(() => {
        //     this.showGive = true;
        //     createCourseCode(this.courseDetail.subjectId).then(res => {
        //       this.giveLink = `${
        //         window.location.href.split("#")[0]
        //       }#/courseDetail/${this.$route.params.id}?code=${res}`;
        //       this.copyLink(this.giveLink);
        //     });
        //   })
        //   .catch(err => {
        //     this.showShare = false;
        //   });
      }
    },
    // 获取课程码
    getCourseCode(){
      createCourseCode(this.courseDetail.subjectId).then(res => {
        this.giveLink = `${
          window.location.href.split("#")[0]
        }#/courseDetail/${this.$route.params.id}?code=${res}`;
        this.copyLink(this.giveLink);
      });
    },
    // 微信分享/未使用
    wxShare() {
      let that = this;
      let url = window.location.href;
      let newurl = url.split("#")[0];
      axios(
        "https://i.g107.com/564/Ajax/getJsSdk",
        {
          url: newurl
        },
        {
          headers: {
            "Content-Type": "application/x-www-form-urlencoded"
          },
          transformRequest: [
            function(data) {
              // 对 data 进行任意转换处理
              return qs.stringify(data);
            }
          ]
        }
      )
        .then(function(response) {
          console.log(response);
          var config = response.data;
          var adress = "ceshi";
          wx.config({
            debug: false,
            appId: config.appId,
            timestamp: config.timestamp,
            nonceStr: config.nonceStr,
            signature: config.signature,
            jsApiList: ["updateAppMessageShareData"]
          });
          wx.ready(function() {
            wx.updateAppMessageShareData({
              title: `${that.courseDetail.subjectName}`, // 分享标题
              desc: `分享简介`, // 分享描述
              link: `${window.location.href.split("#")[0]}#/courseAdDetail/${
                this.$route.params.id
              }/code=${res}`, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
              imgUrl: `${that.courseDetail.subjectThumb}`, // 分享图标
              success: function() {
                // 设置成功
              }
            });
          });
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    // 复制剪切板
    copyLink() {
      //创建输入框
      var input = document.createElement("input");
      //对输入框进行赋值
      input.value = this.giveLink;

      //添加到body中。
      document.body.appendChild(input);
      input.select();
      var copyResult = document.execCommand("copy");
      if (copyResult) {
        this.$toast.success("复制成功~");
        this.showGive = false;
        //移除
        document.body.removeChild(input);
      } else {
        navigator.clipboard.writeText(str);
        this.$toast.success("复制成功~");
        this.showGive = false;
      }
    },
    // 分享弹出
    comfirmCode() {
      this.showGive = true;
    },
    // 触底加载
    getMoreList(done) {
      console.log("到底了");
      if (!this.noDate) {
        setTimeout(() => {
          this.getRecord(done);
        }, 300);
      } else {
        this.$refs.recordScroller.finishInfinite(true);
      }
    },
    // 获取课程变动记录
    getRecord(done) {
      let data = {
        page: this.page.cur,
        pageSize: this.page.size,
        subjectId: this.courseId
      };
      getCourseRecordList(data).then(res => {
        this.recordList = this.recordList.concat(res.list);
        this.page.cur = res.current;
        this.page.total = res.total;
        if (res.pages == res.current) {
          console.log('已无更多')
          if (done) done(true);
          this.noDate = true;
        } else {
          console.log('更多...')
          if (done) done();
          this.page.cur++; //下拉一次页数+1
          this.noDate = false;
        }
      });
    },
    // 返回
    onClickLeft() {
      this.$router.go(-1);
    },
    // 初始化
    init() {
      this.courseId = this.$route.params.id;
      this.courseDetail = JSON.parse(sessionStorage.getItem("course_detail"));
      this.getRecord();
      // this.wxShare();
    },
    destroyed() {
      sessionStorage.removeItem("course_detail");
    }
  }
};
</script>
<style scoped lang="scss">
* {
  margin: 0;
  padding: 0;
}
img {
  display: block;
}
.page {
  background-color: #fff;
  box-sizing: border-box;
  position: relative;
  .courseContent {
    height: calc(100vh - 0.9rem);
    position: relative;
    .record {
      border-top: 1px solid #efefef;
      border-bottom: 1px solid #efefef;
      & > p {
        font-size: 0.28rem;
        line-height: 0.8rem;
        color: #000;
        font-weight: 550;
        padding: 0 0.2rem;
      }
      .recordList {
        border-top: 0.02rem solid #efefef;
        // border-bottom: 1px solid #999;
        .recordLi {
          background: #fff;
          padding: 0 0.2rem;
          &:not(:nth-last-child(1)) {
            border-bottom: 1px solid #efefef;
          }
          .flex-name-num {
            display: flex;
            justify-content: space-between;
            align-items: center;
            & > p {
              font-size: 0.32rem;
              color: #000;
              line-height: 2;
            }
            & > span {
              font-size: 0.32rem;
              color: #000;
              line-height: 2;
            }
          }
          & > p {
            font-size: 0.28rem;
            color: #666;
            line-height: 2;
          }
          & > span {
            font-size: 0.28rem;
            color: #666;
            line-height: 2;
          }
        }
      }
    }
  }
  .courseShare {
    width: calc(100% - 0.6rem);
    height: 0.8rem;
    position: absolute;
    left: 0.3rem;
    bottom: 0.1rem;
    background-color: #26A2FF;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 0.15rem;
    span {
      font-size: 0.26rem;
      color: #fff;
    }
  }
  .wrapper{
    background: #fff;
    width: 75%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    border-radius: 0.2rem;
    padding: 0.3rem 0.2rem;
    .tit{
      font-size: .32rem;
      color: #333;
      line-height: .8rem;
      text-align: center;
      position: relative;
      font-weight: 600;
      position: relative;
      .cancle{
        position: absolute;
        top: 0;
        right: 0;
        font-size: .3rem;
        line-height: .3rem;
      }
    }
    .msg{
      font-size: .27rem;
      text-align: center;
      padding: 0 0.1rem;
    }
    .copy{
      text-align: center;
      margin-top: 0.5rem;
      p{
        font-size: .22rem;
        color: #888;
        line-height: .3rem;
        margin-bottom: 0.15rem;
      }
    }
  }
}
</style>
