import { Button, Sticky, Toast } from 'vant'
import { defineComponent } from 'vue'
import styles from './index.module.less'
import CertInfo from './cert-info'
import ColProtocol from '@/components/col-protocol'
import { teacherState } from './teacherState'
import Steps from './steps'
import CertOne from './cert-one'
import CertTwo from './cert-two'
import CertThree from './cert-three'
import { checkIDCard } from '@/helpers/validate'
import request from '@/helpers/request'
import ColResult from '@/components/col-result'
import { state } from '@/state'
import ColHeader from '@/components/col-header'
import { browser } from '@/helpers/utils'

export default defineComponent({
  name: 'teacherCert',
  data() {
    const query = this.$route.query
    return {
      agreeStatus: false
    }
  },
  async mounted() {
    try {
      // 老师入驻状态 0、未申请 UNPAALY、未申请 DOING、审核中 PASS、通过 UNPASS、不通过
      const entryStatus = state.user.data?.entryStatus || 0
      teacherState.authStatus =
        entryStatus === 'DOING' || entryStatus === 'PASS' ? true : false
      // 如果已经认证，则不用获取声部信息
      if (teacherState.authStatus) {
        teacherState.active = teacherState.authStatus ? 4 : 1
        return
      }

      if (teacherState.subjectList.length <= 0) {
        const res = await request.get('/api-teacher/subject/subjectSelect')
        teacherState.subjectList = res.data || []
      }

      const teacherInfo = await request.get(
        '/api-teacher/teacherAuthEntryRecord/getLastRecordByUserId'
      )
      teacherState.teacherInfo = teacherInfo.data || {}
      const info = teacherState.teacherInfo
      teacherState.teacherCert.introduction = info.introduction
      teacherState.teacherCert.subjectId = info.subjectId
      teacherState.teacherCert.graduateSchool = info.graduateSchool
      teacherState.teacherCert.subject = info.subject
      teacherState.teacherCert.styleVideo = info.styleVideoJson
        ? JSON.parse(info.styleVideoJson)
        : [{ videoUrl: '', cover: '' }]
      teacherState.teacherCert.gradCertificate = info.gradCertificate
      teacherState.teacherCert.degreeCertificate = info.degreeCertificate
      teacherState.teacherCert.teacherCertificate = info.teacherCertificate

      // 判断是否在声部，如果没有声部则取用户信息里面的声部
      if (!info.subjectId) {
        teacherState.teacherCert.subjectId = state.user.data.subjectId || ''
      }
    } catch {
      //
    }
  },
  computed: {
    authStatus(): boolean {
      return !!teacherState.authStatus
    },
    userAuth() {
      // 判断是否实名过
      const users = state.user.data || {}
      return !!(users.idCardNo && users.realName)
    }
  },
  methods: {
    async next() {
      const realName = teacherState.teacherCert.realName
      if (!realName) {
        Toast('请填写真实姓名')
        return
      }
      const idCardNo = teacherState.teacherCert.idCardNo
      if (!this.userAuth) {
        if (!checkIDCard(idCardNo || '')) {
          Toast('请填写正确的身份证号码')
          return false
        }
      }

      if (!this.agreeStatus) {
        Toast('请阅读并同意协议')
        return
      }

      if (!teacherState.teacherCert.birthdate) {
        Toast('请选择出生日期')
        return
      }

      try {
        if (!this.userAuth) {
          await request.post('/api-teacher/teacher/realNameAuth', {
            data: {
              realName,
              idCardNo,
              contract: true,
              save: true
            }
          })
        }
        teacherState.active = 2
      } catch {}
    },
    next2() {
      if (!teacherState.teacherCert.subjectId) {
        Toast('请选择教授科目')
        return
      }
      if (!teacherState.teacherCert.styleVideo[0].videoUrl) {
        Toast('请上传个人风采视频')
        return
      }
      if (!teacherState.teacherCert.styleVideo[0].cover) {
        Toast('请上传个人风采封面')
        return
      }
      teacherState.active = 3
    },
    async onSubmit() {
      try {
        const graduateSchool = teacherState.teacherCert.graduateSchool
        if (!graduateSchool) {
          Toast('请输入您的毕业院校')
          return
        }
        const subject = teacherState.teacherCert.subject
        if (!subject) {
          Toast('请输入您的专业')
          return
        }
        const teacherCert = teacherState.teacherCert
        teacherCert.styleVideoJson = JSON.stringify(teacherCert.styleVideo)
        await request.post('/api-teacher/teacherAuthEntryRecord/doApply', {
          data: teacherState.teacherCert
        })
        Toast('提交成功')
        teacherState.active = 4
      } catch {
        //
      }
    },
    prev() {
      teacherState.active = teacherState.active - 1
    }
  },
  render() {
    return (
      <div class={styles['teacher-cert']}>
        <div>
          {teacherState.active != 4 ? (
            <>
              {browser().isApp ? <ColHeader /> : ''}
              <Steps style={{ marginBottom: '12px' }} />
            </>
          ) : null}
          {teacherState.active === 1 ? (
            <>
              <CertOne />
              <div class={'btnGroup'}>
                <ColProtocol
                  v-model={this.agreeStatus}
                  prototcolType="REGISTER"
                  style={{ paddingLeft: 0, paddingRight: 0 }}
                />
                <Button
                  block
                  round
                  onClick={this.next}
                  type="primary"
                  text="下一步"
                />
              </div>
            </>
          ) : null}
          {teacherState.active === 2 ? (
            <>
              <CertTwo />
              <div class={['btnGroup', 'btnMore']}>
                <Button block round type="primary" plain onClick={this.prev}>
                  上一步
                </Button>
                <Button
                  block
                  round
                  onClick={this.next2}
                  type="primary"
                  text="下一步"
                />
              </div>
            </>
          ) : null}
          {teacherState.active === 3 ? (
            <>
              <CertThree />
              <div class={['btnGroup', 'btnMore']}>
                <Button block round type="primary" plain onClick={this.prev}>
                  上一步
                </Button>
                <Button
                  block
                  round
                  onClick={this.onSubmit}
                  type="primary"
                  text="提交审核"
                />
              </div>
            </>
          ) : null}

          {teacherState.active === 4 ? (
            <>
              <ColHeader />
              <ColResult
                type="teacherCert"
                style={{ paddingTop: '60px' }}
                classImgSize="CERT"
                buttonText={browser().isApp ? '我知道了' : '下载酷乐秀学院'}
                tips="感谢您的申请，小酷将在24小时内完成审核，请留意APP消息及短信获取审核结果。"
                onClick={() => {
                  if (browser().isApp) {
                    postMessage({ api: 'back', content: {} })
                  } else {
                    window.open(location.origin + '/student/#/download?type=teacher')
                  }
                }}
              />
            </>
          ) : null}
        </div>
      </div>
    )
  }
})
