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'

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,
      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: ''
      },
      btnLoading: false,
      checkPhone: false,
      checked: true,
      columnSubject: [] as any,
      countDownStatus: true, // 是否发送验证码
      countDownTime: 120, // 倒计时时间
      // countDownRef: null as any, // 倒计时实例
      imgCodeStatus: false
    })

    const onSubmit = async () => {
      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
      } 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('信息获取失败，请联系老师')
      }
      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: '#64A9FF'
        })
      }
    })

    const onPreview = () => {
      window.open(window.location.origin + '/#/preview-protocol', '_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
              required
              label="真实姓名"
              v-model={state.forms.realName}
              rules={[{ required: true, message: '请填写真实姓名' }]}
              name="realName"
              placeholder="请填写真实姓名"
              maxlength="50"
            ></Field>

            <Field
              required
              label="手机号码"
              v-model={state.forms.phone}
              rules={[
                { required: true, message: '请输入手机号码' },
                { pattern: state.pattern, message: '输入手机号码有误' }
              ]}
              name="phone"
              placeholder="请输入手机号码"
              maxlength={11}
              type="tel"
            ></Field>

            <Field
              required
              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>

            <Field
              required
              label="性别"
              name="gender"
              rules={[{ required: true, message: '请选择性别' }]}
            >
              {{
                input: () => (
                  <RadioGroup
                    checked-color="#64A9FF"
                    v-model={state.forms.gender}
                    direction="horizontal"
                  >
                    <Tag
                      size="large"
                      type="primary"
                      plain={!(state.forms.gender === 1)}
                      color="#64A9FF"
                      class={styles.radioSection}
                      round
                    >
                      <Radio class={styles.radioItem} name={1}></Radio>男
                    </Tag>
                    <Tag
                      size="large"
                      type="primary"
                      plain={!(state.forms.gender === 0)}
                      color="#64A9FF"
                      class={styles.radioSection}
                      round
                    >
                      <Radio class={styles.radioItem} name={0}></Radio>女
                    </Tag>
                  </RadioGroup>
                )
              }}
            </Field>
            <Field
              required
              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="#64A9FF" onClick={onSendCode}>
                      发送验证码
                    </Button>
                  ) : (
                    <Button
                      type="default"
                      round
                      size="small"
                      disabled
                      style={{ minWidth: '60px' }}
                      onClick={onSendCode}
                    >
                      {state.countDownTime + 's'}
                    </Button>
                  )
              }}
            </Field>
            <div class={styles.phoneTips}>
              <Icon name="warning" size="16" />
              提示：手机号码将成为您管乐团管理端登录账号
            </div>
          </CellGroup>

          <div class={styles.protocol}>
            <Checkbox
              v-model={state.checked}
              icon-size="16"
              style="margin-right: 6px"
              checked-color="#64A9FF"
            ></Checkbox>
            <span
              onClick={() => {
                state.checked = !state.checked
              }}
            >
              请认真阅读并勾选
            </span>
            <span class={styles.c} onClick={onPreview}>
              《乐团管理老师注册协议》
            </span>
          </div>

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

        <Popup v-model:show={state.submitStatus} round style="width: 75%" closeOnClickOverlay>
          <div class={styles.stautsS}>
            {/* <img
              class={styles['icon-close']}
              src={iconClose}
              onClick={() => {
                state.submitStatus = false
                window.location.href =
                  window.location.origin + '/orchestra-student/#/download?type=manage'
              }}
            /> */}
            <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="#64A9FF"
                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}
            onClose={() => {
              state.imgCodeStatus = false
            }}
            onSendCode={onCodeSend}
          />
        ) : null}
      </div>
    )
  }
})
