<template>
  <div v-loading="fullscreenLoading"
  style="height: 100dvh;"
  element-loading-text="书籍加载中，请稍等"

  >
  <navigation></navigation>

    <div class="xml-read" v-if="show">
    <xml-digital-teaching
      v-if="digitalTeaching"
      ref="xmlDigitalTeaching"
      systemEnvId="855e5965-d6a9-4aa0-9933-177e705399af"
      :navBarHeight=navBarHeight
      :textBookData="textBookData"
      :catalogList="catalogList"
      :looseLeafData="looseLeafData"
      :chapterId="chapterId"
      :location="location"
      :notesList="data.notes.list"
      :bookmarkList="data.bookmark.list"
      :resourcesList="data.resources.list"
      :highlightList="data.highlight.list"
      :isTrial="isTrial"
      :isTrialIndex="isTrialIndex"
      :trialChapterList ="trialChapterList"
      :isAddMark="isAddMark"
      :userType="userType"
      :setting="setting"
      :joinClass ="joinClass"
      :READER_MODE ="READER_MODE"
      :gradesName = "gradesName"
      :userInfoparms = "userInfo"
      :teacherDateclass = "classList"
      :teacherData = "teacherData"
      :studentData = "studentData"
      :robotData = "robotData"
      :linkOpenLabel = "true"
      :isOperation = "isOperation"
      robotName = "小新"
      @updateReadLocation="updateReadLocation"
      @addNote="addNote"
      @editNote="editNote"
      @deleteNote="deleteNote"
      @deleteHighlight = "deleteHighlight"
      @addTeacherNote="addTeacherNote"
      @editTeacherNote="editTeacherNote"
      @deleteTeacherNote="deleteTeacherNote"
      @addHighlight="addHighlight"
      @updateNotes="updateNotes"
      @addBookmark="addBookmark"
      @deleteBookmark="deleteBookmark"
      @downloadFile="downloadFile"
      @addResources="addResources"
      @deleteResource="deleteResource"
      @editResources="editResources"
      @settingChange="settingChange"
      @learningStatistics ="learningStatistics"
      @changeClass="changeClass"
      @clickToRespond = "clickToRespond"
      :action = "action"
      :headers  = "headers"
      :data = "extradata"
      :isShowTeacherResource="true"
      :continueReading="true"
      :basisPath="basisPath"
      :pageType="pageType"
      :isOpenHyperlink = "true"
      :isShowAi ="isShowAi"
    />
    <!-- officePreviewPath="https://idocview.xxxxxxx.com/view/url?url=" -->

    </div>
      <div v-show="showError">
      <no-data :msg="errormsg"></no-data>
    </div>
  </div>

</template>

<script>
import {LOCAL_VIEW_DETAIL,LOCAL_VIEW_CATALOG,LOCAL_VIEW_DATA} from "../seed/mock"
import NoData from "../components/noData.vue"
import Navigation from "../components/Navigation"
import {getStore,processReuestData} from '../utils/mUtils'
import {bookApi}  from "../service/getData"
import {eventBus} from '../eventBus'
import Vue from 'vue'
import XML from "../plugin/xml-digital-teaching/lib/index"



Vue.use(XML)

