import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref,
  watch
} from 'vue'
import { Sticky, List, Popup, Icon, Switch, Tabs, Tab } from 'vant'
import Search from '@/components/col-search'
import request from '@/helpers/request'
// import Item from './item'
import SelectTag from '../search/select-tag'
import { useRoute, useRouter } from 'vue-router'
import ColResult from '@/components/col-result'
import styles from './index.module.less'
import { getRandomKey } from '../music'
import { openDefaultWebView, state as baseState } from '@/state'
import SelectSubject from '../search/select-subject'
import { SubjectEnum, useSubjectId } from '@/helpers/hooks'
import Song from '../component/song'
import ColHeader from '@/components/col-header'
import { useRect } from '@vant/use'
import { useAsyncState } from '@vueuse/core'
import bgImg from './icons/bgImg.png'
import iconSearch from './icons/icon_search.png'
import { browser } from '@/helpers/utils'
import TheSticky from '@/components/the-sticky'

const noop = () => {
  //
}

export default defineComponent({
  name: 'MusicList',
  props: {
    hideSearch: {
      type: Boolean,
      default: false
    },
    onlySearch: {
      type: Boolean,
      default: false
    },
    height: {
      type: Number,
      default: 0
    },
    defauleParams: {
      type: Object,
      default: () => ({})
    },
    onItemClick: {
      type: Function,
      default: noop
    },
    teacherId: {
      type: String || Number,
      default: ''
    },
    myself: {
      type: Boolean,
      default: false
    }
  },
  setup(
    {
      hideSearch,
      onlySearch,
      height,
      defauleParams,
      onItemClick,
      teacherId,
      myself
    },
    { expose }
  ) {
    const { isLoading, state } = useAsyncState(
      request(baseState.platformApi + '/MusicTag/tree', {
        params: {
          type: 'MUSIC'
        }
      }),
      null
    )

    const stickyHeight = ref(height || 0)

    const updateStickyHeight = (height: number) => {
      stickyHeight.value = height
    }

    const teacherDetaultSubject = ref({
      id: '',
      name: ''
    })
    if (baseState.platformType === 'TEACHER') {
      // defaultSubject
      const users = baseState.user.data
      teacherDetaultSubject.value = {
        name: users.defaultSubjectName || '全部声部',
        id: users.defaultSubject || ''
      }
    } else {
      // const subjects: any = useSubjectId(SubjectEnum.SEARCH)
      // 判断是否已有数据
      // if (!subjects.id) {
      const users = baseState.user.data
      // const subjectId = users.subjectId
      //   ? Number(users.subjectId.split(',')[0])
      //   : ''
      // const subjectName = users.subjectName
      //   ? users.subjectName.split(',')[0]
      //   : ''
      // 存储instrumentId
      const userInstrumentId = users.instrumentId
      localStorage.setItem('userInstrumentId', userInstrumentId)
      // if (subjectId) {
      //   useSubjectId(
      //     SubjectEnum.SEARCH,
      //     JSON.stringify({
      //       id: subjectId,
      //       name: subjectName
      //     }),
      //     'set'
      //   )
      // }
      // }
    }

    localStorage.setItem('behaviorId', getRandomKey())
    const route = useRoute()
    const router = useRouter()
    const tempParams: any = {}
    if (baseState.version) {
      tempParams.version = baseState.version || '' // 处理ios审核版本
      tempParams.platform =
        baseState.platformType === 'STUDENT' ? 'ios-student' : 'ios-teacher'
    }
    const exquisiteFlag = ref(false)
    // 判断是否在搜索页面用过
    if (!hideSearch) {
      if (baseState.platformType === 'TEACHER') {
        tempParams.subjectIds = teacherDetaultSubject.value.id
      } else {
        // const getSubject: any = useSubjectId(SubjectEnum.SEARCH)
        const users = baseState.user.data
        const subjectId = users.subjectId
          ? Number(users.subjectId.split(',')[0])
          : ''
        tempParams.subjectIds = subjectId
      }

      const getMusic: any = useSubjectId(SubjectEnum.MUSIC_FREE)
      exquisiteFlag.value = getMusic.chargeType
    }
    // if(onlySearch) {
    //   const getSubject: any = useSubjectId(SubjectEnum.SEARCH)
    //   tempParams.subjectIds = getSubject.id
    // }
    //

    const params = reactive({
      search: (route.query.search as string) || '',
      musicSortType: (route.query.type as string) || "",
      // exquisiteFlag: 1,
      musicTagIds: route.query.tagids || '',
      page: 1,
      ...defauleParams,
      ...tempParams
    })
    const data = ref<any>(null)
    const loading = ref(false)
    const finished = ref(false)
    const isError = ref(false)
    const tagVisibility = ref(false)
    const isAudit = ref(true)

    const apiSuffix = ref(
      baseState.platformType === 'STUDENT' ? '/api-student' : '/api-teacher'
    )

    const onSearch = (value: string) => {
      params.page = 1
      params.search = value
      data.value = null
      FetchList()
    }

    const FetchList = async () => {
      if (loading.value) {
        return
      }
      loading.value = true
      isError.value = false
      const tempParams = {
        ...params,
        auditStatus: 'PASS',
        idAndName: params.search,
        createBy: teacherId
      }
      if (exquisiteFlag.value) {
        tempParams.chargeType = 'FREE'
      }
      if (myself) {
        tempParams.myself = true
      } else {
        tempParams.myself = false
      }

      try {
        const res = await request.post(`${apiSuffix.value}/music/sheet/list`, {
          data: tempParams
        })
        if (data.value) {
          const result = (data.value?.rows || []).concat(res.data.rows || [])
          data.value.rows = result
        }
        data.value = data.value || res.data
        params.page = res.data.pageNo + 1
        finished.value = res.data.pageNo >= res.data.totalPage
      } catch (error) {
        isError.value = true
      }
      loading.value = false
    }

    // 设置默认声部
    const setDefaultSubject = async (subjectId: any) => {
      try {
        await request.post('/api-teacher/teacher/defaultSubject', {
          params: {
            subjectId
          }
        })
      } catch {
        //
      }
    }

    const onComfirm = tags => {
      const tempTags: any = {}
      // 单独处理乐谱类型
      for (const tag in tags) {
        if (Number(tag) === -1) {
          exquisiteFlag.value = tags[tag][0] ? true : false
        } else {
          tempTags[tag] = tags[tag]
        }
      }

      const d = Object.values(tempTags).flat().filter(Boolean).join(',')
      params.musicTagIds = d
      params.page = 1
      data.value = null
      FetchList()
      tagVisibility.value = false
    }
    const onComfirmSubject = item => {
      //   params.page = 1
      //   params.subjectIds = item.id
      //   data.value = null
      //   subject.instrumentId = item.instrumentId
      //   localStorage.setItem('userInstrumentId', item.instrumentId || "")
      //   if (baseState.platformType === 'TEACHER') {
      //     teacherDetaultSubject.value = {
      //       name: item.name,
      //       id: item.id
      //     }
      //     setDefaultSubject(item.id)
      //   } else {
      //     subject.id = item.id
      //     subject.name = item.name
      //     useSubjectId(
      //       SubjectEnum.SEARCH,
      //       JSON.stringify({
      //         id: item.id,
      //         name: item.name
      //       }),
      //       'set'
      //     )
      //   }
      //   FetchList()
      //   subject.show = false
    }

    // const getSubject: any = useSubjectId(SubjectEnum.SEARCH)

    // // 处理存值的问题 - 重置数量
    // let tempInstrumentId = localStorage.getItem('userInstrumentId') || ''
    // if(tempInstrumentId === 'undefined') {
    //   useSubjectId(SubjectEnum.SEARCH, "", "remove")
    //   tempInstrumentId = ""
    // }

    // const subject = reactive({
    //   show: false,
    //   name: getSubject.id ? getSubject.name : '全部声部',
    //   id: getSubject.id || '',
    //   instrumentId: tempInstrumentId,
    // })

    onMounted(async () => {
      try {
        if (!browser().iPhone) {
          isAudit.value = false
          return
        }
        const { data } = await request.get(
          '/api-admin/appVersionInfo/queryByPlatform',
          {
            params: {
              platform:
                baseState.platformType === 'TEACHER'
                  ? 'ios-teacher'
                  : 'ios-student'
            }
          }
        )
        if (baseState.version > data.version) {
          isAudit.value = true
        } else {
          isAudit.value = false
        }
      } catch {
        //
      }
    })

    expose({
      onSearch,
      onComfirm,
      updateStickyHeight,
      onComfirmSubject
    })

    return () => {
      // const tagList = ((state.value && state.value.data) as any) || []
      return (
        <>
          {!hideSearch && (
            <>
              <TheSticky class={styles.sticky}>
                <ColHeader
                  background="transparent"
                  isFixed={false}
                  v-slots={{
                    content: () => (
                      <div class={styles.woringHeader}>
                        <i
                          onClick={() => {
                            if (browser().isApp) {
                              postMessage({
                                api: 'back'
                              })
                            } else {
                              router.back()
                            }
                          }}
                          class={[
                            'van-badge__wrapper van-icon van-icon-arrow-left van-nav-bar__arrow',
                            styles.leftArrow
                          ]}
                        ></i>
                        <Tabs
                          class={styles.tabSection}
                          v-model:active={params.musicSortType}
                          shrink
                          onClick-tab={(val) => {
                            params.musicSortType = val.name
                            onSearch(params.search)
                          }}
                        >
                          <Tab name="" title="全部"></Tab>
                          <Tab name="TOP" title="推荐"></Tab>
                          <Tab name="HOT" title="热门"></Tab>
                          <Tab name="NEW" title="最新"></Tab>
                        </Tabs>
                      </div>
                    )
                    // right: () =>
                    //   !isAudit.value && (
                    //     <span
                    //       class={styles.fleg}
                    //       onClick={() => {
                    //         // 不要看这个字段的意思
                    //         exquisiteFlag.value != exquisiteFlag.value
                    //         useSubjectId(
                    //           SubjectEnum.MUSIC_FREE,
                    //           JSON.stringify({
                    //             chargeType: exquisiteFlag.value
                    //           }),
                    //           'set'
                    //         )
                    //         data.value = null
                    //         params.page = 1
                    //         FetchList()
                    //       }}
                    //     >
                    //       <Switch v-model={exquisiteFlag.value} size="20px" />
                    //       <span>免费</span>
                    //     </span>
                    //   )
                  }}
                />
                <Search
                  onSearch={onSearch}
                  background="transparent"
                  inputBackground="transparent"
                  leftIcon={iconSearch}
                  // v-slots={{
                  //   left: () => (
                  //     <div
                  //       class={styles.label}
                  //       onClick={() => (subject.show = true)}
                  //     >
                  //       {baseState.platformType === 'TEACHER'
                  //         ? teacherDetaultSubject.value.name
                  //         : subject.name}

                  //       <Icon
                  //         classPrefix="iconfont"
                  //         name="down"
                  //         size={12}
                  //         color="#fff"
                  //       />
                  //     </div>
                  //   )
                  // }}
                />
                {/* <Tabs
                  shrink
                  class={styles.tagTabs}
                  lineHeight={0}
                  onClick-tab={(obj: any) => {
                    params.musicTagIds = obj.name
                    data.value = null
                    params.page = 1
                    FetchList()
                  }}
                >
                  <Tab title="全部" name=""></Tab>
                  {tagList.map((tag: any) => (
                    <Tab title={tag.name} name={tag.id}></Tab>
                  ))}
                </Tabs> */}
              </TheSticky>
              <img class={styles.bgImg} src={bgImg} />
            </>
          )}
          {onlySearch ? (
            <Sticky position="top" offsetTop={stickyHeight.value as any}>
              <Search
                onSearch={onSearch}
                background="transparent"
                inputBackground="white"
                // leftIcon={iconSearch}
                class={styles.searchGroup}
                // v-slots={{
                //   left: () => (
                //     <div
                //       class={[styles.label, styles.searchs]}
                //       onClick={() => (subject.show = true)}
                //     >
                //       {baseState.platformType === 'TEACHER'
                //         ? teacherDetaultSubject.value.name
                //         : subject.name}

                //       <Icon
                //         classPrefix="iconfont"
                //         name="down"
                //         size={12}
                //         color="#949597"
                //       />
                //     </div>
                //   )
                // }}
              />
            </Sticky>
          ) : (
            ''
          )}

          <div class={[styles.alumnList, onlySearch && styles.alumnListOnly]}>
            <List
              loading={loading.value}
              finished={finished.value}
              finished-text={data.value && data.value.rows.length ? '' : ''}
              onLoad={FetchList}
              error={isError.value}
            >
              {data.value && data.value.rows.length ? (
                <Song
                  list={data.value.rows}
                  onDetail={(item: any) => {
                    if (onItemClick === noop) {
                      const url =
                        location.origin +
                        location.pathname +
                        '#/music-detail?id=' +
                        item.id
                      //  + '&instrumentId=' + subject.instrumentId
                      openDefaultWebView(url, () => {
                        router.push({
                          path: '/music-detail',
                          query: {
                            id: item.id
                            // instrumentId: subject.instrumentId
                          }
                        })
                      })
                    } else {
                      onItemClick?.(item)
                    }
                  }}
                />
              ) : (
                !loading.value && (
                  <ColResult
                    tips="暂无曲目"
                    classImgSize="SMALL"
                    btnStatus={false}
                  />
                )
              )}
            </List>
          </div>
          <Popup
            show={tagVisibility.value}
            round
            closeable
            position="bottom"
            style={{ height: '60%' }}
            teleport="body"
            onUpdate:show={val => (tagVisibility.value = val)}
          >
            <SelectTag
              exquisiteFlag
              onConfirm={onComfirm}
              onCancel={() => {
                //
              }}
              defaultValue={route.query.tagids as string}
            />
          </Popup>

          {/* 声部弹框 */}
          {/* <Popup
            show={subject.show}
            position="bottom"
            round
            closeable
            safe-area-inset-bottom
            onClose={() => (subject.show = false)}
            onClosed={() => (subject.show = false)}
          >
            <SelectSubject
              type="MUSIC"
              searchParams={
                baseState.platformType === 'TEACHER'
                  ? teacherDetaultSubject.value
                  : subject
              }
              onComfirm={onComfirmSubject}
            />
          </Popup> */}
        </>
      )
    }
  }
})
