<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
                  :style="{
                    color: Number(item.amount) > 0 ? '#26A2FF' : 'red'
                  }"
                  >{{
                    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"
      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"
            class="copyCode"
            @click="getCourseCode"
            >复制链接</van-button> -->
            <button ref="copys"  id="copyLink"  data-clipboard-action="copy" data-clipboard-target="#copy_text" @click="copy">复制链接</button>
        </div>
      </div>
    </van-overlay>
    
    <input type="text" v-model="giveLink"  id="copy_text" style="opacity: 0">
  </div>
</template>
<script>
import { getCourseRecordList, createCourseCode ,getDealerCourseDetail} from "../api";
import {setWxConfig} from '../utils'
import Clipboard from "clipboard";
import axios from "axios";
import courseList from "../components/courseList.vue";
import wx from "weixin-js-sdk";
export default {
  name: "",
  components: { courseList },
  props: [],
  data() {
    return {
      subjectId:0,
      courseId:0,
      showShare: false,
      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: [],
      copyBtn:null,
    };
  },
  computed: {
    courseInfo() {
      let list = [];
      if (this.courseDetail && this.courseDetail.userId != 0) {
        list.push(this.courseDetail);
      }
      return list;
    }
  },
  created() {
    this.init();
    // setWxConfig();
  },
  mounted(){
    this.copyBtn = new Clipboard(this.$refs.copys);
  },
  methods: {
    setShare(){
      wx.ready(function () {
        console.log("微信配置成功")
      })
      wx.error(function (res) {
        console.log("微信配置失败",res)
      })
      // if(this.$isWx){
      //   wx.ready(function () {
      //     console.log("微信配置成功")
      //   })
      //   wx.error(function (res) {
      //     console.log("微信配置失败",res)
      //   })
      // }
    },
    //分享链接
    shareLink(){
      if(this.$isWx){
        wx.updateAppMessageShareData({ 
          title: this.courseDetail.subjectName, // 分享标题
          desc: '点击查看课程', // 分享描述
          link: this.giveLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: this.courseDetail.subjectThumb, // 分享图标
          success: function () {
            // 设置成功
            console.log("分享成功")
            // this.$toast.success('')
          }
        })
      }else{
        this.$toast.fail('请在微信中打开分享')
      }
    },
    //复制
    copy () {
      let _this = this
      let clipboard = _this.copyBtn
      clipboard.on('success', function () {
        _this.$toast.success('复制成功')
      })
      clipboard.on('error', function (e) {
        console.error('复制失败',e)
      })
    },
    // 分享课程方式选择
    onSelect(option) {
      if (option.name == "复制链接") {
        this.showGive = true;
        this.showShare = false;
      }
    },
    //获取课程详情
    getCourseDetail(){
      getDealerCourseDetail(this.courseId).then(res=>{
        this.courseDetail = res
      })
    },
    // 获取课程码
    getCourseCode() {
      createCourseCode(this.courseDetail.subjectId).then(res => {
        this.giveLink = `点我领取课程，1小时内可领取有效 ${window.location.href.split("#")[0]}#/courseDetail/${
          this.subjectId
        }?code=${res}`;
        console.log(this.giveLink)
        this.showGive = true;
        // this.getCourseDetail();
        // this.copyLink().then(()=>{
        //   this.$toast.success('复制成功')
        //   this.showGive = false;
        // })
      });
    },
    // 复制剪切板
    copyLink() {
      let oInput = document.createElement("input");
      oInput.value = this.giveLink;
      document.body.appendChild(oInput);
      oInput.select(); // 选择对象
      if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {//兼容ios
        if (!document.execCommand("Copy")) {
          oInput.setSelectionRange(0, oInput.value.length);
        }
      }
      document.execCommand("Copy"); // 执行浏览器复制命令
      document.body.removeChild(oInput);
      return new Promise((resolve,reject)=>{
          if (document.execCommand("Copy")) {
              resolve(this.giveLink);
          }else{
              reject(this.giveLink);
          }
      })
    },
    // 分享弹出
    comfirmCode() {
      // this.showGive = true;
      this.getCourseCode()
    },
    // 触底加载
    getMoreList(done) {
      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.subjectId
      };
      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 || res.pages == 0) {
          if (done) done(true);
          this.noDate = true;
        } else {
          if (done) done();
          this.page.cur++; //下拉一次页数+1
          this.noDate = false;
        }
      });
    },
    // 返回
    onClickLeft() {
      this.$router.go(-1);
    },
    // 初始化
    init() {
      let arr = this.$route.params.id.split('-')
      this.courseId = arr[0];
      this.subjectId = arr[1]
      this.getCourseDetail();
      this.getRecord();
    },
    destroyed() {
      sessionStorage.removeItem("course_detail");
    }
  }
};
</script>
<style scoped lang="scss">
@import url('../utils/navBar.scss');
* {
  margin: 0;
  padding: 0;
}
img {
  display: block;
}
.page {
  background-color: #fff;
  box-sizing: border-box;
  position: relative;
  .courseContent {
    height: calc(100vh - 1.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;
          overflow: hidden;
          &:not(:nth-last-child(1)) {
            border-bottom: 1px solid #efefef;
          }
          .flex-name-num {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-top: 0.1rem;
            & > p {
              font-size: 0.32rem;
              color: #000;
              line-height: 1.5;
            }
            & > span {
              font-size: 0.32rem;
              color: #000;
              line-height: 2;
              margin-left: 0.1rem;
            }
          }
          & > p {
            font-size: 0.28rem;
            color: #666;
            line-height: 1;
          }
          & > span {
            font-size: 0.28rem;
            color: #666;
            line-height: 1;
            display: block;
            margin-top: 0.2rem;
            margin-bottom: 0.1rem;
          }
        }
      }
    }
  }
  .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: 0.32rem;
      color: #333;
      line-height: 0.8rem;
      text-align: center;
      position: relative;
      font-weight: 600;
      position: relative;
      .cancle {
        position: absolute;
        top: 0;
        right: 0;
        font-size: 0.3rem;
        line-height: 0.3rem;
      }
    }
    .msg {
      font-size: 0.27rem;
      text-align: center;
      padding: 0 0.1rem;
    }
    .copy {
      text-align: center;
      margin-top: 0.5rem;
      #copyLink{
        padding: 0px 1rem;
        border-radius: 0.4rem;
        color: white;
        background: rgb(38, 162, 255);
        border-color: rgb(38, 162, 255);
        line-height: .75rem;
        border: 0;
        outline: none;
      }
      p {
        font-size: 0.22rem;
        color: #888;
        line-height: 0.3rem;
        margin-bottom: 0.15rem;
      }
    }
  }
}
/deep/ .van-tab--active{
  font-weight: 600;
}
</style>
