<template>
  <div class="learn-report-container" >
    <div class="learn-report" id="learn-report" :ref="learnReportRef" >
        <div class="learn-report-bg">
          <img class="bg" :src="staticImg.learnReportBg" alt="">
          <img class="title-img" :src="staticImg.titleImg" alt="">
          <div class="user-name" >{{state.report?.userNickName || '逻辑狗'}}</div>
        </div>

      <div class="learn-report-content" >
        <!-- 学习天数 -->
      <div class="learn-day" v-if="posterShowState" >
        <div class="user-ava" >
          <img :src="staticImg.learnReportBg" alt="">
        </div>
        <div class="user-name" >{{state.report?.userNickName}}</div>
        <div class="learn-day-desc" >
          <div>我家宝贝已经连续学习<span>{{state.report?.totalStudyDays}}</span>天了</div>
          <div>快来一起学习吧</div>
        </div>
      </div>

      <!-- 学习展示 -->
      <div class="learn-preview" :style="{marginTop: posterShowState ? '16px' : '-16px'}" >
        <div class="learn-preview-data" >
          <div class="data-item"  >
            <div class="staticsc" >
              <span>{{state.report?.totalDuration ? Math.floor( state.report?.totalDuration! / 60) : 0 }}</span>
              <div class="unit" >分钟</div>
            </div>
            <div class="data-item-desc" >
              累计时长
            </div>
          </div>
          <div class="data-item"  >
            <div class="staticsc" >
              <span>{{state.report?.totalStars}}</span>
              <div class="unit" >颗</div>
            </div>
            <div class="data-item-desc" >
              获得星数
            </div>
          </div>
          <div class="data-item"  >
            <div class="staticsc" >
              <span>{{state.report?.accuracy}}</span>
              <div class="unit" >%</div>
            </div>
            <div class="data-item-desc" >
              正确率
            </div>
          </div>
        </div>
        <div class="decator" >
          <img :src="staticImg.decator" alt="">
        </div>
        <div class="audio-play-container" 
          :style="{backgroundImage: `url(${state.report?.task3Image}`}"
        >
          <div v-if="!fco.playing" class="audio-time-total" >
            {{fco.duration}}
          </div>
          <div class="play-button" @click="playAudio" v-if="!fco.playing">
            <img :src="staticImg.playButton" alt="">
          </div>

          <div class="play-process" ref="playProcessRef"   v-show="fco.playing" >
            <van-progress
              @click="updatePercentage"
              class="van-progress"
              :percentage="Number(fco.percentage.toFixed(2)) * 100"
              pivot-color="#FF8024"
              color="#FF8024"
              pivot-text=" "
              track-color="#EDEDED"
            />
            <div class="play-time-process" >
              {{fco.updateTime}}/{{fco.duration}}
            </div>
          </div>
        </div>

        <div class="learn-preview-desc"  v-if="posterShowState" >
          长按扫描二维码，一起查看～
        </div>

      </div>
      <!-- v-if="state.report?.exerciseCardResultList"  -->
      <!-- 练习分析 -->
      <div class="learn-any learn-modle" >
        <div class="learn-modle-title" >
          <img :src="staticImg.learnAny" alt="">
          <div class="learn-title" >今日练习分析</div>
        </div>
        <div class="able-any" >
          <able-chart
            style="margin-bottom: 12px;"
            :title="item.capability"
            :index="index"
            :count="item.correctQuantity"
            v-for="(item, index) in state.report?.exerciseCardResultList"
            :key="item.capability"
          />
        </div>
      </div>
  
      <!-- 家园共育策略 -->
      <div class="home-strategy learn-modle" >
        <div class="learn-modle-title" >
          <img :src="staticImg.strategy" alt="">
          <div class="learn-title" >亲子游戏策略</div>
        </div>
        <div class="strategy" >
          <div class="strategy-item"
            v-for="item in state.report?.teachDescription.split('\n').splice(0, state.report?.teachDescription.split('\n').length)"
            :key="item"
          >
            <div class="dot" ></div>
            <div class="text-content" >
              {{item}}
            </div>
          </div>
        </div>
        <div class="qrcode" v-show="posterShowState">
          <div class="qrcode-img" >
            <img :src="qrcode" alt="">
          </div>
          <div class="qrcode-info" >
            <div class="qrcode-title"> 逻辑狗·一起成长 </div>
            <div class="qrcode-desc">识别二维码，让你家宝贝也来体验吧 </div>
          </div>
        </div>
      </div>

      <!-- 生成报告 -->
      <div class="create-poster" v-if="!posterShowState" >
        <open-app v-if="queryParams.share == 1" />
        <div v-else class="create-button"  @click="openModal">
          <div class="text" >晒报告 <span v-if="!state.shared" >+5</span> </div>
          <img v-if="!state.shared" :src="staticImg.dogCoin" alt="">
        </div>
      </div>

      <!-- 底部图片 -->
      <div class="learn-report-decator" v-if="posterShowState"  >
        <img :src="staticImg.learnReportDecator" alt="">
      </div>
      </div>

    </div>

      <Overlay :show="posterShowState" class="van-overlay" :lock-scroll="false"  :z-index="10"  @click="posterShowState = false">
          <div class="wrapper">
            <div  class="poster-container" id="learnReportRef"></div>
          </div>
      </Overlay>

      <ActionSheet :overlay="false" :show="posterShowState" :closeable="false" :z-index="11" title="晒报告">
          <div class="share-dialog" >
            <div class="share-content" >
              <div class="share-item" @click.stop="savePoster">
                <img :src="staticImg.photo" alt="">
                <span>保存海报</span>
              </div>
              <div class="share-item" @click.stop="shareWx">
                <img :src="staticImg.wechat" alt="">   
                <span>微信好友</span>
              </div>
            </div>
            <div class="cancel-butuon" @click="closeModal" >
              取消
            </div>
          </div>
      </ActionSheet>
  </div>

