import { Component } from 'react'
import { Provider, ProviderProps } from 'mobx-react'
import Taro from '@tarojs/taro'
import './app.less'
// ======store======
import userInfoStore, { UserInfoStore } from './store/userInfo'
import indexStore, { IndexStore } from './store/index'
import Book, { BookStore } from './store/book'
import classifyStore, { ClassifyStore } from './store/classIfy'
import modalStore from './store/modalStore'

// ======引入全局配置======
import { initApp, setApp } from './config'
// ======引入拦截器=========
import './interceptor'
import api from './server/index'
import { getShortBookInfo } from './server/book/short'
// 引入兼容性工具
import { getAccountInfoSync } from './utils/compatibility'
import { bookrackShrotAddOrRemove } from './server/bookrack'
//引入官方小说阅读插件
const novelPlugin = Taro.requirePlugin('novel-plugin')


export interface Store {
  userInfoStore: UserInfoStore,
  indexStore: IndexStore,
  bookStore: BookStore,
  classifyStore: ClassifyStore,
  modalStore: {
    visible: boolean,    // 弹窗开关
    showModal: () => void,
    hideModal: () => void
  }
}
const store: Store = {
  userInfoStore,
  indexStore,
  bookStore: Book,
  classifyStore,
  modalStore
}
class App extends Component {

  //每次打开小程序触发，后台切入不算
  onLaunch(options) {
    console.log("apponLaunch", options)
    // 监听进入插件页事件
    novelPlugin.onPageLoad(this.onNovelPluginLoad)
  }
  onNovelPluginLoad(data) {
    console.log('onNovelPluginLoad', data)
    // data.id - 阅读器实例 id，每个插件页对应一个阅读器实例
    const novelManager = novelPlugin.getNovelManager(data.id)
    //获取自定义参数
    let customParams = novelManager.getCustomServerParams();
    if (customParams) {
      try {
        customParams = JSON.parse(decodeURIComponent(customParams));
        console.log("customParams", customParams)
      } catch (e) {
        console.error('解析失败', e);
      }
    }
    //假如书籍已在书架改变插件书架状态
    if (customParams && customParams.inBookshelf) {
      novelManager.setBookshelfStatus({
        bookshelfStatus: 1
      })
    }

    // 默认设置目录状态
    novelManager.setContents({
      contents: [
        {
          index: 0, // 第一章
          status: 0, // 免费
        },
        {
          index: 1, // 第二章
          status: 0, // 未解锁
        },
        {
          index: 2, // 第三章
          status: 0, // 已解锁
        },
      ],
    })
    // 监听用户行为事件
    novelManager.onUserTriggerEvent(res => {
      /**
       * 判断res.event_id为以下哪个事件
       * start_read	开始阅读书籍时
        leave_readpage	用户离开阅读页时
        read_error	内容发生报错时
        change_chapter	切换章节时
        change_page	翻页时
        open_menu	唤起一级菜单时
        close_menu	轻触收起一级菜单时
        open_content	唤起目录页时
        close_content	收起目录页时
        open_setting	唤起设置面板
        close_setting	收起设置面板
        expose_introduction	书籍介绍页曝光
        click_addbookshelf	点击“加入书架”
        click_startread	点击“开始阅读”
        leave_introduction	离开当前页
        get_chapter	拉取章节数据结束
        page_show	插件页 onShow 生命周期
        page_hide	插件页 onHide 生命周期
        page_unload	插件页 onUnload 生命周期
        change_fontsize	调整字号时
        change_flipmode	调整翻页模式时
        change_background	调整背景色或夜间模式时
        ad_error	广告报错时
        close_ad	关闭广告时
        leave_chapter	离开章节时
        click_listen	点击听书按钮时
        audio_start	音频播放
        audio_pause	音频暂停
        audio_error	音频报错
        audio_stop	停止播放音频
        audio_end	音频自然播放结束
       * */
      switch (res.event_id) {
        case "start_read":
          console.log("开始阅读")
          break;
        case "get_chapter":
          // 此处做用户阅读记录
          console.log("拉取章节数据结束",res)
          break;
        case "click_startread":
          console.log("点击了开始阅读")
          break;
        case "change_chapter":

          console.log("切换章节")
          break;
        case "change_page":
          console.log("翻页",res)
          break;
        case "leave_readpage":
          console.log("离开阅读页")
          break;
        case "close_ad":
          console.log("关闭广告")
          break;
        case  "ad_error":
          console.log("广告报错")
          break;
      }
    })
    //点击加入书架操作
    novelManager.onClickBookshelf((res) => {
      if (res.bookshelfStatus == 0) {
        console.log("点击了加入书架")
        bookrackShrotAddOrRemove({ bookId: customParams.bookId, add: true })
      } else if (res.bookshelfStatus == 1) {
        console.log("点击了移出书架")
        bookrackShrotAddOrRemove({ bookId: customParams.bookId, add: false })
      }
      novelManager.setBookshelfStatus({
        bookshelfStatus: res.bookshelfStatus == 0 ? 1 : 0
      })
    })
  }
  componentDidMount() {
    /**获取状态栏高度 */
    Taro.getSystemInfo({}).then(res => {
      let { system, statusBarHeight, platform } = res
      indexStore.setData({ navBarTop: statusBarHeight, system })//设置navbar高度和当前系统
      setApp({ system: platform })
    })
  }
  async componentDidShow(options) {
    console.log("appcomponentDidShow", options)
    let { scene, query, path } = options//获取当前小程序进入的场景值
    let bookConfig = Taro.getStorageSync("bookConfig")
    if (bookConfig) {
      Book.setData({ bookConfig: JSON.parse(bookConfig) })
    }
    //阅读页面并且路径存在bookId请求数据
    if (query?.bookId && path === "pages/book/bookArticle/index") {
      getShortBookInfo(query?.bookId)
    }
    indexStore.setData({ scene, query })
    // 启动初始化
    console.log("初始化")
    initApp()//初始化全局变量
    let accountInfo = getAccountInfoSync().miniProgram//获取当前小程序的APPID 
    let { appId, version, envVersion } = accountInfo;
    setApp({
      appId,
      proVersion: version,
      envVersion: envVersion as "develop" | "trial" | "release",
      pathParams: { scene, ...query }
    })
    // 初始化登录,获取登录使用的token存放用于登录使用
    await api.loginInit(appId)

  }
  componentDidHide() { }

  componentDidCatchError() { }
  render() {
    return <Provider store={store}>
      {(this.props as ProviderProps).children}
    </Provider >
  }
}

export default App