import { defineComponent, onMounted, onUnmounted, reactive } from 'vue'
import styles from './index.module.less'
import signinTips from './images/signin-tips.png'
import { Button, CellGroup, Field, Picker, Popup, closeToast, showToast } from 'vant'
import { useRoute, useRouter } from 'vue-router'
import OWxTip from '@/components/o-wx-tip'
import { browser, getUrlCode } from '@/helpers/utils'
import qs from 'query-string'
import request from '@/helpers/request'
import { goWechatAuth } from '@/state'
import { useInterval, useIntervalFn } from '@vueuse/core'
const classList: any[] = []
for (let i = 1; i <= 40; i++) {
  classList.push({ text: i + '班', value: i })
}
export default defineComponent({
  name: 'pre-register',
  setup() {
    // 页面定时
    const pageTimer = useInterval(1000, { controls: true })
    pageTimer.pause()
    const router = useRouter()
    const route = useRoute()
    const forms = reactive({
      loading: true,
      orchestraId: route.query.id,
      code: null,
      currentGradeList: [
        { text: '一年级', value: 1 },
        { text: '二年级', value: 2 },
        { text: '三年级', value: 3 },
        { text: '四年级', value: 4 },
        { text: '五年级', value: 5 }
      ], // 年级数组列表
      showPicker: false,
      classPicker: false,
      nameReg: /^[\u4E00-\u9FA5]+$/,
      openId: '' as any,
      id: null,
      videoBrowseData: null,
      videoBrowsePoint: null,
      username: '',
      currentGrade: '', // 年级
      currentClass: '', // 班级
      intervalFnRef: null as any,
      applyStatus: false,
      isPageHide: false
    })

    const message = (value: string) => {
      if (!value) {
        return '请填写学生真实姓名'
      } else if (!forms.nameReg.test(value)) {
        return '学员姓名必须为中文'
      } else if (value.length < 2 || value.length > 15) {
        return '学员姓名必须为2~15个字'
      }
    }

    const onSubmit = async () => {
      try {
        if (forms.applyStatus) {
          showToast('家长会调查问卷已结束')
          return
        }

        if (message(forms.username)) {
          showToast(message(forms.username))
          return
        }

        if (!forms.currentGrade) {
          showToast('请选择年级')
          return
        }

        if (!forms.currentClass) {
          showToast('请选择班级')
          return
        }
        // 暂停回调
        forms.intervalFnRef?.pause()
        // 页面计时暂停
        pageTimer.pause()
        await request.post('/api-student/open/studentBrowseRecord/updateStat', {
          data: {
            id: forms.id,
            pageBrowseTime: pageTimer.counter.value,
            username: forms.username,
            currentGrade: forms.currentGrade,
            currentClass: forms.currentClass ? Number(forms.currentClass) : null
          }
        })

        router.push({
          path: '/pre-register-video',
          query: {
            saveId: forms.id,
            id: forms.orchestraId, // 乐团编号
            openId: forms.openId //
          }
        })
      } catch {
        // 还原
        forms.intervalFnRef?.resume()
        pageTimer.resume()
      }
      // router.push('/pre-register-video')
    }

    const formatterClass = (value: any, list: any[]) => {
      let txt = ''
      list.forEach((listItem: any) => {
        if (listItem.value == value) {
          txt = listItem.text
        }
      })
      return txt
    }

    // 更新时间
    const updateStat = async (pageBrowseTime = 10) => {
      try {
        await request.post('/api-student/open/studentBrowseRecord/updateStat', {
          data: {
            id: forms.id,
            pageBrowseTime // 固定10秒
          }
        })
      } catch {
        //
      }
    }

    onMounted(async () => {
      try {
        if (!forms.orchestraId) {
          showToast('信息获取失败，请联系老师')
        }
        const { data } = await request.get(
          '/api-student/open/orchestra/detail/' + forms.orchestraId
        )
        const schoolSystem = data.schoolSystem || 'sixYearSystem'
        if (schoolSystem === 'sixYearSystem') {
          forms.currentGradeList.push({ text: '六年级', value: 6 })
        }

        // 判断是否获取微信code码
        if (!forms.code) return

        if (data.status !== 'PRE_REGISTER') {
          showToast('家长会调查问卷已结束')
          forms.applyStatus = true
          return
        }
        const recordAdd = await request.post('/api-student/open/studentBrowseRecord/add', {
          data: {
            orchestraId: forms.orchestraId,
            code: forms.code,
            openId: forms.openId
          }
        })
        const recordObj = recordAdd.data
        forms.currentClass = recordObj.currentClass
        forms.currentGrade = recordObj.currentGrade
        forms.openId = recordObj.openId
        forms.username = recordObj.username
        forms.videoBrowseData = recordObj.videoBrowseData
        forms.videoBrowsePoint = recordObj.videoBrowsePoint
        forms.id = recordObj.id

        sessionStorage.setItem('active-open-id', recordObj.openId)

        pageTimer.resume()
        // 间隔10秒更新停留时间
        forms.intervalFnRef = useIntervalFn(() => {
          // 页面时间恢复
          pageTimer.counter.value = 0
          pageTimer.resume()
          updateStat()
        }, 10000)
      } catch {
        //
      }
    })

    const getAppIdAndCode = async (url?: string) => {
      try {
        const { data } = await request.get('/api-school/open/paramConfig/wechatAppId')
        // 判断是否有微信appId
        if (data) {
          closeToast()
          goWechatAuth(data, url)
        }
      } catch {
        //
      }
    }

    if (browser().weixin) {
      //授权
      const openId = sessionStorage.getItem('active-open-id')
      forms.openId = openId
      const code = getUrlCode()
      if (!code) {
        const newUrl =
          window.location.origin +
          window.location.pathname +
          '#' +
          route.path +
          '?' +
          qs.stringify({
            ...route.query
          })
        getAppIdAndCode(newUrl)
        return ''
      } else {
        forms.code = code
      }
    }

    const onPageShow = () => {
      console.log(forms.isPageHide, 'showInfo')
      if (forms.isPageHide) {
        window.location.reload()
      }
    }
    // 处理监听页面返回不刷新的问题
    window.addEventListener('pageshow', onPageShow)

    const onPageHide = () => {
      console.log(forms.isPageHide, 'showInfo')
      forms.isPageHide = true
    }
    window.addEventListener('pagehide', onPageHide)

    onUnmounted(() => {
      window.removeEventListener('pageshow', onPageShow)
      window.removeEventListener('pagehide', onPageHide)
    })
    return () => (
      <div class={styles['per-register-active']}>
        <div class={styles.flowPath}>
          <i class={styles.flowPathTitle}></i>
          <div class={styles.flowPathContent}>
            一、请所有家长进行<span>签到</span>
            <br />
            二、<span>观看</span>管乐团家长会议
            <br />
            1、学校领导讲话（5分钟）
            <br />
            2、基金会老师介绍乐团事项（20分钟）
            <br />
            <p
              style={{
                'padding-left': '1em'
              }}
            >
              *乐团组建背景及政策
              <br />
              *乐团发展规划与乐器知识讲解
              <br />
              *学校/基金会/家长各方职责与投入
              <br />
              *入团流程讲解
            </p>
            三、会后，家长可点击<span>“乐团报名”</span>或扫码进行正式报名
          </div>
        </div>

        <div class={styles.signin}>
          <div class={styles.tips}>
            <img src={signinTips} class={styles.signinTips} />
            <p>
              请先进行<span>签到</span>，再观看<span>管乐团家长会视频</span>
            </p>
          </div>

          <CellGroup class={styles.cellGroup} border={false}>
            <Field
              label="学生姓名"
              labelAlign="top"
              placeholder="请输入学生姓名"
              autocomplete="off"
              v-model={forms.username}
            />
            <Field
              label="年级"
              labelAlign="top"
              placeholder="请选择年级"
              isLink
              readonly
              modelValue={formatterClass(forms.currentGrade, forms.currentGradeList)}
              clickable={false}
              onClick={() => (forms.showPicker = true)}
            />
            <Field
              label="班级"
              labelAlign="top"
              placeholder="请选择班级"
              isLink
              readonly
              modelValue={formatterClass(forms.currentClass, classList)}
              clickable={false}
              onClick={() => (forms.classPicker = true)}
            />

            <Button class={styles.submitBtn} onClick={onSubmit}></Button>
          </CellGroup>
        </div>

        {/* 是否在微信中打开 */}
        <OWxTip />

        {/* 年级 */}
        <Popup v-model:show={forms.showPicker} position="bottom" round>
          <Picker
            columns={forms.currentGradeList}
            onCancel={() => (forms.showPicker = false)}
            onConfirm={({ selectedValues }) => {
              forms.currentGrade = selectedValues[0]
              forms.showPicker = false
            }}
          />
        </Popup>

        {/* 班级 */}
        <Popup v-model:show={forms.classPicker} position="bottom" round>
          <Picker
            columns={classList}
            onCancel={() => (forms.classPicker = false)}
            onConfirm={({ selectedValues }) => {
              forms.currentClass = selectedValues[0]
              forms.classPicker = false
            }}
          />
        </Popup>
      </div>
    )
  }
})
