import ColHeader from '@/components/col-header'
import ColResult from '@/components/col-result'
import ColSearch from '@/components/col-search'
import request from '@/helpers/request'
import { state } from '@/state'
import { List, Popup, Sticky, Image, Icon } from 'vant'
import { defineComponent } from 'vue'
import OrganSearch from '../practice-class/model/organ-search'
import styles from './teacher-elegant.module.less'

import iconTeacher from '@common/images/icon_teacher.png'
import iconUploadPoster from '@common/images/icon_upload_poster.png'
import bars from '@common/svg/bars.svg'
import { useRect } from '@vant/use'
import { SubjectEnum, useSubjectId } from '@/helpers/hooks'

export default defineComponent({
  data() {
    return {
      searchStatus: false,
      openStatus: false,
      subjectList: [],
      params: {
        username: '',
        page: 1,
        subjectId: null as any,
        subjectName: '全部声部'
      },
      dataShow: true, // 判断是否有数据
      loading: false,
      finished: false,
      list: [],
      height: 'auto' as any
    }
  },
  async mounted() {
    try {
      const res = await request.get('/api-student/subject/subjectSelect')
      this.subjectList = res.data || []
    } catch {}
    // 判断是否在缓存
    const subjects: any = useSubjectId(SubjectEnum.ELEGANT)
    if (subjects.id) {
      this.params.subjectId = Number(subjects.id)
      this.params.subjectName = subjects.name
    } else {
      const list = this.subjectList
      const subjectIds = state.user.data?.subjectId || ''
      const subjectId = subjectIds ? Number(subjectIds.split(',')[0]) : null
      list.forEach((subject: any) => {
        const child = subject.subjects || []
        child.forEach((sub: any) => {
          if (sub.id === Number(subjectId)) {
            this.params.subjectId = sub.id
            this.params.subjectName = sub.name
          }
        })
      })
    }
    await this.getList()
    sessionStorage.removeItem('teacherHomeTabs')
  },
  computed: {
    filterDot() {
      const subjectId: any = this.params.subjectId
      return !!subjectId
    }
  },
  methods: {
    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/teacher/stylePage', {
          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
      }
    },
    onSort() {
      this.params.page = 1
      this.list = []
      this.dataShow = true // 判断是否有数据
      this.loading = false
      this.finished = false
      this.searchStatus = false
      if (this.params.subjectId) {
        useSubjectId(
          SubjectEnum.ELEGANT,
          JSON.stringify({
            id: this.params.subjectId,
            name: this.params.subjectName
          }),
          'set'
        )
      }
      this.getList()
    },
    onSearch(_search?: any) {
      this.params.username = _search
      this.onSort()
    },
    onDetail(item: any) {
      // this.params.subjectId &&
      //   sessionStorage.setItem('elegantSubjectId', this.params.subjectId)
      this.$router.push({
        path: '/teacherHome',
        query: {
          teacherId: item.userId
        }
      })
    }
  },
  render() {
    return (
      <div class={styles['teacher-elegant']}>
        <Sticky offsetTop={0} position="top">
          <div ref="header">
            <ColHeader
              class={styles.classHeader}
              border={false}
              background="transparent"
              isFixed={false}
              // onHeaderBack={() => {
              //   this.$nextTick(() => {
              //     const { height } = useRect((this as any).$refs.headers)
              //     this.height = height
              //   })
              // }}
            />
            <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>
                )
              }}
            />
          </div>
          {/* <div class={styles.searchContainer}>
            <div class={styles.item}>
              <div
                class={[styles.searchItem, styles.searchFollow, styles.active]}
              >
                <p class={styles.title}>我的关注</p>
                <p class={styles.content}>老师最新动态</p>
              </div>
              <div
                class={[styles.searchItem, styles.searchLive, styles.active2]}
              >
                <p class={styles.title}>直播中</p>
                <p class={styles.content}>互动直播间</p>
              </div>
            </div>

            <div class={styles.searchDefault}>
              <Icon
                classPrefix="iconfont"
                class={styles.star}
                color="#FFC459"
                name="star_active"
              />
              默认排序
            </div>
          </div> */}
        </Sticky>

        {this.dataShow ? (
          <List
            v-model:loading={this.loading}
            finished={this.finished}
            finishedText=" "
            immediateCheck={false}
            class={[styles.elegant]}
            onLoad={this.getList}
          >
            {this.list.map((item: any) => (
              <div class={styles.tedeoItem}>
                <div
                  class={styles.itemBg}
                  onClick={() => {
                    this.onDetail(item)
                  }}
                ></div>
                <div class={styles.teCover}>
                  <Image src={item.cover || iconUploadPoster} fit="cover" />
                  {item.living === 1 && (
                    <div class={styles.living}>
                      <Image src={bars} class={styles.animation} />
                      <span>直播中</span>
                    </div>
                  )}
                </div>
                <div class={styles.teSection}>
                  {/* <div class={[styles.teTitle, 'van-ellipsis']}>
                    {item.lessonName}
                  </div> */}
                  <div class={styles.info}>
                    <div class={styles.teUserInfo}>
                      <Image
                        src={item.avatar || iconTeacher}
                        class={styles.teUserLogo}
                      />
                      <span
                        class={[
                          styles.teUserName,
                          'van-hairline--right van-ellipsis'
                        ]}
                      >
                        {item?.username || `游客${item?.userId || ''}`}
                      </span>
                    </div>
                    <span class={styles.teUserNum}>{item.browse}浏览</span>
                  </div>
                </div>
              </div>
            ))}
          </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>
    )
  }
})
