import { defineComponent, nextTick, ref, Ref } from 'vue'
import { List, CellGroup, Cell, NoticeBar, Icon, Popup, Toast } from 'vant'
import appState from '/src/state'
import classnames from 'classnames'
import store from 'store'
import requestOrigin from 'umi-request'
import qs from 'query-string'
import state from '/src/pages/state'
import detailState from '../state'
import styles from './index.module.less'
import { event } from '/src/pages/detail/runtime'
import MusicIcon from '/src/pages/list/icons/music.png'
import request from '/src/helpers/request'
import { browser, getRequestHostname } from '/src/helpers/utils'
import ChoosePartName from '/src/pages/list/modals/choosePartName'
import { setPrefix } from '/src/pages/detail/helpers'
import VipIcon from '/src/pages/list/icons/vip.png'
import { postMessage } from '/src/helpers/native-message'

const listRef: Ref = ref(null)

export default defineComponent({
  name: 'detail-list',
  data() {
    return {
      show: true,
      userinfo: null as any,
      chooseShow: false,
      partNames: [] as string[],
      selectedPartName: '',
      selectedPartIndex: 0,
      activeRow: null as any,
    }
  },
  methods: {
    async FetchList() {
      if (state.loading) {
        return
      }
      state.loading = true
      state.error = false
      console.log(state.subjectId)
      try {
          let params = state.params
          const res = await request.get('/sysMusicScore/queryPage2', {
            params: {
              ...params,
              clientType: 'SMART_PRACTICE',
              subjectId: state.subjectId === 0 ? undefined : state.subjectId,
              categoriesId: (
                (state.levelId || state.typeId) === 0 ? undefined : state.typeId || state.levelId
              ),
              search: state.search
            }
          })
          const { data } = res

          state.list = [...state.list, ...data.rows]
          if(params.page >= Math.ceil(data.total / params.rows)) {
            state.finished = true
          }
          state.params.page = data.nextPage
      } catch(e) {
        state.error = true
      }
      state.loading = false
    },
    async getPartNames (xmlUrl: string) {
      const partNames: string[] = []
      Toast({
        type: 'loading',
        overlay: true,
      })
      try {
        const res = await requestOrigin.get(xmlUrl, { mode: 'cors' })
        const xml = new DOMParser().parseFromString(res, 'text/xml')

        for (const item of xml.getElementsByTagName('part-name')) {
          if (item.textContent) {
            partNames.push(item.textContent)
          }
        }
        Toast.clear()
      } catch (error) {
        Toast.clear()
        Toast('读取分谱信息失败，请重试')
      }
      return partNames
    },
    openDetail() {
      const row = this.activeRow
      const needIds = row.rankIds?.split(',')
      const sid = String(appState.user?.student?.memberRankSettingId)
      if (
        row.rankIds &&
        appState.user &&
        !needIds.includes(sid) &&
        getRequestHostname() === '/api-student'
      ) {
        detailState.vipShow = true
        return
      }
      // 此处需要关闭录音以及其它状态
      event.emit('next-click')
      postMessage({
        api: 'cloudDestroy'
      })

      const searchStr = qs.stringify({
        ...qs.parse(location.search),
        _t: new Date().getTime(),
      })
      const hashSearchStr = qs.stringify({
        ...(this as any).$route.query,
        'part-index': this.selectedPartIndex,
      })
      const nextUrl = (
        location.origin +
        location.pathname +
        setPrefix(searchStr) +
        '#/detail/' +
        row.id +
        setPrefix(hashSearchStr)
        // + '?worksid=' + (this as any).$route.
      )
      location.replace(nextUrl)
    },
    async toDetail(row: any) {
      this.activeRow = row
      this.selectedPartName = ''
      this.selectedPartIndex = 0
      const partNames = await this.getPartNames(row.xmlUrl)
      this.partNames = partNames
      if (partNames.length > 1) {
        this.chooseShow = true
      } else {
        this.selectedPartName = partNames[0]
        this.openDetail()
      }
    },
    onSelectedPartName(part: number) {
      this.selectedPartIndex = part
      // this.selectedPartName = partNames[part]
      this.chooseShow = false
      this.openDetail()
    },
    async setScrollTop() {
      await nextTick()
      const detailListScrollTop = store.get('detailListScrollTop')
      if (detailListScrollTop) {
        listRef.value.scrollTop = detailListScrollTop
      }
    },
  },
  async mounted() {
    if (!state.list.length) {
      this.FetchList()
    }
    listRef.value.addEventListener('scroll', () => {
      store.set('detailListScrollTop',listRef.value.scrollTop)
    })
    this.setScrollTop()
  },
  updated() {
    this.setScrollTop()
  },
  render() {
    const paddingLeft = (
      detailState.isSpecialShapedScreen ?
      detailState.notchHeight / 2 + 'px' : ''
    )
    return (
      <div style={{
        height: '100vh',
        borderRadius: '0 30px 30px 0',
        overflow: 'hidden',
        overflowY: 'auto',
        background: '#fff',
        paddingLeft
      }} ref={listRef}>
        <Popup
          show={this.chooseShow}
          teleport="body"
          closeable
          style={{
            borderRadius: '8px',
          }}
          onClickOverlay={() => this.chooseShow = false}
          onClickCloseIcon={() => this.chooseShow = false}
        >
          <ChoosePartName
            isRem={false}
            partNames={this.partNames}
            onSelectedPartName={this.onSelectedPartName}
          />
        </Popup>
        <List
          loading={state.loading}
          finishedText="加载完毕"
          error={state.error}
          offset={100}
          class={classnames(styles.list, {[styles.android]: browser().android})}
          finished={state.finished}
          onLoad={this.FetchList}
          immediateCheck={false}
          vSlots={{
            error: () => (
              <span onClick={this.FetchList}>加载失败，请点击重试</span>
            )
          }}
        >
          <CellGroup>
            {state.list.map((item: any) => (
              <Cell
                class={classnames(
                  styles.item,
                  {[styles.active]: (item.id == (this as any).$route.params.id)})}
                onClick={() => this.toDetail(item)}
                vSlots={{
                  icon: () => (
                    <div class={styles['icon-status']}>
                      <Icon class={styles.iconMusic} name={MusicIcon} />
                      {item.rankIds ? (
                        <div class={styles.icon}>
                          <img src={VipIcon}/>
                        </div>
                      ) : null}
                    </div>
                  ),
                  title: (
                    <NoticeBar
                      background="none"
                      color="#444"
                      class={styles.notice}
                      style={{
                        paddingLeft: (item.rankIds ? '4PX' : '15PX') + '!important',
                      }}
                      text={item.name}
                      key="notactive"
                    />
                  )
                }}
              >
              </Cell>
            ))}
          </CellGroup>
        </List>
      </div>
    )
  }
})
