import { defineComponent } from 'vue'
import { Image, Empty, Popup, Toast, Button } from 'vant'
import { browser, setTongjiTag, getRandomKey, getRequestHostname } from '/src/helpers/utils'
import { postMessage } from '/src/helpers/native-message'
import appState from '/src/state'
import request from '/src/helpers/request'
import ChooseSubjectName from './modals/chooseSubjectName/index'
import styles from './index.module.less'

const browserInfo = browser()

export default defineComponent({
  name: 'baseClass',
  components: { ChooseSubjectName },
  data() {
    return {
      list: [] as any[],
      show: true,
      closeStatus: true,
      courseNum: 0,
    }
  },
  mounted() {
    document.addEventListener('visibilitychange', this.visibilitychange, false)
    localStorage.setItem('behaviorId', getRandomKey())
    this.FetchList()
    setTongjiTag(['_trackEvent', '云练习', '切换页面', '分类页面'])
    appState.subjectId = appState.origanSubjectId
    if (getRequestHostname() === '/api-student') {
      this.FetchCourseInfo()
    }
  },
  unmounted() {
    document.removeEventListener('visibilitychange', this.visibilitychange, false)
  },
  computed: {
    chooseShow() {
      if (
        getRequestHostname() === '/api-student' &&
        !appState.subjectLoading &&
        appState.subjectId === 0 &&
        this.closeStatus
      ) {
        return true
      }
      return false
    },
  },
  methods: {
    visibilitychange() {
      if (document.visibilityState !== 'hidden' && this.courseNum > 0) {
        this.FetchCourseInfo()
      }
    },
    async FetchCourseInfo() {
      try {
        const res = await request('/activityUserMapper/getStudentNoCourseInfo')
        this.courseNum = res.data.courseNum
      } catch (error) {}
    },
    async FetchList() {
      try {
        const res = await request.get('/sysMusicScoreCategories/queryTree')
        // const result = res.data || []
        // result.forEach((item: any) => {
        //   const children = item.sysMusicScoreCategories && item.sysMusicScoreCategories.length > 0 ? item.sysMusicScoreCategories : []
        //   if(item.id !== 40 || item.id === 40 && children.length > 0) {
        //     this.list.push(item)
        //   }
        // })
        this.list = (await this.filterList(res.data || [])) || []
        // console.log(res.data, this.filterList(res.data || []))
        this.show = this.list.length > 0 ? true : false
      } catch (error) {}
    },

    filterList(list: any) {
      // 过滤掉（59分部）考级曲目
      const tenantId = appState.tenantId
      const organId = appState.organId
      // 大雅机构
      let tempOrgan: number[] = []
      // if (getRequestHostname() === "/api-web") {
      //   let tempOrganId: any = String(organId).split(",");
      //   tempOrganId = tempOrganId ? tempOrganId.map((i: any) => Number(i)) : [];
      //   tempOrgan = tempOrganId;
      // } else {
      //   tempOrgan.push(organId);
      // }

      // 如果不是大雅机构则 不过滤
      if (tenantId != 1) {
        return list
      }

      list.forEach((item: any) => {
        const children = item.sysMusicScoreCategoriesList || []
        let tempChildren = []
        if (item.id === 38) {
          // 只对声部训练做处理
          if (tempOrgan.includes(55)) {
            // 显示所有子分类
            tempChildren = children
          } else if (tempOrgan.includes(59)) {
            children.forEach((child: any) => {
              if (child.id == 30) {
                tempChildren.push(child)
              }
            })
          } else if (!tempOrgan.includes(55) && !tempOrgan.includes(59)) {
            children.forEach((item: any) => {
              if (item.id != 30) {
                tempChildren.push(item)
              }
            })
          }
        } else if (item.id === 40) {
          // 考级曲目
          if (tempOrgan.includes(59)) {
            // 齐齐哈尔二部没有考级曲目
            children.forEach((item: any) => {
              if (item.id != 47) {
                tempChildren.push(item)
              }
            })
          } else if (!tempOrgan.includes(59)) {
            children.forEach((item: any) => {
              tempChildren.push(item)
            })
          }
        } else {
          tempChildren = children
        }
        item.sysMusicScoreCategoriesList = tempChildren
      })
      // 判断考级曲目是否有子分类，如果没有则删除
      let parentList: any[] = []
      list.forEach((item: any) => {
        if (item.id == 40 && item.sysMusicScoreCategoriesList && item.sysMusicScoreCategoriesList.length > 0) {
          // 考级曲目
          parentList.push(item)
        }
        if (item.id != 40) {
          parentList.push(item)
        }
      })
      return parentList
    },
    onClickLeft() {
      if (browserInfo.isApp) {
        postMessage({
          api: 'back',
        })
      }
    },
    toDetail(item: any) {
      const childLength = item.sysMusicScoreCategoriesList ? item.sysMusicScoreCategoriesList.length : 0
      // 如果二级分类只有一个分类，则直接跳转到曲目列表
      sessionStorage.setItem('musicScoreList', JSON.stringify(item.sysMusicScoreCategoriesList))
      if (childLength > 1) {
        ;(this as any).$router.push({
          path: '/classify',
          query: {
            parentId: item.id, // 父级元素编号
            ...this.$route.query,
          },
        })
      } else {
        ;(this as any).$router.push({
          path: '/list/' + (childLength == 1 ? item.sysMusicScoreCategoriesList[0]?.id : item.id),
          query: {
            ...this.$route.query,
          },
        })
      }
    },
    audition() {
      postMessage({
        api: 'openWebView',
        content: {
          url: location.origin + '/#/auditionLive',
          orientation: 1,
          isHideTitle: false,
          statusBarTextColor: false,
          isOpenLight: false,
        },
      })
    },
    async onSelectedPartName(item: any) {
      if (!item.id) {
        Toast('请选择声部')
        return
      }
      try {
        await request.post('/student/updateSubject', {
          data: {
            subjectId: item.id,
          },
        })
        this.chooseShow = false
        appState.subjectId = item.id
        appState.origanSubjectId = item.id
      } catch {}
    },
  },
  render() {
    return (
      <div class={styles.container}>
        <Popup
          show={this.chooseShow}
          teleport="body"
          style={{
            borderRadius: '8px',
          }}
        >
          <ChooseSubjectName onSelectedPartName={this.onSelectedPartName} />
        </Popup>
        <div class={styles.content}>
          {getRequestHostname() === '/api-student' && this.courseNum > 0 && (
            <div class={styles.headerTips}>
              <p>
                随心学真人辅导课剩余 <span>{this.courseNum}</span> 节
              </p>
              <Button class={styles.btn} onClick={this.audition}>
                立即约课
              </Button>
            </div>
          )}
          <div class={styles.items}>
            {this.show ? (
              this.list.map((item) => (
                <div key={item.id} onClick={() => this.toDetail(item)}>
                  <div class={styles.inner}>
                    <Image src={item.coverImg} class={styles.img} />
                  </div>
                </div>
              ))
            ) : (
              <Empty description="暂无数据" />
            )}
          </div>
        </div>
      </div>
    )
  },
})