</template>

<script setup lang="ts">

import { ref, nextTick, onMounted, reactive } from 'vue'
import { useAudioManager } from '@/hook/index'
import AbleChart from '../../components/AbleChart.vue'
import { screenShot, createQrcode } from '@/utils/utils'
import { getReportByUser, shareUserReport } from "@/api/learnPlan"
import { useRoute } from 'vue-router'
import { useAppRouter, useAppFunc } from '@/hook/appHook'
import { Overlay, ActionSheet } from 'vant'
import OpenApp from '@/components/OpenApp/index.vue'
import { registerWxopenButton } from '@/utils/utils'

export interface QueryParams {
  i: string,
  u?: string,
  share?: number
}

const staticImg = {
  learnReportBg: require('@LP/assets/learn-report-bg.png'),
  titleImg: require('@LP/assets/title-img.png'),
  decator: require('@LP/assets/decator.png'),
  playButton: require('@LP/assets/play-button.png'),
  learnAny: require('@LP/assets/learn-any.png'),
  strategy: require('@LP/assets/strategy.png'),
  learnReportDecator: require('@LP/assets/learn-report-decator.png'),
  dogCoin: require('@LP/assets/dog-coin.png'),
  photo: require('@/assets/component/common/photo.png'),
  wechat: require('@/assets/component/common/wechat.png')
}

const [fco, atx] = useAudioManager({
  url: '',
  format: 'mm:ss'
})

const queryParams = useRoute().query as unknown as QueryParams

console.log('timeStamp');


console.log('queryParams:', queryParams);


// queryParams.i = "1630466274125459458"
// queryParams.u = "1430026961974345730"

const posterScaleRate = ref(window.screen.width / window.screen.height > 0.7 ? 0.22 : 0.3)

const userId = ref(queryParams.u)

const appRouter = useAppRouter()

const appFunc = useAppFunc()

const qrcode = ref('')

const posterShowState = ref(false)

const shareShowState = ref(false)

const playProcessRef = ref('')

const learnReportRef = ref('')

const posterblob = ref('')

const playAudio = () => {
  fco.play()
}

const state = reactive<Partial<API.LearnPlan.Task>>({})

const closeModal = () => {

  posterShowState.value = false

}

const initAudioDragEvent = () => {
  let element = Array.from(document.getElementsByClassName('van-progress__pivot'))[0]

  let start = 0;

  let distance = 0;

  element.addEventListener("touchstart", function(event) {
    start = event.touches[0].clientX;
    fco.pause()
  });

  element.addEventListener("touchmove", function(event) {
    distance = event.touches[0].clientX - start + 11;
    console.log(distance);
    if (distance < 0) {
      fco.setPercentage(0)
    } else if (distance  > playProcessRef.value.clientWidth) {
      fco.setPercentage( 1)
    } else {
      fco.setPercentage( distance / playProcessRef.value.clientWidth)
    }
    
  });


  element.addEventListener('touchend', function(e) {
    fco.play()
  }, false);

}

const openModal = () => {
  posterShowState.value = true
  createPoster()
}

const savePoster = () => {
  appFunc.savePoster(posterblob.value)
}

const _shareUserReport = async () => {
  await shareUserReport({ "itemId": queryParams.i, "userId": queryParams.u! })
}

const updatePercentage = (e) => {

  const percentage = (e.layerX / playProcessRef.value.clientWidth)

  fco.setPercentage(percentage)

}

