import request from '@/helpers/request'
import {
  Cell,
  List,
  Sticky,
  Image,
  CellGroup,
  Collapse,
  CollapseItem
} from 'vant'
import { defineComponent } from 'vue'
import styles from './theory.module.less'
import ColSearch from '@/components/col-search'
import ColResult from '@/components/col-result'
import { postMessage, promisefiyPostMessage } from '@/helpers/native-message'
import { state } from '@/state'
import { useEventTracking } from '@/helpers/hooks'
import ColHeader from '@/components/col-header'
import ColSticky from '@/components/col-sticky'
import { getHttpOrigin } from '@/helpers/utils'

export default defineComponent({
  name: 'special',
  data() {
    const query = this.$route.query
    return {
      activeNames: [] as any,
      list: [],
      dataShow: true, // 判断是否有数据
      loading: false,
      finished: false,
      // 1热门资讯,2开屏广告，3闪页管理，4轮播图管理 5按钮管理 6 乐理章节
      params: {
        search: '',
        page: 1,
        rows: 20
      },
      theory: null as null
    }
  },
  mounted() {
    const theoryStr = sessionStorage.getItem('theoryCache')
    if (theoryStr) {
      const theory = JSON.parse(theoryStr)
      this.theory = theory
      const activeNames = theory.activeNames.split(',').map(item => item * 1)
      this.activeNames = activeNames
      this.params.search = theory.search || ''
    }
    this.getList()
    useEventTracking('热门资讯')
  },
  methods: {
    async getList() {
      try {
        const params = this.params
        const res = await request.post('/api-cms/music/theory/app/page', {
          data: {
            ...params
          }
        })
        this.loading = false
        const result = res.data || {}
        // 处理重复请求数据
        if (this.list.length > 0 && result.pageNo === 1) {
          return
        }
        this.list = this.list.concat(result.rows || [])
        this.finished = result.pageNo >= result.totalPage
        this.params.page = result.pageNo + 1
        this.dataShow = this.list.length > 0

        const tempList: any = this.list
        if (this.activeNames.length <= 0) {
          this.list.length > 0 && this.activeNames.push(tempList[0].id)
        }
      } catch {
        this.dataShow = false
        this.finished = true
      }
      // if(this.theory&&this.theory.scrollTop as never){
      //   this.$nextTick(()=>{
      //     window.scrollTo(0, this.theory.scrollTop as never)
      //   })
      //   //
      // }
    },
    onSearch(val: string) {
      this.params.search = val
      this.params.page = 1
      this.list = []
      this.dataShow = true // 判断是否有数据
      this.loading = false
      this.finished = false
      this.getList()
    },
    onDetail(item: any) {
      // let scrollTop  = document.documentElement.scrollTop || document.body.scrollTop;
      // console.log(scrollTop)
      // let obj = JSON.stringify({
      //   search: this.params.search,
      //   activeNames: this.activeNames.join(','),
      //   scrollTop:scrollTop
      // })

      // sessionStorage.setItem('theoryCache', obj)

      if (item.linkUrl) {
        window.location.href = item.linkUrl
      } else {
        // this.$router.push({
        //   path: 'theoryDetail',
        //   query: {
        //     id: item.id
        //   }
        // })
        const client = state.platformType === 'STUDENT' ? 'student' : 'teacher'
        postMessage({
          api: 'openWebView',
          content: {
            url: `${getHttpOrigin()}/${client}/#/theoryDetail?id=${item.id}`,
            orientation: 1,
            isHideTitle: false
          }
        })
      }
    }
  },
  render() {
    return (
      <div class={[styles['theory'], 'theory']}>
        <ColSticky position="top" class={'mb12'}>
          <ColHeader border={false} />
          <ColSearch onSearch={this.onSearch} modelValue={this.params.search} />
        </ColSticky>
        {this.dataShow ? (
          <List
            class={styles.videoList}
            v-model:loading={this.loading}
            finished={this.finished}
            finishedText="没有更多了"
            immediateCheck={false}
            onLoad={this.getList}
          >
            {this.list.map((parent: any) => (
              <Collapse v-model={this.activeNames} border={false}>
                <CollapseItem
                  title={parent.name}
                  name={parent.id}
                  center
                  v-slots={{
                    title: () => (
                      <div class={[styles.groupTitle]}>
                        {parent.url && (
                          <Image
                            src={parent.url}
                            fit="cover"
                            class={styles.groupImg}
                          />
                        )}

                        <p class={['van-ellipsis', styles.musicTitle]}>
                          {parent.name}
                        </p>
                      </div>
                    )
                  }}
                >
                  {parent.newsInformationList.map((item: any) => (
                    <Cell
                      title={item.title}
                      class={styles.cell}
                      border={false}
                      onClick={() => {
                        this.onDetail(item)
                      }}
                      titleClass={['van-ellipsis', styles.title]}
                    />
                  ))}
                </CollapseItem>
              </Collapse>
            ))}
          </List>
        ) : (
          <ColResult btnStatus={false} classImgSize="SMALL" tips="暂无内容" />
        )}
      </div>
    )
  }
})
