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'
import OActionSheet from '@/components/o-action-sheet'
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,
      action: [
        { name: '班级类型', id: 'ALL', selected: true },
        { name: '单技班', id: 'SINGLE' },
        { name: '乐理班', id: 'MUSIC_THEORY' },
        { name: '合奏班', id: 'INSTRUMENTAL_ENSEMBLE' }
      ]
    })
    const platformApi = state.platformApi
    const refreshing = ref(false)
    const loading = ref(false)
    const getList = async () => {
      if (form.isClick) {
        return
      }
      form.isClick = true
      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 = form.list.concat(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
      }
      form.isClick = false
    }
    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"
          onGetHeight={(height: any) => {
            document.documentElement.style.setProperty('--header-height', height + 'px')
          }}
        >
          {/* */}
          <OHeader border={false}>
            {{
              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={['searchItem-left', form.oPopover ? 'searchItem-active' : '']}
                  onClick={() => (form.oPopover = true)}
                >
                  <span>{form.statusText} </span>
                </div>
              )
            }}
          />
        </OSticky>

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

        <OActionSheet
          v-model:show={form.oPopover}
          actions={form.action}
          onSelect={(item: any) => {
            form.action.forEach((child: any) => {
              child.selected = false
            })
            item.selected = true
            form.statusText = item.name
            form.params.classTypeCode = item.id === 'ALL' ? null : item.id
            form.oPopover = false
            onSearch()
          }}
        />
      </div>
    )
  }
})
