import ColHeader from '@/components/col-header'
import ColSearch from '@/components/col-search'
import { Sticky, Image, List, Icon, Popup } from 'vant'
import { defineComponent } from 'vue'
import styles from './index.module.less'
import request from '@/helpers/request'
import ColResult from '@/components/col-result'
import LiveItem from './live-item'

import banner from '../video-class/images/banner.png'
import { state } from '@/state'
import OrganSearch from '../practice-class/model/organ-search'
import { useEventTracking } from '@/helpers/hooks'

export default defineComponent({
  name: 'liveClass',
  data() {
    const sessionSubjectId = sessionStorage.getItem('liveClassSubjectId')

    return {
      list: [],
      dataShow: true, // 判断是否有数据
      loading: false,
      finished: false,
      searchStatus: false,
      openStatus: false,
      subjectList: [],
      sessionSubjectId,
      params: {
        search: '',
        courseType: "GROUP",
        subjectId: (sessionSubjectId ||
          state.user.data?.subjectId ||
          null) as any,
        subjectName: '',
        groupStatus: 'APPLY',
        page: 1,
        rows: 20
      }
    }
  },
  async mounted() {
    try {
      const res = await request.get('/api-student/subject/subjectSelect')
      this.subjectList = res.data || []
    } catch {}
    let subjectName = ''
    this.subjectList.forEach((item: any) => {
      item.subjects?.forEach((child: any) => {
        if (child.id === Number(this.sessionSubjectId)) {
          subjectName = child.name
        }
      })
    })
    this.params.subjectName = subjectName || state.user.data?.subjectName || ''

    sessionStorage.removeItem('liveClassSubjectId')
    useEventTracking('直播课')
  },
  methods: {
    onSort() {
      this.params.page = 1
      this.list = []
      this.dataShow = true // 判断是否有数据
      this.loading = false
      this.finished = false
      this.searchStatus = false
      this.getList()
    },
    onSearch(value: string) {
      this.params.search = value
      this.onSort()
    },
    async getList() {
      try {
        const params: any = {
          ...this.params
        }
        if (state.version) {
          params.version = state.version || '' // 处理ios审核版本
          params.platform = 'ios-student'
        }
        const res = await request.post(
          '/api-student/courseGroup/queryPageCourseGroup',
          {
            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
      } catch {
        this.dataShow = false
        this.finished = true
      }
    },
    onDetail(item: any) {
      this.params.subjectId &&
        sessionStorage.setItem('liveClassSubjectId', this.params.subjectId)
      this.$router.push({
        path: '/groupDetail',
        query: {
          groupId: item.courseGroupId
        }
      })
    }
  },
  render() {
    return (
      <div class={styles.liveClass}>
        <Sticky offsetTop={0} position="top">
          <ColHeader
            class={styles.classHeader}
            border={false}
            isFixed={false}
            background="transparent"
          />
          <ColSearch
            placeholder="请输入老师名称/课程名称"
            onSearch={this.onSearch}
            v-slots={{
              left: () => (
                <div
                  class={styles.label}
                  onClick={() => {
                    this.searchStatus = !this.searchStatus
                    this.openStatus = !this.openStatus
                  }}
                >
                  {this.params.subjectName}
                  <Icon
                    classPrefix="iconfont"
                    name="down"
                    size={12}
                    color="#333"
                  />
                </div>
              )
            }}
          />
        </Sticky>

        <div class={styles.banner}>
          <Image src={banner} />
        </div>

        {this.dataShow ? (
          <List
            v-model:loading={this.loading}
            finished={this.finished}
            finishedText=" "
            class={[styles.liveList]}
            onLoad={this.getList}
          >
            {this.list.map((item: any) => (
              <LiveItem onClick={this.onDetail} liveInfo={item} />
            ))}
          </List>
        ) : (
          <ColResult btnStatus={false} classImgSize="SMALL" tips="暂无小组课" />
        )}

        <Popup
          show={this.searchStatus}
          position="bottom"
          round
          closeable
          safe-area-inset-bottom
          onClose={() => (this.searchStatus = false)}
          onClosed={() => (this.openStatus = false)}
        >
          {this.openStatus && (
            <OrganSearch
              subjectList={this.subjectList}
              onSort={this.onSort}
              v-model={this.params.subjectId}
              v-model:subjectName={this.params.subjectName}
            />
          )}
        </Popup>
      </div>
    )
  }
})
