import { computed, defineComponent, nextTick, reactive, ref } from 'vue';
import styles from './index.module.less';
import infoTitle from '../images/info-title.png';
import { Button, CountDown, Field, Form, Picker, Popup, showToast } from 'vant';
import MProtocol from '@/components/m-protocol';
import MImgCode from '@/components/m-img-code';
import { checkPhone } from '@/helpers/utils';
import request from '@/helpers/request';
import { useStudentRegisterStore } from '@/store/modules/student-register-store';
import { setLoginInit, state } from '@/state';
const studentRegisterStore = useStudentRegisterStore();
const classList: any = [];
for (let i = 1; i <= 40; i++) {
  classList.push({ text: i + '班', value: i });
}

export default defineComponent({
  name: 'register-modal',
  props: {
    schoolId: {
      type: String,
      default: ''
    },
    gradeYear: {
      type: String,
      default: ''
    },
    schoolType: {
      type: String,
      default: ''
    }
  },
  emits: ['close', 'submit'],
  setup(props, { emit }) {
    const countDownRef = ref();
    const gradeList = computed(() => {
      let tempList: any = [];
      const five = [
        { text: '一年级', value: 1 },
        { text: '二年级', value: 2 },
        { text: '三年级', value: 3 },
        { text: '四年级', value: 4 },
        { text: '五年级', value: 5 }
      ];
      const one = [{ text: '六年级', value: 6 }];
      const three = [
        { text: '七年级', value: 7 },
        { text: '八年级', value: 8 },
        { text: '九年级', value: 9 }
      ];
      if (props.gradeYear === 'FIVE_YEAR_SYSTEM') {
        tempList.push([...five]);
      } else if (props.gradeYear === 'SIX_YEAR_SYSTEM') {
        tempList.push([...five, ...one]);
      } else if (props.gradeYear === 'THREE_YEAR_SYSTEM') {
        tempList.push([...three]);
      } else if (props.gradeYear === 'FORE_YEAR_SYSTEM') {
        tempList.push([...one, ...three]);
      } else {
        tempList.push([...five, ...one, ...three]);
      }
      return tempList;
    });
    const forms = reactive({
      countDownStatus: true,
      countDownTime: 1000 * 120, // 倒计时时间
      modelValue: false, // 是否选中协议
      imgCodeStatus: false,
      gradeNumText: '',
      currentClassText: '',
      gradeStatus: false,
      classStatus: false,
      loading: false
    });
    const studentInfo = reactive({
      autoRegister: true,
      client_id: 'cooleshow-student',
      client_secret: 'cooleshow-student',
      extra: {
        nickname: '',
        currentGradeNum: '',
        currentClass: ''
      },
      grant_type: 'password',
      loginType: 'SMS',
      password: '',
      username: ''
    });

    const onCodeSend = () => {
      forms.countDownStatus = false;
      nextTick(() => {
        countDownRef.value.start();
      });
    };

    const onSendCode = () => {
      // 发送验证码
      if (!checkPhone(studentInfo.username)) {
        return showToast('请输入正确的手机号码');
      }
      forms.imgCodeStatus = true;
    };

    const validatePhone = computed(() => {
      return checkPhone(studentInfo.username) ? true : false;
    });

    const onFinished = () => {
      forms.countDownStatus = true;
      countDownRef.value.reset();
    };

    const onSubmit = async () => {
      try {
        if (checkForm()) return;
        forms.loading = true;
        const { extra, ...res } = studentInfo;
        const { data } = await request.post('/edu-app/userlogin', {
          hideLoading: false,
          requestType: 'form',
          data: {
            ...res,
            extra: JSON.stringify({ ...extra, schoolId: props.schoolId })
          }
        });

        studentRegisterStore.setToken(
          data.token_type + ' ' + data.access_token
        );
        setLoginInit();

        emit('close');
        emit('submit');
      } catch {
      } finally {
        forms.loading = false;
      }
    };

    const checkForm = () => {
      if (!checkPhone(studentInfo.username)) {
        showToast('请输入正确的手机号码');
        return true;
      } else if (!studentInfo.password) {
        showToast('请输入验证码');
        return true;
      } else if (!studentInfo.extra.nickname) {
        showToast('请输入学生姓名');
        return true;
      } else if (!studentInfo.extra.currentGradeNum) {
        showToast('请选择所在年级');
        return true;
      } else if (!studentInfo.extra.currentClass) {
        showToast('请选择所在班级');
        return true;
      }
      return false;
    };

    return () => (
      <div class={styles.registerModal}>
        <img src={infoTitle} class={styles.infoTitle} />

        <Form labelAlign="top" class={styles.registerForm}>
          <Field
            clearable
            label="联系方式（直接监护人）"
            placeholder="请输入手机号码"
            type="tel"
            autocomplete="off"
            v-model={studentInfo.username}
            maxlength={11}>
            {{
              label: () => (
                <div>
                  联系方式（直接监护人）
                  <p class={styles.tips}>
                    手机号是数字化器乐学练工具的唯一登录账户
                  </p>
                </div>
              )
            }}
          </Field>
          <Field
            center
            clearable
            label="验证码"
            placeholder="请输入验证码"
            autocomplete="off"
            type="number"
            v-model={studentInfo.password}
            maxlength={6}>
            {{
              button: () =>
                forms.countDownStatus ? (
                  <span
                    class={[
                      styles.codeText,
                      !validatePhone.value ? styles.codeTextDisabled : ''
                    ]}
                    onClick={onSendCode}>
                    获取验证码
                  </span>
                ) : (
                  <CountDown
                    ref={(el: any) => (countDownRef.value = el)}
                    auto-start={false}
                    time={forms.countDownTime}
                    onFinish={onFinished}
                    format="ss秒"
                  />
                )
            }}
          </Field>
          <Field
            clearable
            label="学生姓名"
            placeholder="请输入学生姓名"
            autocomplete="off"
            v-model={studentInfo.extra.nickname}
          />
          <Field
            clearable
            label="所在年级"
            placeholder="请选择年级"
            isLink
            readonly
            clickable={false}
            modelValue={forms.gradeNumText}
            onClick={() => (forms.gradeStatus = true)}
          />
          <Field
            clearable
            label="所在班级"
            placeholder="请选择班级"
            isLink
            readonly
            clickable={false}
            modelValue={forms.currentClassText}
            onClick={() => (forms.classStatus = true)}
          />
        </Form>
        <MProtocol
          center
          v-model:modelValue={forms.modelValue}
          prototcolType="REGISTER"
        />

        <Button
          type="primary"
          class={styles.submitBtn}
          color="linear-gradient(121deg, #FFD892 0%, #FFCB75 100%)"
          block
          onClick={onSubmit}
          disabled={forms.loading}
          loading={forms.loading}>
          确认
        </Button>

        {forms.imgCodeStatus ? (
          <MImgCode
            v-model:value={forms.imgCodeStatus}
            phone={studentInfo.username}
            onClose={() => {
              forms.imgCodeStatus = false;
            }}
            onSendCode={onCodeSend}
          />
        ) : null}

        {/* 年级 */}
        <Popup
          v-model:show={forms.gradeStatus}
          position="bottom"
          round
          safeAreaInsetBottom
          lazyRender={false}
          class={'popupBottomSearch'}>
          <Picker
            showToolbar
            columns={gradeList.value as any}
            onCancel={() => (forms.gradeStatus = false)}
            onConfirm={(val: any) => {
              const selectedOption = val.selectedOptions[0];
              studentInfo.extra.currentGradeNum = selectedOption.value;
              forms.gradeNumText = selectedOption.text;
              forms.gradeStatus = false;
            }}
          />
        </Popup>
        {/* 班级 */}
        <Popup
          v-model:show={forms.classStatus}
          position="bottom"
          round
          class={'popupBottomSearch'}>
          <Picker
            showToolbar
            columns={classList}
            onCancel={() => (forms.classStatus = false)}
            onConfirm={(val: any) => {
              const selectedOption = val.selectedOptions[0];
              studentInfo.extra.currentClass = selectedOption.value;
              forms.currentClassText = selectedOption.text;
              forms.classStatus = false;
            }}
          />
        </Popup>
      </div>
    );
  }
});
