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, Popup } from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import styles from './index.module.less'
import iconEdit from './images/icon-edit.png'
import { useRouter } from 'vue-router'
import request from '@/helpers/request'
import { unitTestStatus } from '@/constant'
import dayjs from 'dayjs'
import NoticeStart from './model/notice-start'
import OFullRefresh from '@/components/o-full-refresh'

export default defineComponent({
  name: 'unit-test',
  setup() {
    const router = useRouter()
    const form = reactive({
      oPopover: false,
      searchList: [] as any,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false,
        refreshing: false,
        height: 0 // 页面头部高度，为了处理下拉刷新用的
      },
      statusText: '全部测验',
      params: {
        keyword: null,
        status: null,
        page: 1,
        rows: 20
      },
      isClick: false,
      visiableNotice: false,
      unitExam: {} as any, // 测验详情
      selectUnitExam: {} as any
    })

    const getList = async () => {
      try {
        if (form.isClick) return
        form.isClick = true
        const res = await request.post('/api-student/studentUnitExamination/queryPageByStudent', {
          data: {
            ...form.params
          }
        })
        form.listState.loading = false
        form.listState.refreshing = false
        const result = res.data || {}
        // 处理重复请求数据
        if (form.list.length > 0 && result.current === 1) {
          return
        }
        form.list = form.list.concat(result.rows || [])
        form.listState.finished = result.current >= result.pages
        form.params.page = result.current + 1
        form.listState.dataShow = form.list.length > 0
        form.isClick = false
      } catch {
        form.listState.dataShow = false
        form.listState.finished = true
        form.listState.refreshing = false
        form.isClick = false
      }
    }

    const onSearch = () => {
      form.params.page = 1
      form.list = []
      form.listState.dataShow = true // 判断是否有数据
      form.listState.loading = false
      form.listState.finished = false
      getList()
    }

    // 开始测验
    const onUnitTestStart = async (item: any) => {
      try {
        // 判断是否是继续测验
        form.selectUnitExam = item || {}
        if (item.status === 'C_ING') {
          onExamStart()
        }
        // 是不是未开始
        if (item.status === 'D_NO_SUBMIT') {
          const { data } = await request.get('/api-student/unitExamination/detail', {
            params: {
              unitExaminationId: item.unitExaminationId
            }
          })
          form.unitExam = data || {}
          form.visiableNotice = true
        }
      } catch {
        //
      }
    }

    const onExamStart = async () => {
      try {
        await request.post('/api-student/studentUnitExamination/startExamination', {
          requestType: 'form',
          data: {
            studentUnitExaminationId: form.selectUnitExam.id
          }
        })

        router.push({
          path: '/examination-mode',
          query: {
            id: form.selectUnitExam.id
          }
        })
      } catch {
        //
      }
    }

    onMounted(() => {
      getList()

      const temp: any = [{ name: '全部测验', id: 'ALL' }]
      for (const i in unitTestStatus) {
        temp.push({
          name: unitTestStatus[i],
          id: i
        })
      }
      form.searchList = temp
    })
    return () => (
      <div class={styles.unitTest}>
        <OSticky
          position="top"
          onGetHeight={(height: any) => {
            form.listState.height = height
          }}
        >
          <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={form.listState.refreshing}
            onRefresh={onSearch}
            style={{
              minHeight: `calc(100vh - ${form.listState.height}px)`
            }}
          >
            <List
              v-model:loading={form.listState.loading}
              finished={form.listState.finished}
              finishedText=" "
              class={[styles.liveList]}
              onLoad={getList}
              immediateCheck={false}
            >
              {/* <audio controls>
                <source src="horse.mp3" type="audio/mpeg" />
                <source src="horse.ogg" type="audio/ogg" />
                您的浏览器不支持该音频格式。
              </audio> */}
              {form.list.map((item: any) => (
                <CellGroup inset class={styles.cellGroup} border={false}>
                  <Cell center isLink clickable={false}>
                    {{
                      icon: () => <Image src={iconEdit} class={styles.img} />,
                      title: () => (
                        <span class={[styles.unitTitle, 'van-ellipsis']}>{item.name}</span>
                      ),
                      value: () => (
                        <span
                          class={[
                            styles['no-start'],
                            item.status === 'A_PASS' && styles.pass,
                            item.status === 'B_NO_PASS' && styles['no-pass']
                          ]}
                        >
                          {unitTestStatus[item.status]}
                        </span>
                      )
                    }}
                  </Cell>
                  <Cell center class={styles.unitSection}>
                    {{
                      title: () => (
                        <div class={styles.unitInformation}>
                          <div class={styles.name}>{item.orchestraName}</div>
                          <div class={styles.endTime}>
                            截止时间：
                            {dayjs(item.expiryDate || new Date()).format('YYYY-MM-DD HH:mm')}
                          </div>

                          <div class={styles.unitBtnGroup}>
                            <Button
                              color="#FFF0E6"
                              round
                              block
                              style={{ color: '#F67146' }}
                              onClick={() => {
                                router.push('/test-exercise')
                              }}
                            >
                              练习模式
                            </Button>
                            <Button
                              type="primary"
                              round
                              block
                              disabled={item.status === 'A_PASS' || item.status === 'B_NO_PASS'}
                              onClick={() => onUnitTestStart(item)}
                            >
                              {item.status === 'C_ING' ? '继续测验' : '开始测验'}
                            </Button>
                          </div>
                        </div>
                      )
                    }}
                  </Cell>
                </CellGroup>
              ))}
            </List>
          </OFullRefresh>
        ) : (
          <OEmpty tips="暂无单元测验" />
        )}

        <ActionSheet
          v-model:show={form.oPopover}
          cancelText="取消"
          actions={form.searchList}
          onSelect={(val: any) => {
            form.statusText = val.name
            form.params.status = val.id === 'ALL' ? null : val.id
            form.oPopover = false
            onSearch()
          }}
        />

        {/* 测验须知 */}
        <Popup
          v-model:show={form.visiableNotice}
          round
          style={{ width: '90%' }}
          closeOnClickOverlay={false}
        >
          <NoticeStart
            data={form.unitExam}
            onClose={() => {
              form.visiableNotice = false
            }}
            onConfirm={onExamStart}
          />
        </Popup>
      </div>
    )
  }
})
