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, TransitionGroup } 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'
import ODialog from '@/components/o-dialog'
import { setLogin, state } from '@/state'
import OActionSheet from '@/components/o-action-sheet'

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,
      dialogMessage: '',
      dialogStatus: false
    })

    const getList = async (status = false) => {
      try {
        if (form.isClick) return
        form.isClick = true
        const res = await request.post('/api-student/studentUnitExamination/queryPageByStudent', {
          // hideLoading: status,
          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 = (status = false) => {
      form.params.page = 1
      form.list = []
      form.listState.dataShow = true // 判断是否有数据
      form.listState.loading = false
      form.listState.finished = false
      getList(status)
    }

    // 开始测验
    const onUnitTestStart = async (item: any) => {
      try {
        // 判断是否是会员
        if (!state.user.data.vipMember) {
          form.dialogStatus = true
          form.dialogMessage = '您暂未开通团练宝，请开通后使用'
          return
        }
        // 判断是否是继续测验
        form.selectUnitExam = item || {}
        if (item.status === 'C_ING') {
          onExamStart()
        }
        // 是不是未开始
        if (item.status === 'D_NO_SUBMIT') {
          const { data } = await request.post(
            '/api-student/studentUnitExamination/getExaminationDetail',
            {
              requestType: 'form',
              hideLoading: false,
              data: {
                studentUnitExaminationId: item.id
              }
            }
          )
          form.unitExam = data || {}
          form.visiableNotice = true
        }
      } catch {
        //
      }
    }

    // 查看测验
    const onUnitTestLook = (item: any) => {
      //
      router.push({
        path: '/unit-detail',
        query: {
          id: item.id
        }
      })
    }

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

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

    onMounted(async () => {
      const unitType = sessionStorage.getItem('unit-test-search-type')
      const temp: any = [{ name: '全部测验', id: 'ALL', selected: true }]
      let selectItem = {} as any
      for (const i in unitTestStatus) {
        temp.push({
          name: unitTestStatus[i],
          id: i
        })
        if (i === unitType) {
          selectItem = {
            name: unitTestStatus[i],
            id: i
          }
        }
      }
      form.searchList = temp
      if (selectItem.id && selectItem.id !== 'ALL') {
        form.statusText = selectItem.name
        form.params.status = selectItem.id
      }

      try {
        // 重新初始化用户信息
        const userCash = await request.get(state.platformApi + '/user/getUserInfo')
        setLogin(userCash.data)
      } catch {
        //
      }
      await getList()
    })
    return () => (
      <div class={[styles.unitTest, !form.listState.dataShow && 'emptyRootContainer']}>
        <OSticky
          position="top"
          onGetHeight={(height: any) => {
            form.listState.height = height
          }}
        >
          <OHeader border={false} />
          <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={form.listState.refreshing}
            onRefresh={() => onSearch(true)}
            style={{
              minHeight: `calc(100vh - ${form.listState.height}px)`
            }}
          >
            <List
              // v-model:loading={form.listState.loading}
              finished={form.listState.finished}
              finishedText=" "
              class={[styles.liveList]}
              style={{
                paddingTop: '12px'
              }}
              onLoad={getList}
              immediateCheck={false}
            >
              {form.list.map((item: any) => (
                <CellGroup inset class={styles.cellGroup} border={false}>
                  <Cell
                    center
                    // isLink
                    clickable={false}
                    titleStyle={{ flex: '1 auto' }}
                    valueClass={[
                      styles['no-start'],
                      item.status === 'A_PASS' && styles.pass,
                      item.status === 'B_NO_PASS' && styles['no-pass']
                    ]}
                  >
                    {{
                      icon: () => <Image src={iconEdit} class={styles.img} />,
                      title: () => (
                        <div class={[styles.unitTitle, 'van-ellipsis']}>{item.name}</div>
                      ),
                      value: () => unitTestStatus[item.status]
                    }}
                  </Cell>
                  <Cell center class={styles.unitSection}>
                    {{
                      title: () => (
                        <div class={styles.unitInformation}>
                          <div>
                            <div class={styles.name}>{item.orchestraName}</div>
                            <div class={styles.endTime}>
                              截止时间：
                              {dayjs(item.expiryDate || new Date()).format('YYYY-MM-DD')}
                            </div>
                          </div>
                          {item.status === 'A_PASS' || item.status === 'B_NO_PASS' ? (
                            <span>
                              {item.score || 0}
                              <i>分</i>
                            </span>
                          ) : (
                            ''
                          )}
                        </div>
                      ),

                      label: () => (
                        <div class={styles.unitBtnGroup}>
                          <Button
                            color="#FFF0E6"
                            round
                            block
                            style={{ color: '#F67146' }}
                            onClick={() => {
                              router.push({
                                path: '/test-exercise',
                                query: {
                                  id: item.unitExaminationId
                                }
                              })
                            }}
                          >
                            练习模式
                          </Button>
                          {item.status === 'A_PASS' || item.status === 'B_NO_PASS' ? (
                            <Button type="primary" round block onClick={() => onUnitTestLook(item)}>
                              查看测验
                            </Button>
                          ) : (
                            <Button
                              type="primary"
                              round
                              block
                              disabled={dayjs(dayjs().format('YYYY-MM-DD')).isAfter(
                                dayjs(item.expiryDate)
                              )}
                              onClick={() => onUnitTestStart(item)}
                            >
                              {item.status === 'C_ING' ? '继续测验' : '开始测验'}
                            </Button>
                          )}
                        </div>
                      )
                    }}
                  </Cell>
                </CellGroup>
              ))}
            </List>
          </OFullRefresh>
        ) : (
          <OEmpty tips="暂无阶段自测" />
        )}

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

        <ODialog
          message={form.dialogMessage}
          v-model:show={form.dialogStatus}
          showCancelButton
          cancelButtonText="取消"
          confirmButtonText="立即开通"
          onConfirm={() => {
            router.push('/memberCenter')
          }}
        />

        <OActionSheet
          v-model:show={form.oPopover}
          actions={form.searchList}
          onSelect={(val: any) => {
            form.searchList.forEach((child: any) => {
              child.selected = false
            })
            val.selected = true
            form.statusText = val.name
            form.params.status = val.id === 'ALL' ? null : val.id
            sessionStorage.setItem('unit-test-search-type', val.id)
            form.oPopover = false
            onSearch()
          }}
        />
      </div>
    )
  }
})
