import request from '@/student/home-layout-orchestra/request-home'
import { verifyUrl } from '@/helpers/toolsValidate'
import { openDefaultWebView } from '@/student/home-layout-orchestra/state-orchestra'
import { PullRefresh, Swipe, SwipeItem, Image, Tabs, Tab, Popup } from 'vant'
import { defineComponent } from 'vue'
import HotAlbum from './components/hot-album'
import InfoList from './components/info-list'
import MenuList from './components/menu-list'
import Music from './components/music'
import RecommendSage from './components/recommend-sage'
import TalentStyle from './components/talent-style'
import TheHomeHeader from './components/TheHomeHeader'
import VideoClass from './components/video-class'
import styles from './index.module.less'
import Download from './model/download'
import popupClose from './images/popup-close.png'
import {
  listenerMessage,
  postMessage,
  promisefiyPostMessage,
  removeListenerMessage
} from '@/helpers/native-message'
import { browser } from '@/helpers/utils'
import { setLogout, state } from '@/state'
import event from './event'

export default defineComponent({
  name: 'home-index',
  props: {
    album: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      loading: false,
      height: 'auto' as any,
      banner: [], // BANNER列表
      appMenu: [], // 按钮列表
      albumList: [], // 热门专辑
      musicList: {
        topMusicSheet: [] as any,
        newMusicSheet: [] as any,
        hotMusicSheet: [] as any
      },
      sageList: [], // 推荐达人
      videoList: [], // 视频课
      headerHeight: 0,
      downloadStatus: false
    }
  },
  async mounted() {
    await this.init()

    event.on('downloadApp', async () => {
      // 管乐团里面，获取是否已安装酷乐秀
      const type = browser().orchestraAndroid
        ? 'com.cooleshow.student'
        : 'ColexiuStudent://'
      await promisefiyPostMessage({
        api: 'isInstall',
        content: { type: type }
      }).then((res: any) => {
        const content = res.content
        state.orchestraInfo.installStatus = content.installStatus
      })
      this.downloadStatus = true
    })

    listenerMessage('webViewOnResume', () => {
      promisefiyPostMessage({ api: 'getUserAccount' }).then((res: any) => {
        const content = res.content
        // console.log(state.orchestraInfo, 'state.orchestraInfo')
        // console.log(content, 'content')
        if (content.phone !== state.orchestraInfo.phone) {
          // 判断是否已经有关联编号
          if (content.unionId) {
            window.location.reload()
          } else {
            state.orchestraInfo.token = content.token.split(' ')[1]
            state.orchestraInfo.phone = content.phone
            state.orchestraInfo.nickname = content.nickname
            state.orchestraInfo.avatar = content.avatar
            state.orchestraInfo.unionId = content.unionId || 0
            // 13310106048
            // 15088666723
            setLogout()
            // window.location.reload()
            this.$router.push({
              path: '/home-auth'
            })
          }
        }
      })
    })

    postMessage({ api: 'setBarStatus', content: { status: 0 } })
  },
  unmounted() {
    removeListenerMessage('webViewOnResume', () => {
      //
    })
  },
  methods: {
    async init() {
      try {
        const res = await request.post('/api-cms/news/app/home', {
          data: {
            clientType: 'STUDENT'
          }
        })
        const result = res.data || {}
        this.banner = result.banner || []
        this.appMenu = this.arrChange(5, result.appMenu || [])

        // 热门专辑
        const album = await request.post('/api-student/music/album/list', {
          data: {
            albumStatus: 1,
            clientId: 'STUDENT'
          }
        })
        this.albumList = album.data.rows || []

        // 曲谱
        const music = await request.post(
          '/api-student/music/sheet/appMusicSheet',
          {
            data: {}
          }
        )
        const musicData = music.data || []
        this.musicList = {
          topMusicSheet: this.arrChange(4, musicData.topMusicSheet || []),
          newMusicSheet: this.arrChange(4, musicData.newMusicSheet || []),
          hotMusicSheet: this.arrChange(4, musicData.hotMusicSheet || [])
        }

        const sage = await request.get(
          '/api-student/teacher/queryHotTeacherList'
        )
        this.sageList = sage.data || []

        const video = await request.get(
          '/api-student/courseSchedule/queryLiveAndVideo'
        )
        this.videoList = video.data.videoList || []
      } catch {
        //
      }
      setTimeout(() => {
        this.loading = false
      }, 500)
    },
    arrChange(num: number, arr: any) {
      const newArr = [] as any
      while (arr.length > 0) {
        newArr.push(arr.splice(0, num))
      }
      return newArr
    },
    async onRefresh() {
      await this.init()
      setTimeout(() => {
        this.loading = false
      }, 500)
    }
  },
  render() {
    return (
      <div class={styles.home}>
        <TheHomeHeader
          ref="header"
          onHeaderDom={(height: number) => {
            console.log(height, 'height')
            this.headerHeight = height
          }}
          onCart={() => {
            this.downloadStatus = true
          }}
          onSearch={() => {
            // 搜索详情
            this.downloadStatus = true
          }}
          onMore={() => {
            this.downloadStatus = true
          }}
        />

        <PullRefresh
          v-model={this.loading}
          loading-text="正在刷新..."
          success-text="刷新完成"
          onRefresh={() => this.onRefresh()}
        >
          <div class={styles.hotContent}>
            <Swipe class={styles.swipe} autoplay={3000}>
              {this.banner.map((item: any) => (
                <SwipeItem
                  onClick={() => {
                    // 判断url是否正常
                    // if (verifyUrl(item.linkUrl)) {
                    //   openDefaultWebView(item.linkUrl, () => {
                    //     window.location.href = item.linkUrl
                    //   })
                    // }
                    this.downloadStatus = true
                  }}
                >
                  <Image
                    class={styles.swipeItemImg}
                    src={item.coverImage}
                    fit="fill"
                  />
                </SwipeItem>
              ))}
            </Swipe>

            <MenuList productList={this.appMenu} />
          </div>

          <HotAlbum album={this.albumList} />

          <Music title="推荐曲目" music={this.musicList?.topMusicSheet || []} />
          <Music title="最新曲目" music={this.musicList?.newMusicSheet || []} />
          <Music title="最热曲目" music={this.musicList?.hotMusicSheet || []} />

          {/* 推荐达人 */}
          <RecommendSage sage={this.sageList} />

          {/* 精品视频课 */}
          <VideoClass video={this.videoList} />

          <Tabs
            shrink
            background="#f6f8f9"
            class={styles.homeTabs}
            sticky
            offsetTop={this.headerHeight + 'px'}
          >
            <Tab title="达人风采" name="sage">
              <TalentStyle />
            </Tab>
            <Tab title="热门资讯" name="info">
              <InfoList />
            </Tab>
          </Tabs>
        </PullRefresh>

        <Popup
          v-model:show={this.downloadStatus}
          round
          style={{ width: '86%', background: 'transparent' }}
          closeable
          closeIcon={popupClose}
        >
          <Download
            buttonText={
              state.orchestraInfo.installStatus ? '唤起酷乐秀' : '下载酷乐秀'
            }
            onConfirm={() => {
              const type = browser().orchestraAndroid
                ? 'com.cooleshow.student'
                : 'ColexiuStudent://'
              if (state.orchestraInfo.installStatus) {
                postMessage({ api: 'openApp', content: { type: type } })
              } else {
                // const urlIos =
                //   'https://itunes.apple.com/cn/app/id1626971695?mt=8'
                // const urlAndroid =
                //   'https://appstore.ks3-cn-beijing.ksyuncs.com/clx-student-domain.apk'

                const url = browser().orchestraAndroid
                  ? window.location.origin +
                    window.location.pathname +
                    '#/download'
                  : 'https://itunes.apple.com/cn/app/id1626971695?mt=8'
                postMessage({
                  api: 'downloadApp',
                  content: { type: type, url: url }
                })
              }
            }}
          />
        </Popup>
        {/* 
          ColexiuStudent IOS 学生端
          com.cooleshow.student ADNROID 学生端
          com.cooleshow.teacher ADNROID 老师端
         */}
      </div>
    )
  }
})
