<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"
        :teacherDate="teacherData"
        :studentData="studentData"
        :robotData="robotData"
        :linkOpenLabel="true"
        :isOperation="isOperation"
        :generalAPI="generalAPI"
        :robotName="robotName"
        :isOpenStudy="isOpenStudy"
        :action="action"
        :headers="headers"
        :data="extradata"
        :isShowTeacherResource="true"
        :continueReading="true"
        :basisPath="basisPath"
        :pageType="pageType"
        :isOpenHyperlink="true"
        :isShowAi="isShowAi"
        @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"
      />
    </div>

    <div v-show="showError">
      <no-data :msg="errormsg"></no-data>
    </div>
     <!-- <AIFloatButton v-if="true" /> -->
     <AIFloatButton v-if="false" :model-auth-key="aiModelAuthKey" openText="信息技术"
     knowledge-base-id="99cfea95-02a9-4456-898f-5c37204d1763" :knowledge-base-auth-key="aiKnowledgeBaseAuthKey" />
  </div>
</template>

<script>
import NoData from '../components/noData.vue'
import Navigation from '../components/Navigation'
import { getStore, processReuestData } from '../utils/mUtils'
import { bookApi } from '../service/getData'
import Vue from 'vue'
import XML from '../plugin/xml-digital-teaching/lib/index'
import { eventBus } from '../eventBus'
import AIFloatButton from '../components/AIChatModuleVue2/AIFloatButton.vue';

Vue.use(XML)

