import OEmpty from '@/components/o-empty'
import { postMessage } from '@/helpers/native-message'
import request from '@/helpers/request'
import { browser } from '@/helpers/utils'
import { state } from '@/state'
import { useRect } from '@vant/use'
import OFullRefresh from '@/components/o-full-refresh'
import {
  Cell,
  CellGroup,
  DropdownItem,
  DropdownMenu,
  Icon,
  List,
  Popover,
  PullRefresh,
  Search,
  showConfirmDialog,
  Sticky
} from 'vant'
import { defineComponent, reactive, ref, onMounted, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getImage } from './images'
import styles from './index.module.less'
import OSticky from '@/components/o-sticky'

export default defineComponent({
  name: 'accompany-music-list',
  props: {
    musicTree: {
      type: Array,
      default: () => []
    }
  },
  setup(props, ctx) {
    const route = useRoute()
    const router = useRouter()
    const imgDefault = getImage('icon-music.svg')
    const userInfo = ref<any>({})
    const data = reactive({
      loading: false,
      finished: false,
      refreshing: false,
      musicTree: [] as any,
      pagenation: {
        page: 1,
        rows: 20
      },
      value1: null,
      value2: null,
      PopoverOpen: false,
      list: [] as any,
      keyword: ''
    })
    const getTree = async () => {
      try {
        const res: any = await request.get(
          state.platformApi + '/musicSheetCategories/queryTree?enable=true'
        )
        if (Array.isArray(res?.data)) {
          data.musicTree = res.data
        }
        getList()
      } catch (error) {
        console.log(error)
      }
    }
    /**获取会员购买记录 */
    const getUserInfo = async () => {
      try {
        const res: any = await request.get(`/api-student/student/member`)
        userInfo.value = res.data || {}
      } catch (error) {}
    }
    const option1 = computed(() => {
      const v1: any = data.musicTree.find((n: any) => n.id == route.query.categorieid)
      if (Array.isArray(v1?.musicSheetCategoriesList)) {
        const list = v1.musicSheetCategoriesList.map((m: any) => {
          if (!data.value1) {
            data.value1 = m.id
            data.value2 = null
          }
          return {
            text: m.name,
            value: m.id
          }
        })
        return list
      }
      return []
    })
    const option2 = computed(() => {
      const v1: any = data.musicTree.find((n: any) => n.id == route.query.categorieid)
      if (Array.isArray(v1?.musicSheetCategoriesList)) {
        const v2: any = v1.musicSheetCategoriesList.find((n: any) => n.id == data.value1)
        if (Array.isArray(v2?.musicSheetCategoriesList)) {
          const list = [{ text: '全部', value: null }].concat(
            v2.musicSheetCategoriesList.map((m: any) => {
              return {
                text: m.name,
                value: m.id
              }
            })
          )
          return list
        }
      }
      return [{ text: '全部', value: null }]
    })

    const getList = async () => {
      if (data.loading) return
      data.loading = true
      try {
        const res: any = await request.post(state.platformApi + '/musicSheet/page', {
          data: {
            ...data.pagenation,
            keyword: data.keyword,
            musicSheetCategoriesId: data.value2 || data.value1
          },
          hideLoading: true
        })
        if (Array.isArray(res?.data?.rows)) {
          data.list = [].concat(data.list, res.data.rows)
          data.pagenation.page += 1
          data.finished = res.data.rows.length ? false : true
        } else {
          data.finished = true
        }
      } catch (error) {
        data.finished = true
      }
      data.loading = false
      data.refreshing = false
    }
    // 重置搜索
    const onSearch = () => {
      data.pagenation.page = 1
      data.list = []
      data.finished = false
      data.list = []
      getList()
    }
    //进入云教练
    const openView = (item: any) => {
      // 学生端验证
      if (state.platformType == 'STUDENT') {
        //学生有待激活会员
        if (!userInfo.value.membershipDays && userInfo.value.purchaseMemberRecord) {
          showConfirmDialog({
            message: '您的团练宝暂未激活，请激活后使用'
          }).then(() => {
            router.push({
              path: '/memberCenter'
            })
          })
          return
        }
        //学生没有会员
        if (!userInfo.value.vipMember) {
          showConfirmDialog({
            message: '您暂未开通团练宝，请开通后使用'
          }).then(() => {
            router.push({
              path: '/memberCenter'
            })
          })
          return
        }
      }

      let src = `${location.origin}/orchestra-music-score/?id=${item.id}`
      console.log('🚀 ~ 去云教练的src', src)
      postMessage({
        api: 'openAccompanyWebView',
        content: {
          url: src,
          orientation: 0,
          isHideTitle: true,
          statusBarTextColor: false,
          isOpenLight: true
        }
      })
    }
    onMounted(() => {
      getUserInfo()
      getTree()
    })
    return () => (
      <div class={styles['accompany-music-list']}>
        <OSticky
          mode="sticky"
          class={styles.heade}
          onGetHeight={(height: number) => {
            document.documentElement.style.setProperty('--header-height', height + 'px')
          }}
        >
          <div>
            <DropdownMenu>
              <DropdownItem
                v-model:modelValue={data.value1}
                options={option1.value}
                onChange={() => onSearch()}
              ></DropdownItem>
              <DropdownItem
                v-model:modelValue={data.value2}
                options={option2.value as any}
                onChange={() => onSearch()}
              ></DropdownItem>
            </DropdownMenu>
            <div class={styles.filter}>
              <Search
                placeholder="请输入搜索关键词"
                background="#F8F8F8"
                shape="round"
                showAction={true}
                v-model:modelValue={data.keyword}
              >
                {{
                  // label: () => (
                  //   <Popover
                  //     v-model:show={data.PopoverOpen}
                  //     actions={actions}
                  //     placement="bottom-start"
                  //   >
                  //     {{
                  //       reference: () => (
                  //         <div>
                  //           长笛 <Icon name="arrow" />
                  //         </div>
                  //       )
                  //     }}
                  //   </Popover>
                  // ),
                  action: () => (
                    <div class={styles.searchBtn} onClick={() => onSearch()}>
                      搜索
                    </div>
                  )
                }}
              </Search>
            </div>
          </div>
        </OSticky>
        <OFullRefresh
          v-model:modelValue={data.refreshing}
          onRefresh={onSearch}
          style="min-height: calc(100vh - var(--header-height))"
        >
          <List
            loading-text=" "
            immediateCheck={false}
            loading={data.loading}
            v-model:finished={data.finished}
            finishedText="没有更多了"
            onLoad={() => {
              getList()
            }}
          >
            <CellGroup inset>
              {data.list.map((item: any) => {
                return (
                  <Cell
                    size="large"
                    center
                    title={item.musicSheetName}
                    isLink
                    onClick={() => openView(item)}
                  >
                    {{
                      icon: () => (
                        <Icon style={{ marginRight: '12px' }} size={40} name={imgDefault} />
                      )
                    }}
                  </Cell>
                )
              })}
            </CellGroup>
          </List>
          {!data.loading && !data.list.length && <OEmpty tips="暂无曲谱" />}
        </OFullRefresh>
      </div>
    )
  }
})
