import { defineComponent, nextTick, onMounted, reactive, ref } 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 { 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'

const noop = () => {
  //
}

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

    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]
        : ''
      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'
    }
    // 判断是否在搜索页面用过
    if (!hideSearch) {
      const getSubject: any = useSubjectId(SubjectEnum.SEARCH)
      tempParams.subjectIds = getSubject.id
    }
    //
    const params = reactive({
      search: (route.query.search 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 exquisiteFlag = ref(false)
    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.exquisiteFlag = 1
      }
      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 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
      subject.id = item.id
      subject.name = item.name
      data.value = null
      useSubjectId(
        SubjectEnum.SEARCH,
        JSON.stringify({
          id: item.id,
          name: item.name
        }),
        'set'
      )

      FetchList()
      subject.show = false
    }

    const getSubject: any = useSubjectId(SubjectEnum.SEARCH)
    const subject = reactive({
      show: false,
      name: getSubject.id ? getSubject.name : '全部声部',
      id: getSubject.id || ''
    })

    expose({
      onSearch,
      onComfirm,
      onComfirmSubject
    })

    return () => {
      const tagList = ((state.value && state.value.data) as any) || []
      return (
        <>
          {!hideSearch && (
            <>
              {' '}
              <Sticky class={styles.sticky}>
                <ColHeader
                  background="transparent"
                  isFixed={false}
                  border={false}
                  backIconColor="white"
                  color="#fff"
                  v-slots={{
                    right: () => (
                      <span
                        class={styles.fleg}
                        onClick={() => {
                          exquisiteFlag.value != exquisiteFlag.value
                          data.value = null
                          params.page = 1
                          FetchList()
                        }}
                      >
                        <span>精品</span>
                        <Switch v-model={exquisiteFlag.value} size="20px" />
                      </span>
                    )
                  }}
                />
                <Search
                  onSearch={onSearch}
                  background="transparent"
                  inputBackground="transparent"
                  leftIcon={iconSearch}
                  v-slots={{
                    left: () => (
                      <div
                        class={styles.label}
                        onClick={() => (subject.show = true)}
                      >
                        {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>
              </Sticky>
              <img class={styles.bgImg} src={bgImg} />
            </>
          )}
          <div class={styles.alumnList}>
            <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) {
                      router.push({
                        path: '/music-detail',
                        query: {
                          id: item.id
                        }
                      })
                    } 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={subject}
              onComfirm={onComfirmSubject}
            />
          </Popup>
        </>
      )
    }
  }
})
