import OEmpty from '@/components/o-empty'
import request from '@/helpers/request'
import { state } from '@/state'
import OFullRefresh from '@/components/o-full-refresh'
import { Cell, CellGroup, DropdownItem, DropdownMenu, Icon, List } from 'vant'
import { defineComponent, reactive, ref, onMounted, nextTick, computed } from 'vue'
import { useRoute } from 'vue-router'
import styles from './index.module.less'
import OSticky from '@/components/o-sticky'
import OSearch from '@/components/o-search'
import OHeader from '@/components/o-header'
import { getImage } from '@/views/accompany/images'
import { unitData } from './data'

export default defineComponent({
  name: 'accompany-music-list',
  emits: ['confirm'],
  setup(props, { emit }) {
    const imgDefault = getImage('icon-music.svg')
    const subjectKey = state.user?.data?.phone || 'accompany-music-list-subject'
    const subjectId =
      localStorage.getItem(subjectKey) || state.user?.data?.subjectId?.split(',')?.[0] || ''
    const data = reactive({
      loading: false,
      firstRender: false,
      finished: false,
      refreshing: false,
      musicTree: [] as any,
      pagenation: {
        page: 1,
        rows: 20
      },
      value0: null,
      value1: null,
      value2: null,
      PopoverOpen: false,
      list: [] as any,
      keyword: '',
      // 合奏班默认选中所有声部
      musicSubject: unitData.courseType === 'INSTRUMENTAL_ENSEMBLE' ? '' : subjectId,
      subjectList: [] as any
    })

    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

          // 默认选择独奏曲目
          const item = data.musicTree.find((item: any) => item.name === '独奏曲目')
          if (item) {
            data.value0 = item.id
          }
        }
      } catch (error) {
        console.log(error)
      }
    }
    // 获取声部信息
    const getSubjects = async () => {
      try {
        const subjects = await request.post(state.platformApi + '/open/subjectBasicConfig/page', {
          data: {
            enableFlag: true,
            page: 1,
            rows: 100
          }
        })
        const rows = subjects.data.rows || []
        data.subjectList.push({
          text: '全部',
          value: ''
        })
        rows.forEach((item: any) => {
          data.subjectList.push({
            text: item.subjectName,
            value: item.subjectId + ''
          })
        })
      } catch {
        //
      }
    }
    const option0 = computed(() => {
      const v1: any = data.musicTree
      if (Array.isArray(v1)) {
        const list = v1.map((m: any) => {
          if (!data.value0) {
            data.value0 = m.id
            data.value1 = null
            data.value2 = null
          }
          return {
            text: m.name,
            value: m.id
          }
        })
        return list
      }
      return []
    })

    const option1 = computed(() => {
      const v1: any = data.musicTree.find((n: any) => n.id == data.value0)
      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 == data.value0)
      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
      const bodyData: any = {
        ...data.pagenation,
        keyword: data.keyword,
        musicSheetCategoriesId: data.value2 || data.value1,
        status: 1,
        musicSubject: data.musicSubject
      }
      try {
        const res: any = await request.post(state.platformApi + '/musicSheet/page', {
          data: bodyData,
          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 < data.pagenation.rows ? true : false
        } else {
          data.finished = true
        }
      } catch (error) {
        data.finished = true
      }
      data.loading = false
      data.refreshing = false
      data.firstRender = true
    }
    // 重置搜索
    const onSearch = () => {
      data.pagenation.page = 1
      data.list = []
      data.finished = false
      data.list = []
      getList()
    }

    //
    const onDetail = (row: any) => {
      emit('confirm', row)
    }
    onMounted(async () => {
      await getTree()
      nextTick(async () => {
        await getSubjects()
        await getList()
      })
    })

    return () => (
      <div class={styles['accompany-music-list']}>
        <OSticky
          mode="sticky"
          class={styles.heade}
          onGetHeight={(height: number) => {
            document.documentElement.style.setProperty('--header-height', height + 'px')
          }}
        >
          <OHeader border={false} />
          <div>
            <DropdownMenu activeColor="var(--van-primary)">
              <DropdownItem
                v-model:modelValue={data.musicSubject}
                options={data.subjectList}
                onChange={() => {
                  localStorage.setItem(subjectKey, data.musicSubject)
                  onSearch()
                }}
              ></DropdownItem>
              <DropdownItem
                v-model:modelValue={data.value0}
                options={option0.value}
                onChange={() => {
                  data.value1 = null
                  data.value2 = null
                  nextTick(() => {
                    onSearch()
                  })
                }}
              ></DropdownItem>
              <DropdownItem
                v-model:modelValue={data.value1}
                options={option1.value}
                onChange={() => {
                  data.value2 = null
                  onSearch()
                }}
              ></DropdownItem>
              <DropdownItem
                v-model:modelValue={data.value2}
                options={option2.value as any}
                onChange={() => onSearch()}
              ></DropdownItem>
            </DropdownMenu>
            <div class={styles.filter}>
              <OSearch
                background="#f8f8f8"
                inputBackground="white"
                class={styles.filterBox}
                onSearch={(keyword: string) => {
                  data.keyword = keyword
                  onSearch()
                }}
              />
            </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}
                    clickable
                    onClick={() => onDetail(item)}
                  >
                    {{
                      icon: () => (
                        <Icon style={{ marginRight: '12px' }} size={40} name={imgDefault} />
                      )
                    }}
                  </Cell>
                )
              })}
            </CellGroup>
            <div style={{ height: '40px' }}></div>
          </List>
          {data.firstRender && !data.loading && !data.list.length && <OEmpty tips="暂无曲谱" />}
        </OFullRefresh>
        {/* <Popup teleport="body" position="bottom" round v-model:show={staffData.open}>
          <Picker
            columns={staffData.musicXml[staffData.instrumentName]}
            onConfirm={(value) => {
              staffData.open = false
              staffData.partIndex = value.selectedValues[0]
              openView({ id: staffData.instrumentName })
            }}
            onCancel={() => (staffData.open = false)}
          />
        </Popup> */}
      </div>
    )
  }
})
