import { defineComponent } from 'vue'
import {
  Sticky,
  Search,
  List,
  Empty,
  CellGroup,
  Cell,
  Icon,
  NoticeBar,
  DropdownMenu,
  DropdownItem,
  Popup,
  Toast,
} from 'vant'
import classnames from 'classnames'
import qs from 'query-string'
import { find } from 'lodash'
import requestOrigin from 'umi-request'
import { browser, getRequestHostname, setTongjiTag, toNext } from '/src/helpers/utils'
import request from '/src/helpers/request'
import { postMessage } from '/src/helpers/native-message'
import appState from '/src/state'
import detailState from '/src/pages/detail/state'
import state, { getInitState } from '/src/pages/state'
import ChoosePartName from '/src/pages/list/modals/choosePartName'
import VipIcon from '/src/pages/list/icons/vip.png'
import iconSearch from '/src/pages/list/icons/icon_search.png'
import styles from './index.module.less'

const searchParse = qs.parse(location.search)

import MusicIcon from './icons/music.png'

export default defineComponent({
  name: 'music-list',
  data() {
    return {
      show: true,
      isFirstLoad: false,
      userinfo: null,
      isApp: browser().isApp,
      tempLevelId: 0,
      chooseShow: false,
      partNames: [] as string[],
      selectedPartName: '',
      selectedPartIndex: 0,
      activeRow: null as any,
    }
  },
  async mounted() {
    await this.initList()
  },
  // watch: {
  //   tempLevelId(newVal) {
  //     console.log(newVal, 'tempLevelId')
  //     if(newVal) {
  //       this.onSearch()
  //     }
  //   },
  // },
  methods: {
    async initList() {
      setTongjiTag(['_trackEvent', '云练习', '切换页面', '列表页面'])
      const initState = getInitState()
      for (const key in initState) {
        if (Object.prototype.hasOwnProperty.call(initState, key)) {
          state[key] = initState[key]
        }
      }
      // sessionStorage.setItem('parentId', this.$route.params.id || 1)
      state.parentId = this.$route.params.id || 1
      await this.FetchLevel()

      await this.FetchList()
    },
    async FetchLevel() {
      try {
        const musicScoreList = sessionStorage.getItem('musicScoreList')
        const musicList = musicScoreList ? JSON.parse(musicScoreList) : []
        let childClass = []
        for (let music of musicList) {
          if (music.id == state.parentId) {
            childClass = music.sysMusicScoreCategoriesList || []
          }
        }
        // console.log(childClass)
        state.levelOptions = [
          ...childClass.map((item: any) => ({
            value: item.id,
            text: item.name,
            childs: item.sysMusicScoreCategoriesList,
          })),
        ]
        if (state.levelOptions.length && !state.levelId) {
          state.levelId = state.levelOptions[0].value
          const active = find(state.levelOptions, { value: state.levelId })
          if (active) {
            if (active.childs) {
              console.log(active, 'showInfo')
              state.typeOptions = [
                { value: 0, text: '全部' },
                ...active.childs.map((item: any) => ({
                  value: item.id,
                  text: item.name,
                })),
              ]
            } else {
              state.typeOptions = null
            }
          }
        }
        // const res = await request.get('/sysMusicScoreCategories/queryTree', {
        //   params: {
        //     parentId: this.$route.params.id || 1
        //   }
        // })
        // state.levelOptions = [...res.data.map((item: any) => ({
        //   value: item.id,
        //   text: item.name,
        //   childs: item.sysMusicScoreCategoriesList
        // }))]
        // if (state.levelOptions.length && !state.levelId) {
        //   state.levelId = state.levelOptions[0].value
        //   const active = find(state.levelOptions, {value: state.levelId})
        //   if (active) {
        //     if (active.childs) {
        //       state.typeOptions = [
        //         {value: 0, text: '全部'},
        //         ...active.childs.map((item: any) => ({
        //           value: item.id,
        //           text: item.name
        //       }))]
        //     } else {
        //       state.typeOptions = null
        //     }
        //   }
        // }
      } catch (error) {}
    },
    async FetchCats() {
      try {
        const res = await request.get('/sysMusicScoreAccompaniment/querySubjectIds', {
          params: {
            categoriesId: this.$route.params.id || 1,
          },
        })
        appState.subjectOptions = [
          { value: 0, text: '全部声部' },
          ...res.data
            .filter((item: any) => !!item)
            .map((item: any) => ({
              value: item.id,
              text: item.name,
            })),
        ]
      } catch (error) {}
    },
    async FetchList() {
      state.error = false
      if (state.loading) {
        return
      }
      // if (state.levelOptions.length <= 0) {
      //   await this.FetchLevel()
      // }
      state.loading = true
      console.log(appState.subjectOptions)
      if (getRequestHostname() !== '/api-student') {
        await this.FetchCats()
      }
      if (getRequestHostname() === '/api-student') {
        // 因为学生端加了一个扩展声部
        appState.subjectOptions = [
          ...appState.extSubjectIds
            .filter((item: any) => !!item)
            .map((item: any) => ({
              value: item.id,
              text: item.name,
            })),
        ]
      }
      // if (getRequestHostname() != '/api-student') {
      // 每次请求前设置，确保列表中有值。不在声部列表中清空掉，此处不会影响详情
      const ids: number[] = appState.subjectOptions.map((item: any) => item.value).filter((item: number) => item > 0)
      console.log(ids, appState.subjectId)
      if (ids.includes(5)) {
        ids.push(6)
      }
      if (!ids.includes(appState.subjectId)) {
        appState.subjectId = 0
      }
      // }
      console.log(appState.subjectOptions)
      try {
        // let hasSub = false
        // for (const item of appState.subjectOptions) {
        //   if (item.value == appState.subjectId) {
        //     hasSub = true
        //     break
        //   }
        // }
        // if (!hasSub) {
        //   state.subjectId = 0
        //   appState.subjectId = 0
        // }
        state.subjectId = appState.subjectId
        let params = state.params
        let parentId = this.$route.params.id
        // 如果根级分类没有，则取父级分类
        // let categoriesId = 181
        let categoriesId =
          ((state.levelId || state.typeId) === 0 ? undefined : state.typeId || state.levelId) || parentId
        let subjectId = appState.subjectId === 0 ? undefined : appState.subjectId
        if (getRequestHostname() !== '/api-student') {
          // 学生端则根据当前登录人声部选择,其它端,则选择全部
          // subjectId = undefined
          // 需要这个id 暂时移除
        }

        const res = await request.get('/sysMusicScore/queryPage2', {
          params: {
            ...params,
            clientType: 'SMART_PRACTICE',
            subjectId,
            categoriesId,
            search: state.search,
          },
        })
        const { data } = res
        // 处理接口重复请求，过滤数据
        if (state.list.length > 0 && data.pageNo == 1) {
          return
        }
        state.list = [...state.list, ...data.rows]
        if (params.page >= Math.ceil(data.total / params.rows)) {
          state.finished = true
          // Toast('列表加载完成')
        }
        state.params.page = data.nextPage
        if (state.list.length <= 0) {
          this.show = false
        }
      } 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
      }
      if (searchParse.mode === 'select') {
        if (this.isApp) {
          postMessage({
            api: 'onAccompanySelectResult',
            content: {
              id: row.id,
              name: row.name,
              partIndex: this.selectedPartIndex,
            },
          })
        }
        return
      }
      const herf = '/detail/' + row.id + '?part-index=' + this.selectedPartIndex
      if (this.isApp) {
        /**
         * app 已验证麦克风，摄像头权限才会继续打开页面
         */
        postMessage({
          api: 'openAccompanyWebView',
          content: {
            url: location.origin + '/accompany/#' + herf,
            orientation: 0,
            isHideTitle: true,
            statusBarTextColor: false,
            isOpenLight: true,
          },
        })
      } else {
        const nextUrl = toNext('#' + herf, {
          ...this.$route.query,
          // worksid: this.$route.params.id
        })
        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()
    },
    onPayVideo(evt: MouseEvent, data: any) {
      evt.stopPropagation()
      postMessage({
        api: 'recordHomeworkVideo',
        content: {
          ...data,
          partIndex: this.selectedPartIndex,
        },
      })
    },
    openRecordingWebview(evt: MouseEvent, row: any) {
      evt.stopPropagation()
      postMessage({
        api: 'recordHomeworkVideo',
        content: {
          id: row.id,
          partIndex: this.selectedPartIndex,
          // url: location.origin + '/accompany/#/detail/' + row.examSongId + '?mode=homework',
          // orientation: 0,
          // isHideTitle: true,
          // statusBarTextColor: false,
          // isOpenLight: true,
        },
      })
    },
    onSearch() {
      state.params.page = 1
      state.list = []
      this.show = true
      state.finished = false
      this.FetchList()
    },
    subjectChange(val: number) {
      appState.subjectId = val
      this.onSearch()
    },
    onClickLeft() {
      ;(this as any).$router.replace('/')
    },
  },
  render() {
    return (
      <div class={styles.accompany}>
        <Popup
          show={this.chooseShow}
          teleport="body"
          closeable
          style={{
            borderRadius: '8px',
          }}
          onClickOverlay={() => (this.chooseShow = false)}
          onClickCloseIcon={() => (this.chooseShow = false)}
        >
          <ChoosePartName partNames={this.partNames} onSelectedPartName={this.onSelectedPartName} />
        </Popup>
        <Sticky>
          {state.typeOptions || (state.levelOptions && state.levelOptions.length > 0) ? (
            <DropdownMenu activeColor="#01C1B5">
              {state.levelOptions && state.levelOptions.length > 0 ? (
                <DropdownItem
                  modelValue={state.levelId}
                  options={state.levelOptions}
                  onChange={(val: number) => {
                    state.levelId = val
                    state.typeId = 0
                    const active = find(state.levelOptions, { value: val })
                    if (active) {
                      if (active.childs) {
                        state.typeOptions = [
                          { value: 0, text: '全部' },
                          ...active.childs.map((item: any) => ({
                            value: item.id,
                            text: item.name,
                          })),
                        ]
                      } else {
                        state.typeOptions = null
                      }
                    }
                    this.onSearch()
                  }}
                />
              ) : null}
              {state.typeOptions ? (
                <DropdownItem
                  class={styles.searchSelect}
                  get-container="#app"
                  modelValue={state.typeId}
                  options={state.typeOptions}
                  onChange={(val: any) => {
                    state.typeId = val
                    this.onSearch()
                  }}
                />
              ) : null}
              {/* <DropdownItem
              modelValue={appState.subjectId}
              options={appState.subjectOptions}
              onChange={this.subjectChange}
            /> */}
            </DropdownMenu>
          ) : null}
          <Search
            class={[styles.search]}
            placeholder="请输入搜索关键词"
            modelValue={state.search}
            background="#F8F9FC"
            onUpdate:model-value={(text: string) => (state.search = text)}
            showAction
            onSearch={this.onSearch}
            vSlots={{
              'left-icon': () => <img class={styles.iconSearch} src={iconSearch} />,
              label: () => {
                if (
                  getRequestHostname() == '/api-student' &&
                  appState.subjectOptions &&
                  appState.subjectOptions.length === 1
                )
                  return null
                return (
                  <DropdownMenu
                    activeColor="#01C1B5"
                    onClick={(evt: MouseEvent) => {
                      evt.preventDefault()
                    }}
                  >
                    <DropdownItem
                      class={styles.searchSelect}
                      get-container="#app"
                      modelValue={appState.subjectId}
                      options={appState.subjectOptions}
                      onChange={(val: any) => {
                        appState.subjectId = val
                        this.onSearch()
                      }}
                    />
                  </DropdownMenu>
                )
              },
              action: () => (
                <span class={styles.search_btn} onClick={this.onSearch}>
                  搜索
                </span>
              ),
            }}
          />
        </Sticky>
        {/* <div class={styles.vipTip}><span class={styles.strong}>限时免费</span>使用</div> */}
        <div class={classnames(styles.accompanyList, styles.song)}>
          {this.show ? (
            <List
              loading={state.loading}
              finishedText="加载完毕"
              error={state.error}
              offset={100}
              finished={state.finished}
              immediateCheck={false}
              onLoad={this.FetchList}
              vSlots={{
                error: () => <span onClick={this.FetchList}>加载失败，请点击重试</span>,
              }}
            >
              <CellGroup>
                {state.list.map((item: any) => (
                  <Cell
                    size="large"
                    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"
                          style={{
                            paddingLeft: (item.rankIds ? '4PX' : '15PX') + '!important',
                          }}
                          text={item.name}
                          key="notactive"
                        />
                      ),
                    }}
                  ></Cell>
                ))}
              </CellGroup>
            </List>
          ) : (
            <Empty description="暂无数据" />
          )}
        </div>
      </div>
    )
  },
})
