<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"
      :isAddMark="isAddMark"
      :userType="userType"
      :setting="setting"
      :joinClass ="joinClass"
      :READER_MODE ="READER_MODE"
      :gradesName = "gradesName"
      :userInfoparms = "userInfo"
      :teacherDateclass = "classList"
      :teacherData = "teacherData"
      :studentData = "studentData"
      :robotData = "robotData"
      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"
      :action = "action"
      :headers  = "headers"
      :data = "extradata"
      :isShowTeacherResource="true"
      :continueReading="true"
      :basisPath="basisPath"
      :pageType="pageType"
  
    />
    <!-- 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'

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,
      userType: 'teacher',
      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(){

      return 60;
    }
  },
  created() {
    
    this.bookId = this.$route.query.bookId

    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")

    this.isTrial = this.$route.query.isTrial=="true"?true:false    

    if (!this.userId){
      this.isTrial = true
    }
     this.extradata = processReuestData({})

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

     
     if (userType){
      this.userType = userType
     }


    
    if (this.$route.query.type) {
      this.pageType = this.$route.query.type
      // this.isTrialIndex = Number(this.$route.query.isTrialIndex)
      if (this.$route.query.isTrialIndex) {
        this.isTrial = true
      }
    }

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

    this.request()//  请求数据
    setTimeout( async() => {
      // this.getData()
     await this.getMineData()
     await  this.studySituation()
      // this.getSetting()
    }, 800)
  },

  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 locationData = await bookApi.userAction.getReadLocation({bookId:this.bookId})
  //  this.location = locationData.location


   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()
     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()

     var  mydata = this.looseLeafData['1803310246204116992']
     
     var  mylooseLeafInfo = JSON.parse(mydata.looseLeafInfo)
     debugger
     this.basisPath = res.basisPath
     
   }

   this.show = true
    this.fullscreenLoading = false
    this.digitalTeaching = true 

   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.classList = await bookApi.user.classList({bookId:this.bookId})

    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({
        userId: this.userId,
        classId: this.classId
      })

      
      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

      }

  },
    
    // 学生笔记操作 start
    addNote(model) {
      bookApi.note.add({
        bookId:this.bookId,
        data:JSON.stringify(model)
      })
      this.addData('notes', model)
    },
    editNote(model) {
      bookApi.note.edit({
        bookId:this.bookId,
        data:JSON.stringify(model)
      }) 
      this.updateData('notes', model)
    },
    deleteNote(model,feedback) {
     
         bookApi.note.delete({
        bookId:this.bookId,
        data:JSON.stringify(model)
      }) 
      this.deleteData('notes', model)
      feedback()
    },

    // 教师笔记操作 start
    addTeacherNote(model, rollback) {
      bookApi.resource.add({
        bookId:this.bookId,
        data:JSON.stringify(model)
      })  
          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()
    },

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

      bookApi.highlight.add({
        bookId:this.bookId,
        data:JSON.stringify(model)
      })
      this.addData('highlight', model)
    },
    // 高亮删除
    deleteHighlight(model, rollback) {

      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)) || {}
    },

    // 更新笔记
    updateNotes(model) {

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

    // 添加书签
    addBookmark(e) {  
      bookApi.bookmark.add({
        bookId:this.bookId,
        data:JSON.stringify(e)
      })
      this.addData('bookmark', e)
    },

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

    // 添加数据
    addData(type, item) {
      this.data[type].list.push(item)
      let list = JSON.stringify(this.data)
      localStorage.setItem('simulated-data_' + this.textBookData.id, list)
      this.getData(type, item)
    },



    async getMineData(){


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

      })
     
      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
      })
      

    },
    // 查询数据
    getData(type, item) {
      setTimeout(() => {
        // JSON.parse(localStorage.getItem('simulated-data_' + this.textBookData.id))
        
        this.data = 
        JSON.parse(localStorage.getItem('simulated-data_' + this.textBookData.id))
        
        || {
          notes: {
            list: []
          },
          bookmark: {
            list: []
          },
          highlight: {
            list: []
          },
          resources: {
            list: []
          }
        }
        // 
      }, 300)
    },
    getSetting() {
      this.setting = JSON.parse(localStorage.getItem('setting_#_' + this.textBookData.id)) || {}
    },

    // 更新数据
    updateData(type, item) {
      console.log(item)
      let i = this.data[type].list.findIndex((items) => items.id == item.id)
      this.data[type].list[i] = item
      let list = JSON.stringify(this.data)
      localStorage.setItem('simulated-data_' + this.textBookData.id, list)
      this.getData(type, item)
    },

    // 删除数据
    deleteData(type, item) {
      console.log(item,"deleteData")
      let i = this.data[type].list.findIndex((items) => items.id == item.id)
      this.data[type].list.splice(i, 1)
      let list = JSON.stringify(this.data)
      localStorage.setItem('simulated-data_' + this.textBookData.id, list)
      this.getData(type, item)
    },

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

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

      
      console.log('我要更新阅读进度了'+newLocation)
      bookApi.userAction.updateReadLocation({
        bookId:this.bookId,
        data: newLocation.location
      })
      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)
    },

    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
      }

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

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

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

    },


  }
}
</script>