import { areas } from '@/helpers/area'
import request from '@/helpers/request'
import {
  CellGroup,
  Form,
  Field,
  RadioGroup,
  Tag,
  Icon,
  Checkbox,
  Radio,
  Button,
  showToast,
  showDialog,
  showLoadingToast,
  closeToast,
  Picker,
  Popup,
  CountDown
} from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import { useRoute } from 'vue-router'
import styles from './manage-teacher-register.module.less'
import ImgCode from '@/components/o-img-code'
import schoolLogo from './images/school-logo.png'
import iconClose from './images/icon-close.png'
import topBanner1 from './images/top-banner.png'
import { checkPhone } from '@/helpers/validate'
import dayjs from 'dayjs'
import { browser, getUrlCode } from '@/helpers/utils'
import OUpload from '@/components/o-upload'
import qs from 'query-string'

export default defineComponent({
  name: 'companion-teacher-register',

  setup() {
    const route = useRoute()
    const state = reactive({
      showPicker: false,
      showSubject: false,
      submitStatus: false,
      id: route.query.id,
      name: route.query.name,
      t: route.query.t as any, // 过期时间
      qrCodeStatus: false, // 二维码是否失效
      qrCodeMessage: '',
      pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
      columns: [] as any,
      pickerType: null, // 下拉类型
      forms: {
        realName: '',
        phone: null,
        gender: 1,
        idCardNo: null,
        smsValidCode: '',
        idcardFrontImg: '',
        idcardBackImg: '' // 身份证反面照
      },
      btnLoading: false,
      checkPhone: false,
      checked: true,
      columnSubject: [] as any,
      countDownStatus: true, // 是否发送验证码
      countDownTime: 120, // 倒计时时间
      // countDownRef: null as any, // 倒计时实例
      imgCodeStatus: false,
      showPopup: false,
      code: ''
    })

    const onSubmit = async () => {
      if (state.qrCodeStatus) {
        showDialog({
          title: '提示',
          message: state.qrCodeMessage,
          theme: 'round-button',
          confirmButtonColor: '#ff8057'
        })
        return
      }
      if (!state.checked) {
        showToast('请阅读并同意协议')
        return
      }
      state.btnLoading = true
      try {
        const forms = state.forms
        await request.post('/api-school/open/schoolStaff/registerTeacher', {
          data: {
            ...forms,
            schoolId: state.id
          }
        })
        // state.submitStatus = true
        window.location.href =
          'https://mp.weixin.qq.com/s?__biz=MzkxMDMwOTI5Nw==&mid=2247485261&idx=1&sn=70c79a832a609bf9fae01c9e90fb4f69&chksm=c12c2593f65bac85d26362bca470f6abc2bfc087d9f4dcf87c00094420bdf5a3acb1b870199b#rd'
      } catch {
        //
      }
      state.btnLoading = false
    }

    const onSendCode = () => {
      // 发送验证码
      if (!checkPhone(state.forms.phone as any)) {
        return showToast('请输入正确的手机号码')
      }
      state.imgCodeStatus = true
    }
    const onCodeSend = () => {
      state.countDownStatus = false
      const clearTimer = setInterval(() => {
        state.countDownTime = state.countDownTime - 1
        if (state.countDownTime <= 0) {
          state.countDownTime = 120
          state.countDownStatus = true
          clearInterval(clearTimer)
        }
      }, 1000)
    }
    const onFinished = () => {
      state.countDownStatus = true
      // ;(this.$refs.countDownRef as any).reset()
    }

    onMounted(async () => {
      if (!state.id) {
        showToast('信息获取失败，请联系老师')
      }

      // 判断是否是微信，只能微信中打开
      if (!browser().weixin) {
        state.showPopup = true
        return
      } else {
        //授权
        const code = getUrlCode()
        if (!code) {
          const newUrl =
            window.location.origin +
            window.location.pathname +
            '#' +
            route.path +
            '?' +
            qs.stringify({
              ...route.query
            })
          getAppIdAndCode(newUrl)
          return
        } else {
          state.code = code
        }
      }

      // t: route.query.t, // 过期时间
      try {
        const res = await request.post('/api-school/open/schoolTeacherStudent/queryQrCodeStatus', {
          data: {
            schoolId: state.id,
            qrCodeEffectiveStartTime: state.t
              ? dayjs(Number(state.t)).format('YYYY-MM-DD HH:mm:ss')
              : null
          }
        })
        if (res.code === 999) {
          showDialog({
            title: '提示',
            message: res.message,
            theme: 'round-button',
            confirmButtonColor: '#FF8057'
          })

          state.qrCodeStatus = true
          state.qrCodeMessage = res.message
        }
      } catch (e: any) {
        //
        console.log(e)
      }

      try {
        const tempareas: any = []
        areas.forEach((item) => {
          const temp = {
            name: item.name,
            code: item.code,
            areas: [] as any
          }
          if (item.areas && item.areas.length > 0) {
            item.areas.forEach((child) => {
              temp.areas.push({
                name: child.name,
                code: child.code
              })
            })
          }
          tempareas.push(temp)
        })
        state.columns = tempareas || []

        const { data } = await request.post(
          '/api-school/open/orchestraSubjectConfig/pageByOrchestraId',
          {
            data: {
              orchestraId: state.id,
              page: 1,
              rows: 50
            }
          }
        )

        const rows = data.rows || []
        const tempSubjects: any = []
        rows.forEach((item) => {
          tempSubjects.push({
            text: item.name,
            value: item.subjectId
          })
        })
        state.columnSubject = tempSubjects
      } catch {
        showDialog({
          message: '信息获取失败，请联系老师',
          theme: 'round-button',
          confirmButtonColor: '#FF8057'
        })
      }
    })

    const getAppIdAndCode = async (url?: string) => {
      try {
        const { data } = await request.get('/api-school/open/paramConfig/wechatAppId')
        // 判断是否有微信appId
        if (data) {
          closeToast()
          goAuth(data, url)
        }
      } catch {
        //
      }
    }
    const goAuth = (wxAppId: string, urlString?: string) => {
      // 用户授权
      console.log(urlString || window.location.href, 'urlString || window.location.href')
      const urlNow = encodeURIComponent(urlString || window.location.href)
      console.log(urlNow, 'urlNow')
      const scope = 'snsapi_base' //snsapi_userinfo   //静默授权 用户无感知
      const appid = wxAppId || 'wx8654c671631cfade'
      const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${urlNow}&response_type=code&scope=${scope}&state=STATE&connect_redirect=1#wechat_redirect`
      window.location.replace(url)
    }

    const onPreview = (type: string) => {
      if (type === 'REGISTER') {
        window.open(
          window.location.origin + window.location.pathname + '#/preview-protocol',
          '_blank'
        )
      } else if (type === 'PRIVACY') {
        window.open(
          window.location.origin + window.location.pathname + '#/privacyProtocol',
          '_blank'
        )
      } else if (type === 'WITHDRAW') {
        //
        window.open(window.location.origin + window.location.pathname + '#/cashProtocol', '_blank')
      }
    }

    return () => (
      <div class={styles.register}>
        <div class={styles.title}>
          <p class={styles.tips}>
            <img src={schoolLogo} />
            <span>{state.name}</span>
          </p>
        </div>
        <Form validateFirst scrollToError onSubmit={onSubmit} ref="form" class={styles.form}>
          <CellGroup inset class={styles['cell-group']}>
            <Field
              label="真实姓名"
              v-model={state.forms.realName}
              rules={[{ required: true, message: '请填写真实姓名' }]}
              name="realName"
              placeholder="请填写真实姓名"
              maxlength="5"
            ></Field>

            <Field
              label="手机号码"
              v-model={state.forms.phone}
              rules={[
                { required: true, message: '请输入手机号码' },
                { pattern: state.pattern, message: '输入手机号码有误' }
              ]}
              name="phone"
              placeholder="请输入手机号码"
              maxlength={11}
              type="tel"
            ></Field>
            <div class={styles.phoneTips}>
              <Icon name="warning" size="16" />
              提示：手机号码将成为您管乐团管理端登录账号
            </div>

            <Field
              label="身份证号码"
              v-model={state.forms.idCardNo}
              rules={[
                { required: true, message: '请输入身份证号' },
                {
                  pattern:
                    /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
                  message: '请输入正确的身份证号'
                }
              ]}
              name="idCardNo"
              placeholder="请输入身份证号码"
            ></Field>

            <div class={[styles.fieldGroup, 'van-hairline--bottom']}>
              <Field
                label="身份证照片正面"
                v-model={state.forms.idcardFrontImg}
                readonly
                border={false}
                name="idcardFrontImg"
                rules={[{ required: true, message: '请上传身份证正面', trigger: 'onChange' }]}
                placeholder="请上传身份证正面"
              >
                {{
                  input: () => (
                    <OUpload
                      style={{ width: '100%' }}
                      tips="上传身份证正面"
                      bucket="gyt"
                      path="/user/"
                      v-model:modelValue={state.forms.idcardFrontImg}
                    />
                  )
                }}
              </Field>
              <Field
                label={'上传身份证反面'}
                labelClass={styles.fieldTitle}
                v-model={state.forms.idcardBackImg}
                readonly
                border={false}
                name="idcardBackImg"
                rules={[{ required: true, message: '请上传身份证反面', trigger: 'onChange' }]}
                placeholder="请上传身份证反面"
              >
                {{
                  input: () => (
                    <OUpload
                      style={{ width: '100%' }}
                      tips="上传身份证反面"
                      bucket="gyt"
                      path="/user/"
                      v-model:modelValue={state.forms.idcardBackImg}
                    />
                  )
                }}
              </Field>
            </div>

            <Field label="性别" name="gender" rules={[{ required: true, message: '请选择性别' }]}>
              {{
                input: () => (
                  <RadioGroup
                    checked-color="#FF8057"
                    v-model={state.forms.gender}
                    direction="horizontal"
                  >
                    <Tag
                      size="large"
                      type="primary"
                      color={!(state.forms.gender === 1) ? '#EAEAEA' : '#FF8057'}
                      textColor={!(state.forms.gender === 1) ? '#AAA' : '#FFF'}
                      class={styles.radioSection}
                      round
                    >
                      <Radio class={styles.radioItem} name={1}></Radio>男
                    </Tag>
                    <Tag
                      size="large"
                      type="primary"
                      color={!(state.forms.gender === 0) ? '#EAEAEA' : '#FF8057'}
                      textColor={!(state.forms.gender === 0) ? '#AAA' : '#FFF'}
                      class={styles.radioSection}
                      round
                    >
                      <Radio class={styles.radioItem} name={0}></Radio>女
                    </Tag>
                  </RadioGroup>
                )
              }}
            </Field>
            <Field
              label="验证码"
              v-model={state.forms.smsValidCode}
              name="smsValidCode"
              rules={[{ required: true, message: '请输入验证码', trigger: 'onChange' }]}
              placeholder="请输入验证码"
              maxlength={6}
              type="tel"
            >
              {{
                button: () =>
                  state.countDownStatus ? (
                    <Button type="primary" round size="small" color="#FF8057" onClick={onSendCode}>
                      发送验证码
                    </Button>
                  ) : (
                    <Button
                      type="default"
                      round
                      size="small"
                      disabled
                      style={{ minWidth: '60px' }}
                      onClick={onSendCode}
                    >
                      {state.countDownTime + 's'}
                    </Button>
                  )
              }}
            </Field>
          </CellGroup>

          <div class={styles.protocol}>
            <Checkbox
              v-model={state.checked}
              icon-size="16"
              style="margin-right: 6px"
              checked-color="#FF8057"
            ></Checkbox>
            <div>
              <span
                onClick={() => {
                  state.checked = !state.checked
                }}
              >
                请认真阅读并勾选
              </span>
              <span class={styles.c} onClick={() => onPreview('REGISTER')}>
                《管乐团用户注册协议》
              </span>
              、
              <span class={styles.c} onClick={() => onPreview('PRIVACY')}>
                《隐私协议》
              </span>
              、
              <span class={styles.c} onClick={() => onPreview('WITHDRAW')}>
                《共享经济平台注册经营者协议》
              </span>
            </div>
          </div>

          <Button
            size="large"
            block
            round
            class={styles['btn-submit']}
            color="#FF8057"
            loading={state.btnLoading}
            native-type="submit"
          >
            完成
          </Button>
        </Form>

        <Popup v-model:show={state.submitStatus} round style="width: 75%" closeOnClickOverlay>
          <div class={styles.stautsS}>
            <img src={topBanner1} class={styles['submit-img']} />
            <div class={styles['submit-container']}>
              <p class={styles['submit-title']}>恭喜您已成功登记为</p>
              <p class={styles['submit-o']}>
                {state.name} <br />
                <span>【管理老师】</span>
              </p>
              <p class={styles['submit-tips']}>请下载管乐团管理端APP</p>
              <Button
                type="primary"
                color="#FF8057"
                block
                round
                onClick={() => {
                  state.submitStatus = false
                  window.location.href =
                    window.location.origin + '/orchestra-student/#/download?type=manage'
                }}
              >
                立即下载
              </Button>
            </div>
          </div>
        </Popup>

        {state.imgCodeStatus ? (
          <ImgCode
            v-model:value={state.imgCodeStatus}
            phone={state.forms.phone as any}
            type="REGISTER"
            onClose={() => {
              state.imgCodeStatus = false
            }}
            onSendCode={onCodeSend}
          />
        ) : null}

        <Popup
          v-model:show={state.showPopup}
          round
          style={{ width: '88%' }}
          closeOnClickOverlay={false}
          class={styles.wxPopupDialog}
        >
          <div class={styles.popupContainer}>
            <p class={styles.title1}>温馨提示</p>
            <p class={styles.popupTips}>请使用微信打开</p>
          </div>
        </Popup>
      </div>
    )
  }
})