export default {
  components: {
    NoData,
    Navigation,
    AIFloatButton
  },
  data() {
    return {
      // 基础数据
      bookId: '',
      chapterId: '',
      textBookData: {},
      catalogList: [],
      looseLeafData: {},
      location: '',
      basisPath: 'https://smile-ebook.oss-cn-qingdao.aliyuncs.com/newjc/',
      
      // UI 状态
      show: false,
      showError: false,
      fullscreenLoading: true,
      errormsg: '无数据',
      digitalTeaching: false,
      
      // 用户相关
      userId: '',
      userType: 'teacher',
      userInfo: {},
      classList: [],
      classId: 0,
      className: '',
      teacherData: {},
      studentData: {},
      
      // 试用相关
      isTrial: true,
      isTrialIndex: 30,
      trialChapterList: [],
      
      // 功能开关
      isOpenStudy: true,
      isAddMark: true,
      isOperation: true,
      isShowAi: '0',
      
      // 阅读器配置
      READER_MODE: 'immersive',
      pageType: 'pc',
      joinClass: '',
      gradesName: '班级名称',
      setting: {},
      
      // 数据列表
      data: {
        notes: { list: [] },
        bookmark: { list: [] },
        highlight: { list: [] },
        resources: { list: [] }
      },
      
      // API 配置
      action: '/api/smile/uploadResources',
      headers: {},
      extradata: {},
      generalAPI: {
        isCatalogStudent: true,
        getCatalogStudent: e => this.getCatalogStudent(e)
      },
      
      // AI 机器人配置
      robotName: this.$route.query.robotName || '小新',
      robotData: {
        appId: '44425659-f566-4841-a55c-26ade9813ac7',
        token: 'bce-v3/ALTAK-b9aN76J3Uvh578XNMZcnk/d85af61f15629f8ce23cdbd1e242cfa9e58c54c2',
        baseUrl: '/baiduAi/v2/app/conversation',
        conversationUrl: '/baiduAi/v2/app/conversation/runs'
      },
      

      // 自主ai 配置 
      aiModelAuthKey : "bce-v3/ALTAK-8VwDu2U2h5TcsgFBpUpDH/804815c6b7f21fdfe716c7c8c1269e105c3105e6" ,// 替换为实际的模型认证密钥
      aiKnowledgeBaseAuthKey : "Bearer bce-v3/ALTAK-Whk44lUWwOsyro8mNlVhq/a0f9f719410e695928289034690003afe1571556" ,// 替换为实际的知识库认证密钥
      // 其他
      pkid: ''
    }

  },

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

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


    let title =  this.$route.query.title
    if (title){
      document.title = title 
    }
    
    if (this.$route.query.isOpenStudy=="false"){
      this.isOpenStudy = false
    }
    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
     }


    
  



    await this.request()//  请求数据

    await this.getMineData() // 获取我的数据（笔记、书签、高亮、资源）
    await this.studySituation() // 获取学情数据

      // this.getSetting()
  },

  mounted() {
    this.$store.state.showNaotu = true
    
    // 监听阅读模式切换事件
    eventBus.$on('changeMode', (data) => {
      if (this.$refs.xmlDigitalTeaching) {
        if (data) {
          this.$refs.xmlDigitalTeaching.READER_MODE('immersive')
        } else {
          this.$refs.xmlDigitalTeaching.READER_MODE('initial')
        }
      }
    })
  },
 
  methods: {
    /**
     * 初始化请求数据
     */
    async request() {
      // 检测设备类型
      this.pageType = /Mobi|Android|iPhone/i.test(navigator.userAgent) ? 'h5' : 'pc'

      // 获取书籍基本信息
      const res = await bookApi.bookinfo.json({ bookId: this.bookId })

      if (res) {
        // 加载书籍详情
        const detailRes = await fetch(res.LOCAL_VIEW_DETAIL, { mode: 'cors' })
        this.textBookData = await detailRes.json()
        document.title = this.textBookData.textBooksName
        this.$store.state.textBookData = this.textBookData

        // 加载目录
        const catalogRes = await fetch(res.LOCAL_VIEW_CATALOG, { mode: 'cors' })
        this.catalogList = await catalogRes.json()

        // 加载书籍数据
        const dataRes = await fetch(res.LOCAL_VIEW_DATA, { mode: 'cors' })
        this.looseLeafData = await dataRes.json()

        // 设置基础路径和阅读位置
        this.basisPath = res.basisPath
        this.location = localStorage.getItem(this.textBookData.id)
      }

      // 显示组件
      this.show = true
      this.fullscreenLoading = false

      // 获取购买信息
      const bookInfo = await bookApi.bookinfo.request_info({ bookId: this.bookId })
      if (bookInfo) {
        this.isTrial = bookInfo.isBuy === 0
      }

      // 获取试用章节列表
      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 })

      // 获取用户信息
      this.userInfo = await bookApi.user.info()
      this.digitalTeaching = true

      // 获取班级列表
      try {
        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
        }
      } catch (error) {
        console.error('获取班级列表失败:', error)
      }

      // 初始化用户数据和学情
      this.getUerData()
      this.studySituation()

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


    /**
     * 获取用户数据
     */
    async getUerData() {
      const user = {
        nickname: this.userInfo.nickname,
        className: this.className,
        img: this.userInfo.img
      }

      if (this.userType === 'teacher') {
        this.teacherData = user
      } else if (this.userType === 'student') {
        this.studentData = user
      }
    },
    /**
     * 获取学情数据
     */
    async studySituation() {
      const res = await bookApi.study.info({
        bookId: this.bookId,
        userId: this.userId,
        classId: this.classId
      })

      if (!res) return

      if (this.userType === 'teacher') {
        if (res.teacherInfo && res.teacherInfo.length > 0) {
          const item = res.teacherInfo[0]
          this.teacherData = {
            ...item,
            className: item.nickname,
            img: item.headImg
          }
        }
        this.$nextTick(() => {
          this.$set(this.teacherData, 'studentList', res.studentList)
        })
      } else if (this.userType === 'student') {
        if (res.length > 0) {
          const studentInfo = res[0]
          this.studentData = {
            ...studentInfo,
            testNum: studentInfo.testNum,
            noteNum: this.data.notes.list.length,
            bookmarkNum: this.data.bookmark.list.length,
            lineationNum: this.data.highlight.list.length
          }
        }
      }
    },

    /**
     * 获取章节学习情况
     * @param {Object} e - 章节信息，包含 id
     */
    getCatalogStudent(e) {
      return new Promise((resolve, reject) => {
        bookApi.study.chapterInfo({
          userId: this.userId,
          bookId: this.bookId,
          chapterId: e.id
        })
          .then(res => {
            const resnew = { data: { ...res[0] } }
            resolve(resnew)
          })
          .catch(error => {
            console.error('获取章节学习情况失败:', error)
            reject(error)
          })
      })
    },

    /**
     * 点击响应后刷新数据
     */
    async clickToRespond() {
      await this.getMineData()
      await this.studySituation()
    },

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

    /**
     * 编辑笔记
     */
    editNote(model) {
      bookApi.note.edit({
        bookId: this.bookId,
        data: JSON.stringify(model)
      })
      this.updateData('notes', model)
    },

    /**
     * 删除笔记
     */
    async deleteNote(model, feedback) {
      await bookApi.note.delete({
        bookId: this.bookId,
        data: JSON.stringify(model)
      })
      this.deleteData('notes', model)
      feedback()
    },

    // ========== 教师笔记操作 ==========
    /**
     * 添加教师笔记
     */
    async addTeacherNote(model) {
      await 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()
    },

    // ========== 高亮操作 ==========
    /**
     * 添加高亮
     */
    async addHighlight(model) {
      await bookApi.highlight.add({
        bookId: this.bookId,
        data: JSON.stringify(model)
      })
      this.addData('highlight', model)
    },

    /**
     * 删除高亮
     */
    async deleteHighlight(model) {
      await bookApi.highlight.delete({
        bookId: this.bookId,
        data: JSON.stringify(model)
      })
      this.deleteData('highlight', model)
    },

    /**
     * 设置变更
     */
    // eslint-disable-next-line no-unused-vars
    settingChange(key, value) {
      // 预留设置变更逻辑
    },

    /**
     * 更新笔记
     */
    async updateNotes(model) {
      await bookApi.note.edit({
        bookId: this.bookId,
        data: JSON.stringify(model)
      })
      this.updateData('notes', model)
      this.getUerData()
    },

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

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

    // ========== 数据管理 ==========
    /**
     * 添加数据后刷新
     */
    // eslint-disable-next-line no-unused-vars
    async addData(type, item) {
      await this.getMineData()
      await this.studySituation()
    },

    /**
     * 更新数据后刷新
     */
    // eslint-disable-next-line no-unused-vars
    async updateData(type, item) {
      await this.getMineData()
      await this.studySituation()
    },

    /**
     * 删除数据后刷新
     */
    // eslint-disable-next-line no-unused-vars
    async deleteData(type, item) {
      await this.getMineData()
      await this.studySituation()
    },

    /**
     * 获取我的数据（笔记、书签、高亮、资源）
     */
    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
      })
    },

    /**
     * 获取设置
     */
    getSetting() {
      this.setting = JSON.parse(localStorage.getItem('setting_#_' + this.textBookData.id)) || {}
    },

    // ========== 其他操作 ==========
    /**
     * 下载资源文件
     */
    // eslint-disable-next-line no-unused-vars
    downloadFile(e) {
      // 下载文件逻辑
    },
    
    /**
     * 更新阅读进度
     */
    async updateReadLocation(newLocation) {
      // 更新阅读位置
      await bookApi.userAction.updateReadLocation({
        bookId: this.bookId,
        data: JSON.stringify(newLocation)
      })
      localStorage.setItem(this.textBookData.id, newLocation.location)

      // 更新学习进度
      const params = {
        chapterId: newLocation.chapterId,
        bookId: this.bookId,
        userId: this.userId,
        classId: this.classId,
        lastAt: Math.floor(Date.now() / 1000),
        learningProgress: newLocation.schedule,
        ...newLocation
      }

      const res = await bookApi.study.update({ data: JSON.stringify(params) })
      this.pkid = res.pkid
    },

    // ========== 教师资源操作 ==========
    /**
     * 添加教师资源
     */
    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) {
      const params = {
        bookId: this.bookId,
        userId: this.userId,
        classId: this.classId,
        xmlCompRef: e.xmlCompRef,
        chapterId: e.chapterId,
        lastAt: Math.floor(Date.now() / 1000),
        type: e.type,
        pkid: this.pkid,
        ...e
      }

      // 根据资源类型设置统计参数
      if (e.type === 'image') {
        params.imgLearnNum = 1
      } else if (e.type === 'audio') {
        params.audioLearnTime = 10
        params.audioLearnNum = 1
        params.time = 10
      } else if (e.type === 'video') {
        params.videoLearnTime = 10
        params.videoLearnNum = 1
        params.time = 10
      } else if (e.type === 'question') {
        params.answersNum = 1
        Object.assign(params, e.e)
      }

      // 更新学习统计
      if (['image', 'audio', 'video', 'question'].includes(e.type)) {
        await bookApi.study.resouceUpdate({ data: JSON.stringify(params) })
      } else {
        await bookApi.study.update({ data: JSON.stringify(params) })
      }

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

    /**
     * 切换班级
     */
    changeClass(e) {
      this.classId = e.pkid
      this.className = e.title
      this.studySituation()
    }


  }
}
</script>