export default {
  components:{
    NoData,
    Navigation,
  },
  data() {
    return {
      action:'http://60.xxxx.137.15:8081/admin-api/teachingMaterial/resource/upload/16550/6940601956829184',
      headers:{Authorization:`eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjYyMDFlYjA3LTY4ZWUtNGJhOC1iMjc3LTk4MjU0ZGI0MzUwMSJ9.zvW8Rr8ShOvwH5i7Cvl9bgp4MtznyLusrY86LMLW7MplNOjRp6j8lx6zkAD4_CvNXVF7v7MsYcRhN90DvhTq1g`},
      digitalTeaching: false,
      isAddMark: true,
      // textBookData: LOCAL_VIEW_DETAIL,
      // catalogList: LOCAL_VIEW_CATALOG,
      // looseLeafData: LOCAL_VIEW_DATA,
      textBookData: {},
      catalogList: [],
      looseLeafData: {},
      bookId: '',
      chapterId:"",
      show:false,
      showError:false,
      fullscreenLoading:true,
      // loadingText:'书籍加载中，请稍等',
      errormsg:'无数据',
      location: '',
      basisPath: 'https://smile-ebook.oss-cn-qingdao.aliyuncs.com/newjc/',
      pageType: 'pc',
      isTrial: false,
      isTrialIndex: 30,
      trialChapterList:[],
      userType: 'teacher',
      isShowAi: "0",
      isOperation:true,
      robotData:{
      // aiAppId = "44425659-f566-4841-a55c-26ade9813ac7"
      // aiToken = "bce-v3/ALTAK-b9aN76J3Uvh578XNMZcnk/d85af61f15629f8ce23cdbd1e242cfa9e58c54c2"
        appId:"44425659-f566-4841-a55c-26ade9813ac7",//应用ID
        token:"bce-v3/ALTAK-b9aN76J3Uvh578XNMZcnk/d85af61f15629f8ce23cdbd1e242cfa9e58c54c2",//应用token
        baseUrl:"/baiduAi/v2/app/conversation",//新建对话接口地址
        conversationUrl: "/baiduAi/v2/app/conversation/runs",//大模型对话接口
        // baseUrl:"https://qianfan.baidubce.com/v2/app/conversation",//新建对话接口地址
        // conversationUrl: "https://qianfan.baidubce.com/v2/app/conversation/runs",//大模型对话接口
      },
      extradata :{},
      READER_MODE:"immersive",
      joinClass:"",
      gradesName:"班级名称",
      data: {
        notes: {
          list: []
        },
        bookmark: {
          list: []
        },
        highlight: {
          list: []
        },
        resources: {
          list: []
        }
      },
      setting: {},
      userInfo:{},
      userId:{},
      classList:[],
      classId:0,
      className:'',
      teacherData:{},
      studentData:{}
    }
  },

  computed:{

    navBarHeight(){

      if (this.isMobileDevice) {
        return 0;
      }
      return  100;
    },
    isMobileDevice() {
        return window.matchMedia("(max-width: 767px)").matches;
      },
  },
  async created() {
    
    // document.title = '新的页面标题';

    debugger
    this.bookId = this.$route.query.bookId


    let title =  this.$route.query.title
    if (title){
      document.title = title 
    }
    
    this.userId = getStore("userId")
    if (this.$route.query.chapterId){
      this.chapterId = this.$route.query.chapterId
    }
    // this.userType = this.$route.query.userType || 'student'
    this.$store.state.redirecturl = this.$route.query.redirecturl
     var userType = getStore("userType")

     

   if (this.$route.query.showAi=="true") {
    this.isShowAi ="0"
   }
   if (this.$route.query.showAi=="false"){
    this.isShowAi ="1"
 
   } 
  
     this.extradata = processReuestData({})

    //  var uploadUrl = "https://local.xinsiketang.com"
    var uploadUrl = ""
     uploadUrl  = uploadUrl+'/api/smile/uploadResources'
     this.action = uploadUrl

     
     if (userType){
      this.userType = userType
     }


    
  



     this.request()//  请求数据

    setTimeout( async() => {
      // this.getData()
     await this.getMineData()
     await  this.studySituation()

      // this.getSetting()
    }, 1600)
  },

  async mounted(){

    var apikey = getStore("apikey")

    // if(!apikey){
    //   this.isAddMark = false
    // }

    this.$store.state.showNaotu = true

   var that = this 

    eventBus.$on('changeMode',(data) =>{

      
      if(data){ 
        that.$refs.xmlDigitalTeaching.READER_MODE("immersive")
      }else{
        that.$refs.xmlDigitalTeaching.READER_MODE("initial") 
      }
    })

  },
 
  methods: {

    async request(){
    


    this.pageType = /Mobi|Android|iPhone/i.test(navigator.userAgent)?'h5':'pc'

    
    // resourcesList({})

    // console.log(this.bookId)

   var res = await bookApi.bookinfo.json({bookId:this.bookId})

  //  res = JSON.stringify(res)
  //  res = res.replaceAll("https://smile-ebook.oss-cn-qingdao.aliyuncs.com/", "fileapi/")
  //  res = JSON.parse(res)

  
   if (res){
     var res1   = await fetch(res.LOCAL_VIEW_DETAIL,{
      mode: 'cors'
     })
     this.textBookData = await res1.json()
     document.title = this.textBookData.textBooksName // 
     var res2 = await fetch (res.LOCAL_VIEW_CATALOG,{
      mode: 'cors'
     })
         this.$store.state.textBookData = this.textBookData
     this.catalogList = await res2.json()
     var res3  = await fetch(res.LOCAL_VIEW_DATA,{
      mode: 'cors'
     })


     console.log(this.catalogList)
     this.looseLeafData = await res3.json()

     
     this.basisPath = res.basisPath

     this.location = localStorage.getItem(this.textBookData.id)


   }

   this.show = true
    this.fullscreenLoading = false
   

   var locationData = await bookApi.userAction.getReadLocation({bookId:this.bookId})
  //  this.location = locationData.location

  var  abc = await bookApi.bookinfo.request_info({bookId: this.bookId})
  
  debugger
  // abc.isBuy = 1
  if (abc){
      if (abc.isBuy == 0) {
      this.isTrial = true
    }
    else {
      this.isTrial = false
    } 
  }



   this.trialChapterList = await bookApi.bookinfo.unlock({bookId:this.bookId})
   if (this.trialChapterList.length>=0){
    this.isTrialIndex = 0;
   }
   


   this.data.resources.list = await bookApi.resource.list({bookId:this.bookId})


   if (this.$route.query.chapterId){
      this.chapterId = this.$route.query.chapterId
    }



    // 
    this.userInfo  = await bookApi.user.info()
    this.digitalTeaching = true 

    try {
      this.classList = await bookApi.user.classList({bookId:this.bookId})

    } catch (error) {
      
      console.log(error)
    }



    if(this.classList.length>0){
      // this.classId = this.classList[0].pkid
      // this.className = this.classList[0].className

      this.classId = this.classList.at(-1).pkid
      this.className = this.classList.at(-1).className
    }
    // this.classId = 12304
    //学情
    this.getUerData()

    this.studySituation()





    var params = {
        bookId:this.bookId,
        userId: this.userId,
        classId: this.classId,
        lastAt:"0",
        learnNum:1
    }
    //  初始化学情
    bookApi.study.update({data:JSON.stringify(params)})
    
  },


  // 用户信息
  async  getUerData(){


    
      var  user = {

        nickname:this.userInfo.nickname,
        className:this.className,
        img:this.userInfo.img,
        // notNum:this.notes.list.length,
        // bookmarkNum:this.bookmark.list.length,//书签数量
        // lineationNum:this.highlight.list.length//划线数量
        }

        
    if(this.userType == "teacher"){

        this.teacherData = user
     }


     if (this.userType == "student")
     {
        this.studentData = user
     }

  },
    // 学情
   async studySituation(){

      
      var res = await bookApi.study.info({
        bookId: this.bookId,
        userId: this.userId,
        classId: this.classId
      })
      
      if (res == undefined){return}
      if (this.userType == "teacher") {

        if (res.teacherInfo.length>0){
          var item  = res.teacherInfo[0]

          this.teacherData = item
          this.teacherData.className = item.nickname
          this.teacherData.img = item.headImg
        }

          // this.teacherData.studentList = res.studentList

        

        this.$nextTick(()=>  this.$set(this.teacherData,"studentList", res.studentList))
       
      
      }

      if (this.userType == "student"){
        
        if (res.length>0){
        res = res[0]
        this.studentData.learningProgress =res.learningProgress
        this.studentData.learnTime =res.learnTime
        this.studentData.learnNum =res.learnNum
        this.studentData.totalLearnTime = res.totalLearnTime
        this.studentData.imgLearnNum = res.imgLearnNum
        this.studentData.audioLearnNum = res.audioLearnNum
        this.studentData.videoLearnNum = res.videoLearnNum
        this.studentData.videoLearnTime = res.videoLearnTime
        this.studentData.audioLearnTime = res.audioLearnTime

        this.studentData.answersNum = res.answersNum

          //     noteNum:'',//笔记数量
          // bookmarkNum:'',//书签数量
          // lineationNum:''//划线数量

  
        }
        
        this.studentData.noteNum= this.data.notes.list.length
        this.studentData.bookmarkNum = this.data.bookmark.list.length
        this.studentData.lineationNum = this.data.highlight.list.length

      }

  },

  async clickToRespond(data){

    
     await this.getMineData()
     await  this.studySituation()

  },
    
    // 学生笔记操作 start
    async addNote(model) {
      this.isOperation = false 
      await bookApi.note.add({
        bookId:this.bookId,
        data:JSON.stringify(model)
      })
      
      this.isOperation = true 

      // await this.getMineData()
      this.addData('notes', model)

    },
    editNote(model) {
      bookApi.note.edit({
        bookId:this.bookId,
        data:JSON.stringify(model)
      }) 
      this.updateData('notes', model)
      
    },
    async deleteNote(model,feedback) {
     
     
          //  this.isOperation = false 

      await   bookApi.note.delete({
        bookId:this.bookId,
        data:JSON.stringify(model)
      }) 
            // this.isOperation = true 

      // await this.getMineData()

      this.deleteData('notes', model)
      feedback()
    },

    // 教师笔记操作 start
   async addTeacherNote(model, rollback) {
     await bookApi.resource.add({
        bookId:this.bookId,
        data:JSON.stringify(model)
      })  
      // await this.getMineData()

          this.addData('resources', model)
    },
    editTeacherNote(model) {
      bookApi.resource.edit({
        bookId:this.bookId,
        data:JSON.stringify(model)
      })  
      this.updateData('resources', model)
    },
    deleteTeacherNote(model, feedback) {
      bookApi.resource.delete({
        bookId:this.bookId,
        data:JSON.stringify(model)
      }) 
      this.deleteData('resources', model)
      feedback()
    },

    // 高亮操作
   async addHighlight(model, rollback) {

   await   bookApi.highlight.add({
        bookId:this.bookId,
        data:JSON.stringify(model)
      })
      // await this.getMineData()

      this.addData('highlight', model)

          
    },
    // 高亮删除
   async deleteHighlight(model, rollback) {

    await  bookApi.highlight.delete({
        bookId:this.bookId,
        data:JSON.stringify(model)
      })
      this.deleteData('highlight', model)
      console.log(model,"model")

      
    },

    settingChange(key, value) {
      // let newSetting = Object.assign({}, this.setting, { [key]: value })
      // localStorage.setItem('setting_#_' + this.textBookData.id, JSON.stringify(newSetting))
      // this.setting = JSON.parse(localStorage.getItem('setting_#_' + this.textBookData.id)) || {}
    },

    // 更新笔记
   async updateNotes(model) {

     await  bookApi.note.edit({
        bookId:this.bookId,
        data:JSON.stringify(model)
      })
       this.updateData('notes', model)
      this.getuserData()

     
    },

    // 添加书签
   async addBookmark(e) {  
   this.isOperation = false 
    await  bookApi.bookmark.add({
        bookId:this.bookId,
        data:JSON.stringify(e)
      })
      this.addData('bookmark', e)
      // this.getuserData()
      setTimeout(()=>{
      this.isOperation = true
      },2000)
      


    },

    // 删除书签
   async deleteBookmark(e) {
   this.isOperation = false 
      bookApi.bookmark.delete({
        bookId:this.bookId,
        pkid:e.pkid,
        data:JSON.stringify(e)
      })
      this.deleteData('bookmark', e)
      this.isOperation = true
    
    },

    // 添加数据
   async addData(type, item) {
     await this.getMineData()
      await  this.studySituation() 
    },



    async getMineData(){


      this.data.notes.list = await bookApi.note.list({
        bookId:this.bookId,

      })
      if(this.data.notes.list){
          this.data.notes.list.map( (val)=>{
          console.log(val.pkid)
        })
      }
   
     
      this.data.bookmark.list = await bookApi.bookmark.list({
        bookId:this.bookId
      })

      this.data.highlight.list = await bookApi.highlight.list({
        bookId:this.bookId
      })
      this.data.resources.list = await bookApi.resource.list({
        bookId:this.bookId
      })

      console.log('11212j3ijio',this.data);
      
      

    },
    // 查询数据
    getData(type, item) {
     
    },
    getSetting() {
      this.setting = JSON.parse(localStorage.getItem('setting_#_' + this.textBookData.id)) || {}
    },

    // 更新数据
    async updateData(type, item) {
      console.log(item)
    
      this.getData(type, item)

      await this.getMineData()
      await  this.studySituation() 
    },

    // 删除数据
    async deleteData(type, item) {
     await this.getMineData()
      await  this.studySituation() 
      console.log(item,"deleteData")
     
      // this.getData(type, item)
      // await this.getMineData()
      // await  this.studySituation() 
    },

    // 下载资源文件
    downloadFile(e) {
      console.log(e)
    },

    // 更新阅读进度
    updateReadLocation(newLocation) {

      
      console.log('我要更新阅读进度了'+newLocation)
      bookApi.userAction.updateReadLocation({
        bookId:this.bookId,
        data: JSON.stringify(newLocation)
      })
      localStorage.setItem(this.textBookData.id, newLocation.location)

        var params ={
          bookId:this.bookId,
          userId: this.userId,
          classId: this.classId,
          lastAt:Math.floor(Date.now() / 1000),
          // learnNum:1,
          learningProgress:newLocation.schedule
      }
      bookApi.study.update({data:JSON.stringify(params)})
    },

    // 添加教师资源
    addResources(e) {
      bookApi.resource.add({
        bookId:this.bookId,
        data:JSON.stringify(e)
      })
      this.addData('resources', e)
    },
    // 删除教师资源
    deleteResource(e) {
      bookApi.resource.delete({
        bookId:this.bookId,
        data:JSON.stringify(e)
      })
      this.deleteData('resources', e)
    },
    // 编辑教师资源
    editResources(e) {
      bookApi.resource.edit({
        bookId:this.bookId,
        data:JSON.stringify(e)
      })
      this.updateData('resources', e)
    },

    async learningStatistics(e){

      
      var params ={
        bookId:this.bookId,
        userId: this.userId,
        classId: this.classId,
        lastAt:Math.floor(Date.now() / 1000),
        // learnNum:1
    }

    if (e.type =="image"){
        
        params.imgLearnNum = 1
      }
      if (e.type =="audio"){
        
        params.audioLearnTime = 10
        params.audioLearnNum = 1 

      }


      if (e.type =="video"){
        
        params.videoLearnTime = 10
        params.videoLearnNum = 1 
      }

      if (e.type =="question"){
        
        params.answersNum = 1
      }

      await bookApi.study.update({data:JSON.stringify(params)})

      await this.getUerData()

      await this.studySituation()
     
       console.log(e)
    },
    changeClass(e){
      
       
         this.classId = e.pkid

         this.className = e.title
         this.studySituation()
      console.log(e)

    },


  }
}
</script>