import OEmpty from '@/components/o-empty'
import OHeader from '@/components/o-header'
import OSearch from '@/components/o-search'
import OSticky from '@/components/o-sticky'
import { ActionSheet, Button, Cell, CellGroup, Icon, Image, List, showToast } from 'vant'
import { defineComponent, onMounted, onUnmounted, reactive, ref } from 'vue'
import styles from './index.module.less'
import iconEdit from '../images/icon-edit.png'
import iconAdd from '@common/images/icon_add.png'
import { useRouter } from 'vue-router'
import UnitListItem from './models/unit-list-item'
import OFullRefresh from '@/components/o-full-refresh'
import { state } from '@/state'
import request from '@/helpers/request'
import { postMessage } from '@/helpers/native-message'
export default defineComponent({
  name: 'unit-list',
  setup() {
    const router = useRouter()
    const form = reactive({
      oPopover: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },
      statusText: '班级类型',
      params: {
        keyword: null,
        classTypeCode: null,
        page: 1,
        rows: 20
      },
      isClick: false
    })
    const platformApi = state.platformApi
    const refreshing = ref(false)
    const loading = ref(false)
    const getList = async () => {
      loading.value = true
      try {
        if (refreshing.value) {
          form.params.page = 1
          form.list = []
          refreshing.value = false
        }
        const url =
          state.platformType === 'TEACHER'
            ? `${platformApi}/studentUnitExamination/queryPageByTeacher`
            : `${platformApi}/studentUnitExamination/queryPageByManage`

        const res = await request.post(url, {
          data: { ...form.params }
        })

        if (form.list.length > 0 && res.data.pages === 1) {
          return
        }

        form.params.page = res.data.current + 1
        //form.list  =form.list .concat(res.data.rows || [])
        form.list = res.data.rows
        form.listState.dataShow = form.list.length > 0
        loading.value = false
        // form.listState.finished = true

        form.listState.finished = res.data.current >= res.data.pages
      } catch (e: any) {
        // console.log(e, 'e')
        const message = e.message
        showToast(message)
        form.listState.dataShow = false
        form.listState.finished = true
      }
    }
    const onRefresh = () => {
      form.listState.finished = true
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      loading.value = true
      getList()
    }
    const onSearch = () => {
      form.params.page = 1
      form.list = []
      form.listState.dataShow = true // 判断是否有数据
      form.listState.loading = false
      form.listState.finished = false
      getList()
    }
    onMounted(() => {
      getList()

      // 处理返回上一页的问题
      window.history.pushState(null, '', document.URL)
      window.addEventListener('popstate', onBack, false)
    })

    const onBack = () => {
      postMessage({ api: 'back' })
    }

    onUnmounted(() => {
      window.removeEventListener('popstate', onBack)
    })

    const createUnit = () => {
      sessionStorage.removeItem('unit-create')
      router.push('/unit-create')
    }
    return () => (
      <div class={styles.unitTest}>
        <OSticky position="top">
          {/* */}
          <OHeader>
            {{
              right: () =>
                platformApi == '/api-teacher' ? (
                  <Icon name={iconAdd} size={19} onClick={createUnit} />
                ) : null
            }}
          </OHeader>
          <OSearch
            placeholder="请输入测验名称"
            inputBackground="white"
            background="#f6f8f9"
            onSearch={(val: any) => {
              form.params.keyword = val
              onSearch()
            }}
            v-slots={{
              left: () => (
                <div
                  class={styles.searchBand}
                  style={{ marginRight: '13px' }}
                  onClick={() => (form.oPopover = true)}
                >
                  {form.statusText} <Icon name={form.oPopover ? 'arrow-up' : 'arrow-down'} />
                </div>
              )
            }}
          />
        </OSticky>

        {form.listState.dataShow ? (
          <OFullRefresh
            v-model:modelValue={refreshing.value}
            onRefresh={onRefresh}
            style="min-height: 100vh;"
          >
            <List
              // v-model:loading={form.listState.loading}
              finished={form.listState.finished}
              finishedText=" "
              class={[styles.liveList]}
              onLoad={getList}
              immediateCheck={false}
            >
              {form.list.map((item: any) => (
                <UnitListItem item={item}></UnitListItem>
              ))}
            </List>
          </OFullRefresh>
        ) : (
          <OEmpty tips="暂无单元测验" />
        )}

        <ActionSheet
          v-model:show={form.oPopover}
          cancelText="取消"
          actions={
            [
              { name: '班级类型', id: 'ALL' },
              { name: '单技班', id: 'SINGLE' },
              { name: '乐理班', id: 'MUSIC_THEORY' },
              { name: '合奏班', id: 'INSTRUMENTAL_ENSEMBLE' }
            ] as any
          }
          onSelect={(val: any) => {
            form.statusText = val.name
            form.params.classTypeCode = val.id === 'ALL' ? null : val.id
            form.oPopover = false
            onSearch()
          }}
        />
      </div>
    )
  }
})