// 分享海报到微信
const shareWx = () => {
  appFunc.shareWx(posterblob.value)
  _shareUserReport()
}

// 获取用户报告信息
const _getReportByUser = async () => {
  
  const { data } = await getReportByUser({ "itemId": queryParams.i, "userId": queryParams.u! })

  fco.src = data.report.userLearnShareAudio
  state.report = data.report
  userId.value = data.userId

  getQrcodeUrl()
}

const createPoster = async () => {
  nextTick(async () => {
    const target = document.getElementById('learnReportRef')!
    if (Array.from(target!.children).length === 0) {
      const posterEl = await screenShot('learn-report')
      posterblob.value = posterEl.src
      posterEl.style.width = window.screen.width * posterScaleRate.value + 'px'
      target.append(posterEl)
      state.shared = 1
    }
  }) 

}

const getQrcodeUrl = async () => {
  
  qrcode.value = await createQrcode(queryParams.u ? window.location.href + `&share=1` :  `${window.location.href}&u=${userId.value}&share=1`)
}

onMounted(async () => {


  if (queryParams.u) {
   _getReportByUser()
  } else {
    await appRouter.getToken()
   _getReportByUser()
  }

  registerWxopenButton()

  initAudioDragEvent()

})

</script>

<style scoped lang="scss">
.learn-report-container {
  padding-bottom: 120px;
  background-color: #F5F5F5;
}
.learn-report {
  width: 100vw;
  background-color: #F5F5F5;
  .learn-report-bg {
    position: relative;
    z-index: 2;
    .bg {
      width: 100vw;
      height: 248px;
      display: block;
      position: relative;
      top: -20px;
      object-fit: cover;
    }
    .title-img {
      width: 146px;
      height: 39px;
      display: block;
      position: absolute;
      top: 98px;
      left: 17px;
    }
    .user-name {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #FFFFFF;
      position: absolute;
      top: 146px;
      left: 20px;
    }
  }

  .learn-report-content {
    margin-top: -70px;
  }

  .learn-day {
    width: 343px;
    height: 125px;
    background: #FEFEFE;
    position: relative;
    z-index: 2;
    margin: 0 auto;
    border-radius: 20px;
    .user-ava {
      width: 62px;
      height: 62px;
      border-radius: 50%;
      background-color: #FFFFFF;
      position: absolute;
      top: -31px;
      left: 50%;
      transform: translateX(-50%);
      display: flex;
      justify-content: center;
      align-items: center;
      img {
        width: 52px;
        height: 52px;
        border-radius: 50%;
        margin: 0 auto;
        object-fit: cover;
      }
    }
    .user-name {
      font-size: 13px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #333333;
      position: absolute;
      top: 39px;
      left: 50%;
      transform: translateX(-50%);
    }
    .learn-day-desc {
      width: 100%;
      position: absolute;
      top: 66px;
      left: 50%;
      transform: translateX(-50%);
      font-size: 13px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #333333;
      display: flex;
      flex-direction: column;
      align-items: center;
      span {
        color: #FF8024;
        font-size: 20px;
      }
    }
  }

  .learn-preview {
    width: 343px;
    height: 488px;
    background: #FEFEFE;
    margin: 16px auto;
    border-radius: 20px;
    overflow: hidden;
    padding: 0 40px;
    box-sizing: border-box;
    position: relative;
    z-index: 2;
    .learn-preview-data {
      width: 100%;
      display: flex;
      justify-content: space-between;
      margin-top: 30px;
      .data-item {
        .staticsc {
          display: flex;
          align-items: flex-end;
          span {
            font-size: 36px;
            font-family: DINAlternate-Bold, DINAlternate;
            font-weight: bold;
            color: #FF8024;
            margin-bottom: -5px;
          }
          .unit {
            font-size: 12px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #999999;
            height: 41px;
            display: flex;
            align-items: flex-end;
          }
        }
        .data-item-desc {
          margin-top: 6px;
          font-size: 12px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #4C4C4C;
        }
      }
    }

    .decator {
      width: 219px;
      height: 16px;
      margin: 0 auto;
      margin-top: 40px;
      img {
        width: 100%;
        height: 100%;
        display: block;
      }
    }

    .audio-play-container {
      width: 262px;
      height: 277px;
      // background-color: #F5F5F5;
      border-radius: 20px;
      margin-top: 30px;
      position: relative;
      background-size: cover;
      .audio-time-total {
        width: 56px;
        height: 24px;
        background: rgba(0,0,0,0.4);
        border-radius: 12px;
        position: absolute;
        left: 15px;
        bottom: 13px;
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #FFFFFF;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .play-button {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        img {
          width: 60px;
          height: 60px;
          display: block;
        }
      }

      .play-process {
        width: 238px;
        position: absolute;
        left: 12px;
        bottom: 9px;
        display: flex;
        flex-direction: column;
        align-items: end;
        .van-progress {
          width: 238px;

        }
        /deep/ .van-progress__pivot {
          width: 12px !important;
          height: 12px;
          border-radius: 50%;
          min-width: 12px;
        }
        .play-time-process {
          font-size: 12px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #FFFFFF;
          margin-top: 4px;
          // position: absolute;
          // bottom: 0px;
          // right: 0px;
        }
      }
    }

    .learn-preview-desc {
      font-size: 13px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #666666;
      margin: 0 auto;
      margin-top: 8px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .learn-modle {
    box-sizing: border-box;
    padding: 30px 20px;
    .learn-modle-title {
      display: flex;
      align-items: center;
      img {
        width: 24px;
        height: 24px;
        display: block;
        margin-right: 5px;
      }
      .learn-title {
        font-size: 16px;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: #333333;
      }
    }
  }

  .learn-any {
    width: 343px;
    border-radius: 20px;
    background: #FEFEFE;
    margin: 0 auto;
    margin-top: 16px;
    box-sizing: border-box;
    padding-bottom: 18px;
    .able-any {
      margin-top: 20px;
    }
  }

  .home-strategy {
    width: 343px;
    border-radius: 20px;
    background: #FEFEFE;
    margin: 0 auto;
    margin-top: 16px;
    box-sizing: border-box;
    position: relative;
    z-index: 3;
    .strategy {
      width: 303px;
      background: #FDF8F5;
      border-radius: 10px;
      padding: 16px;
      box-sizing: border-box;
      margin-top: 20px;
      .strategy-item {
        display: flex;
        align-items: flex-start;
        .dot {
          width: 4px;
          height: 4px;
          background: #FE6E2C;
          margin-right: 8px;
          margin-top: 8px;
          border-radius: 50%;
        }
        .text-content {
          width: 261px;
          font-size: 14px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #333333;
          line-height: 22px;
          margin-bottom: 8px;
        }
      }
    }

    .qrcode {
      display: flex;
      align-items: center;
      margin-top: 20px;
      .qrcode-img {
        width: 73px;
        height: 73px;
        background: #0043BD;
        border-radius: 8px;
        margin-right: 14px;
        img {
          width: 100%;
          height: 100%;
          display: block;
        }
      }
      .qrcode-info {
        display: flex;
        flex-direction: column;

        .qrcode-title {
          font-size: 15px;
          font-family: PingFangSC-Semibold, PingFang SC;
          font-weight: 600;
          color: #333333;
          line-height: 24px;
        }
        .qrcode-desc {
          font-size: 13px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #666666;
          line-height: 24px;
        }
      }
    }
  }

  .learn-report-decator {
    // position: relative;
    // left: 0px;
    // bottom: 0px;
    width: 375px;
    height: 144px;
    z-index: 2;
    img {
      width: 100%;
      height: 100%;
      display: block;
    }
  }

  .create-poster {
    width: 100vw;
    height: 88px;
    background: #FEFEFE;
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 3;
    padding-top: 9px;
    box-sizing: border-box;
    display: flex;
    align-items: flex-start;
    justify-content: center;
    .create-button {
      width: 334px;
      height: 52px;
      background: #FF8024;
      border-radius: 26px;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 0 auto;
      .text {
        font-size: 18px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #FFFFFF;
      }
      img {
        width: 24px;
        height: 24px;
        display: block;
        margin-left: 8px;
      }
    }
  }
}

.van-overlay {
  width: 100vw;
  height: 100vh;
  background-color: rgba(0,0,0,0.4);
  z-index: 11;
}
.wrapper {
    width: 100vw;
    height: 100vh;
    overflow-y: scroll;
    z-index: 40;
    .poster-container {
      position: fixed;
      left: 50%;
      top: 6%;
      transform: translateX(-50%);
    }
  }

  .share-dialog {
    padding: 0px 86px;
    box-sizing: border-box;
    height: 236px;
    width: 100%;
    position: relative;
    background-color: #fff;
    .share-content {
      display: flex;
      justify-content: space-between;
      .share-item {
        display: flex;
        flex-direction: column;
        justify-content: center;
        margin-top: 18px;
        align-items: center;
        img {
          width: 51px;
          height: 51px;
          display: block;
          margin-bottom: 6px;
        }
      }
    }
    .cancel-butuon {
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 600;
      color: #333333;
      position: absolute;
      bottom: 40px;
      left: 50%;
      transform: translateX(-50%);
    }
    
  }
</style>
