import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref
} from 'vue';
import styles from './index.module.less';
// import infoTitle from '../images/info-title.png';
import {
  Button,
  CountDown,
  Field,
  Form,
  Picker,
  Popup,
  Radio,
  RadioGroup,
  Tag,
  showToast
} from 'vant';
import OWxTip from '@/components/m-wx-tip';
import MProtocol from '@/components/m-protocol';
import MImgCode from '@/components/m-img-code';
import { browser, checkPhone } from '@/helpers/utils';
import request from '@/helpers/request';
import { useStudentRegisterStore } from '@/store/modules/student-register-store';
import { setLoginInit, state } from '@/state';
// import iconGift from '../images/icon-gift.png';
import vipGiftIcon from '../images/vip-gift-icon.png';
import { useRoute, useRouter } from 'vue-router';
import MSticky from '@/components/m-sticky';
import MMessageTip from '@/components/m-message-tip';
import SelectStudent from '../modal/select-student';
import dayjs from 'dayjs';
const classList: any = [];
for (let i = 1; i <= 40; i++) {
  classList.push({ text: i + '班', value: i });
}

export default defineComponent({
  name: 'register-modal',
  emits: ['close', 'submit'],
  setup() {
    const route = useRoute();
    const router = useRouter();
    const studentRegisterStore = useStudentRegisterStore();
    // 初始化学校编号
    studentRegisterStore.setShoolId(route.query.sId as any);
    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 (forms.gradeYear === 'FIVE_YEAR_SYSTEM') {
        tempList.push([...five]);
      } else if (forms.gradeYear === 'SIX_YEAR_SYSTEM') {
        tempList.push([...five, ...one]);
      } else if (forms.gradeYear === 'THREE_YEAR_SYSTEM') {
        tempList.push([...three]);
      } else if (forms.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,
      schoolId: route.query.sId as any,
      details: {} as any,
      multi_user_limit: 1, // 限制注册学生数量
      showSelectStudent: false, // 选择学生
      studentList: [], // 手机号关联学生列表
      studentItem: {} as any, // 选择的学生
      isRegister: 'create' as 'create' | 'update' | '', // 是否注册学生
      isTipRegister: false, // 是否显示名字不一致 - 默认显示
      isChangeSchool: false, // 是否切换学校
      gradeYear: null,
      schoolType: null,
      giftVipDay: null,
      showTips: false,
      showButton: false,
      showMessage: '请使用微信打开',
      showOtherSchool: false,
      showOtherMessage: '',
      gradePopupShow: false,
      gradePopupIndex: [] as any, // 年级下拉索引
      classPopupShow: false,
      classPopupIndex: [] as any // 班级下拉索引
    });
    const otherParams = reactive({
      showOtherSchool: false,
      showCloseButton: true, // 是否显示关闭按钮
      showOtherMessage: '',
      /**  limit 超限制，change 更换学生，nickname 名称不一致  */
      otherType: '' as 'limit' | 'change' | 'nickname',
      showCancelButton: true,
      cancelButtonColor: '',
      cancelButtonText: '取消',
      showConfirmButton: true,
      confirmButtonColor: '',
      confirmButtonText: '确定',
      messageAlign: 'left' as 'center' | 'left' | 'right'
    });
    const studentInfo = reactive({
      autoRegister: true,
      multiUser: true, // 是否为多用户
      client_id: 'cooleshow-student',
      client_secret: 'cooleshow-student',
      extra: {
        nickname: '',
        currentGradeNum: '',
        currentClass: '',
        gender: 1,
        registerType: '', // 报名类型
        giftVipDay: 0 // 赠送会员天数
      },
      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() || checkSubmit()) return;
        forms.loading = true;
        const { extra, loginType, autoRegister, password, multiUser, ...res } =
          studentInfo;
        let tLoginType = loginType,
          tAutoRegister = autoRegister,
          tPassword = password,
          tMultiUser = multiUser;
        if (forms.isRegister === 'update') {
          tLoginType = 'TOKEN';
          tAutoRegister = false;
          tPassword = forms.studentItem.token;
          tMultiUser = false;
        }
        // const { extra, ...res } = studentInfo;
        const result = await request.post('/edu-app/userlogin', {
          hideLoading: false,
          requestType: 'form',
          data: {
            loginType: tLoginType,
            autoRegister: tAutoRegister,
            password: tPassword,
            multiUser: tMultiUser,
            ...res,
            extra: JSON.stringify({
              ...extra,
              schoolId: forms.schoolId
            })
          }
        });
        if (result.code === 5436) {
          forms.showTips = true;
          forms.showMessage = '二维码已经失效，详情请咨询学校老师';
          forms.showButton = false;
        } else if (result.code === 5435) {
          forms.showTips = true;
          forms.showMessage = '报名信息更新，请刷新后重新提交';
          forms.showButton = true;
        } else {
          studentRegisterStore.setToken(
            result.data.token_type + ' ' + result.data.access_token
          );
          setLoginInit();

          const { extra, username } = studentInfo;
          const registerResult = await request.post(
            '/edu-app/student/register',
            {
              data: {
                schoolId: forms.schoolId,
                clientType: 'STUDENT',
                schoolVerify: true,
                ...extra,
                mobile: username,
                newRegUser: forms.isRegister === 'create' ? true : false
              }
            }
          );

          if (registerResult.code !== 200) {
            if (registerResult.code === 5436) {
              forms.showTips = true;
              forms.showMessage = '二维码已经失效，详情请咨询学校老师';
              forms.showButton = false;
            } else if (registerResult.code === 5435) {
              forms.showTips = true;
              forms.showMessage = registerResult.message;
              forms.showButton = true;
            }
            return;
          }

          setTimeout(() => {
            showToast('报名成功');
            // router.push('/download');
          }, 100);
          setTimeout(() => {
            if (browser().weixin) {
              // 关闭微信
              (window as any).WeixinJSBridge.call('closeWindow');
            }
          }, 1000);
        }
      } catch {
        // 重置信息 - 如果是新建则不提示
        changeTipStatus(forms.isRegister === 'create' ? false : true, false);
      } 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 (![0, 1].includes(studentInfo.extra.gender)) {
        showToast('请选择性别');
        return true;
      } else if (!studentInfo.extra.currentGradeNum) {
        showToast('请选择所在年级');
        return true;
      } else if (!studentInfo.extra.currentClass) {
        showToast('请选择所在班级');
        return true;
      }
      return false;
    };

    const getUserInfos = async () => {
      if (
        studentInfo.password.length !== 6 ||
        !checkPhone(studentInfo.username)
      ) {
        return;
      }
      try {
        const { data } = await request.get(
          `/edu-app/open/student/studentInfo?mobile=${studentInfo.username}&code=${studentInfo.password}&type=REGISTER`
        );
        forms.studentList = data || [];

        if (forms.studentList.length > 0) {
          const firstStudent: any = forms.studentList[0];
          forms.studentItem = firstStudent;
          studentInfo.extra.nickname = firstStudent.nickname;
          const tempGrade: any = gradeList.value[0] || [];
          tempGrade?.forEach((i: any) => {
            if (i.value === firstStudent.currentGradeNum) {
              forms.gradeNumText = i.text;
              studentInfo.extra.currentGradeNum = firstStudent.currentGradeNum;
            }
          });
          classList.forEach((i: any) => {
            if (i.value === firstStudent.currentClass) {
              forms.currentClassText = i.text;
              studentInfo.extra.currentClass = firstStudent.currentClass;
            }
          });
          studentInfo.extra.gender = firstStudent.gender;

          forms.isRegister = 'update';
          changeTipStatus(true, false);
        } else {
          forms.isRegister = 'create';
          changeTipStatus(false, false);
          forms.studentItem = [];
        }
      } catch {
        //
      }
    };

    // 格式化提示状态
    const changeTipStatus = (register: boolean, school: boolean) => {
      forms.isTipRegister = register;
      forms.isChangeSchool = school;
    };

    //
    const checkSubmit = () => {
      const { extra } = studentInfo;
      if (
        forms.studentItem.nickname !== extra.nickname &&
        forms.isTipRegister
      ) {
        otherParams.showOtherMessage =
          '学生姓名与上次提交信息不一致，请确认修改学生信息或创建新的学生账号';
        otherParams.showOtherSchool = true;
        otherParams.showCancelButton = true;
        otherParams.showCloseButton = true;
        otherParams.cancelButtonColor =
          'linear-gradient( 224deg, #3FE1E6 0%, #00CDD4 100%)';
        otherParams.cancelButtonText = '新建学生';
        otherParams.confirmButtonColor =
          'linear-gradient( 305deg, #40C8FF 0%, #3192FF 100%)';
        otherParams.confirmButtonText = '修改信息';
        otherParams.otherType = 'nickname';
        otherParams.messageAlign = 'left';
        return true;
      }

      // 判断新建学员是否上限了
      if (
        forms.isRegister === 'create' &&
        forms.studentList.length >= forms.multi_user_limit
      ) {
        otherParams.showOtherMessage = `同一手机号最多创建${forms.multi_user_limit}个学生`;
        otherParams.showOtherSchool = true;
        otherParams.showCancelButton = false;
        otherParams.showCloseButton = true;
        otherParams.confirmButtonColor =
          'linear-gradient( 305deg, #40C8FF 0%, #3192FF 100%)';
        otherParams.confirmButtonText = '我知道了';
        otherParams.otherType = 'limit';
        otherParams.messageAlign = 'center';
        return true;
      }

      // 判断是否为同一个学校
      if (
        forms.studentItem.schoolId &&
        forms.studentItem.schoolId !== forms.details.id &&
        !forms.isChangeSchool &&
        forms.isRegister === 'update'
      ) {
        otherParams.showOtherMessage = `您已绑定<span style="color: #2B85FF">【${
          forms.studentItem?.schoolName || ''
        }】</span>，提交后将更换到<span style="color: #2B85FF">【${
          forms.details.name || ''
        }】</span>，是否确认提交？`;
        otherParams.showOtherSchool = true;
        otherParams.showCancelButton = true;
        otherParams.showCloseButton = false;
        otherParams.cancelButtonColor = '';
        otherParams.cancelButtonText = '取消';
        otherParams.confirmButtonColor = '';
        otherParams.confirmButtonText = '确定';
        otherParams.otherType = 'change';
        otherParams.messageAlign = 'left';
        return true;
      }
      return false;
    };

    const getRegisterGoods = async () => {
      try {
        const { data } = await request.get('/edu-app/open/school/detail', {
          params: {
            id: forms.schoolId
          },
          noAuthorization: true // 是否请求接口的时候添加toekn
        });

        forms.giftVipDay = data.giftVipDay;
        forms.schoolType = data.schoolType;
        forms.gradeYear = data.gradeYear;
        studentInfo.extra.giftVipDay = data.giftVipDay;
        studentInfo.extra.registerType = data.registerType;
        forms.details = data;
        if (browser().weixin) {
          if (data.registerType !== 'GIFT_VIP_DAY' || data.status === 0) {
            forms.showTips = true;
            forms.showMessage = '二维码已经失效，详情请咨询学校老师';
            forms.showButton = false;
          }
        } else {
          forms.showTips = true;
        }
      } catch {}
    };

    onMounted(async () => {
      try {
        // 获取支付类型
        let expireDay = null;
        const { data } = await request.get(
          '/edu-app/open/paramConfig/queryByParamNameList',
          {
            requestType: 'form',
            params: {
              paramNames: 'multi_user_limit,qr_code_expire_time'
            }
          }
        );
        if (data && Array.isArray(data)) {
          data.forEach((item: any) => {
            if (item.paramName === 'multi_user_limit') {
              forms.multi_user_limit = item.paramValue
                ? Number(item.paramValue)
                : 1;
            } else if (item.paramName === 'qr_code_expire_time') {
              expireDay = item.paramValue ? Number(item.paramValue) : null;
            }
          });
        }

        const createT = route.query.t;
        if (createT && expireDay !== null) {
          if (dayjs(Number(createT)).add(expireDay, 'day').isBefore(dayjs())) {
            forms.showTips = true;
            forms.showMessage = '二维码已经失效，详情请咨询学校老师';
            forms.showButton = false;
          }
        }

        await getRegisterGoods();
      } catch {}
    });

    /** 手机号变更时清空验证码信息，用户信息 */
    const phoneChangeEmptyInfo = () => {
      studentInfo.password = '';
      studentInfo.extra.nickname = '';
      studentInfo.extra.currentGradeNum = '';
      studentInfo.extra.currentClass = '';
      studentInfo.extra.gender = 1;
      forms.currentClassText = '';
      forms.gradeNumText = '';
      forms.studentList = []; // 手机号关联学生列表
      forms.studentItem = {}; // 选择的学生
      forms.isRegister = 'create'; // 是否注册学生
      forms.isTipRegister = false; // 是否显示名字不一致 - 默认显示
      forms.isChangeSchool = false; // 是否切换学校
    };
    return () => (
      <div class={styles.registerModal}>
        {/* {forms.giftVipDay ? (
          <div class={styles.memberNumer}>
            <img src={iconGift} class={styles.iconGift} />

            <p>
              现在报名立即赠送乐器AI学练工具有效期{' '}
              <span>{forms.giftVipDay}</span> 天
            </p>
          </div>
        ) : (
          ''
        )} */}
        <div class={styles.studentRegisterContainer}>
          <div
            class={[
              styles.studentSection,
              styles.studentSectionForm,
              styles.noSendDay
            ]}>
            <div class={styles.title3}></div>
            <Form labelAlign="left" class={styles.registerForm}>
              <Field
                clearable={false}
                label="联系方式（直接监护人）"
                placeholder="请输入手机号码"
                type="tel"
                required
                autocomplete="off"
                inputAlign="right"
                class={styles.username}
                v-model={studentInfo.username}
                border={false}
                maxlength={11}
                onUpdate:modelValue={() => {
                  phoneChangeEmptyInfo();
                }}>
                {{
                  label: () => (
                    <div>
                      联系方式
                      <p class={styles.tips}>（直接监护人）</p>
                    </div>
                  )
                }}
              </Field>
              <div class={['van-hairline--bottom', styles.fieldTipsGroup]}>
                <div class={[styles.fieldTips]}>
                  手机号是音乐数字课堂的唯一登录账户
                </div>
              </div>

              <Field
                center
                clearable={false}
                required
                inputAlign="right"
                label="验证码"
                placeholder="请输入验证码"
                autocomplete="off"
                type="number"
                v-model={studentInfo.password}
                maxlength={6}
                onUpdate:modelValue={(val: any) => {
                  getUserInfos();
                }}>
                {{
                  button: () =>
                    forms.countDownStatus ? (
                      <span
                        class={[
                          styles.codeText,
                          !validatePhone.value ? styles.codeTextDisabled : ''
                        ]}
                        onClick={onSendCode}>
                        获取验证码
                      </span>
                    ) : (
                      <CountDown
                        ref={(el: any) => (countDownRef.value = el)}
                        auto-start={false}
                        class={styles.countDown}
                        time={forms.countDownTime}
                        onFinish={onFinished}
                        format="ss秒后重试"
                      />
                    )
                }}
              </Field>
            </Form>
          </div>

          <div
            class={[
              styles.studentSection,
              styles.studentSectionForm,
              styles.noSendDay
            ]}>
            <div class={styles.title1}></div>
            <Form labelAlign="left" class={styles.registerForm}>
              {/* 大于等于2，则可以切换学生 */}
              {forms.studentList.length > 1 && (
                <div
                  class={[
                    styles.selectStudentGroup,
                    forms.showSelectStudent && styles.selectStudentGroupChecked
                  ]}
                  onClick={() => (forms.showSelectStudent = true)}>
                  <i
                    class={[
                      styles.studentIcon,
                      !forms.studentItem.userId && styles.studentIconAdd
                    ]}></i>
                  <span>
                    {forms.studentItem.userId
                      ? forms.studentItem.nickname
                      : '新增学生'}
                  </span>
                </div>
              )}
              <Field
                clearable={false}
                label="学生姓名"
                placeholder="请输入学生姓名"
                autocomplete="off"
                maxlength={14}
                v-model={studentInfo.extra.nickname}
                required
                input-align="right"
              />
              <Field
                clearable={false}
                label="学生性别"
                placeholder="请选择性别"
                autocomplete="off"
                required
                input-align="right">
                {{
                  input: () => (
                    <RadioGroup
                      checked-color="#ffcb75"
                      v-model={studentInfo.extra.gender}
                      direction="horizontal">
                      <Tag
                        size="large"
                        type="primary"
                        color={
                          !(studentInfo.extra.gender === 1)
                            ? '#F5F6FA'
                            : 'linear-gradient( 135deg, #31C7FF 0%, #007AFE 100%)'
                        }
                        textColor={
                          !(studentInfo.extra.gender === 1) ? '#626264' : '#fff'
                        }
                        class={styles.radioSection}
                        round>
                        <Radio class={styles.radioItem} name={1}></Radio>男
                      </Tag>
                      <Tag
                        size="large"
                        type="primary"
                        color={
                          !(studentInfo.extra.gender === 0)
                            ? '#F5F6FA'
                            : 'linear-gradient( 135deg, #31C7FF 0%, #007AFE 100%)'
                        }
                        textColor={
                          !(studentInfo.extra.gender === 0) ? '#626264' : '#fff'
                        }
                        class={styles.radioSection}
                        round>
                        <Radio class={styles.radioItem} name={0}></Radio>女
                      </Tag>
                    </RadioGroup>
                  )
                }}
              </Field>
              <Field
                clearable={false}
                label="所在年级"
                placeholder="请选择年级"
                isLink
                readonly
                clickable={false}
                modelValue={forms.gradeNumText}
                // onClick={() => (forms.gradeStatus = true)}
                required
                input-align="right"
                onClick={() => {
                  forms.gradePopupIndex = [studentInfo.extra.currentGradeNum];
                  forms.gradeStatus = true;
                }}
              />
              <Field
                clearable={false}
                label="所在班级"
                placeholder="请选择班级"
                isLink
                readonly
                clickable={false}
                modelValue={forms.currentClassText}
                // onClick={() => (forms.classStatus = true)}
                onClick={() => {
                  forms.classPopupIndex = [studentInfo.extra.currentClass];
                  forms.classStatus = true;
                }}
                required
                input-align="right"
              />
              {studentInfo.extra.registerType === 'GIFT_VIP_DAY' &&
              forms.giftVipDay &&
              Number(forms.giftVipDay) > 0 ? (
                <div class={styles.giftTips}>
                  <img src={vipGiftIcon} />
                  <span>
                    现在报名立即赠送乐器AI学练工具有效期
                    <i>{forms.giftVipDay}</i>天
                  </span>
                </div>
              ) : null}
            </Form>
          </div>
        </div>
        {/* <MProtocol
          center
          v-model:modelValue={forms.modelValue}
          prototcolType="REGISTER"
        /> */}

        <MSticky position="bottom">
          <div class={styles.paymentContainer}>
            <div class={styles.traditionBtn}>
              <Button
                type="primary"
                class={styles.submitBtn}
                color="linear-gradient( 135deg, #31C7FF 0%, #007AFE 100%)"
                round
                onClick={() => onSubmit()}
                disabled={forms.loading}
                loading={forms.loading}>
                提交注册
              </Button>
            </div>
          </div>
        </MSticky>

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

        {/* 年级 */}
        <Popup
          v-model:show={forms.gradeStatus}
          position="bottom"
          round
          safeAreaInsetBottom
          lazyRender={false}
          class={'popupBottomSearch'}
          onOpen={() => {
            forms.gradePopupShow = true;
          }}
          onClosed={() => {
            forms.gradePopupShow = false;
          }}>
          {forms.gradePopupShow && (
            <Picker
              showToolbar
              v-model={forms.gradePopupIndex}
              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'}
          onOpen={() => {
            forms.classPopupShow = true;
          }}
          onClosed={() => {
            forms.classPopupShow = false;
          }}>
          {forms.classPopupShow && (
            <Picker
              showToolbar
              v-model={forms.classPopupIndex}
              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>
        {/* 是否在微信中打开 */}
        <OWxTip
          v-model:show={forms.showTips}
          message={forms.showMessage}
          showButton={forms.showButton}
          buttonText="刷新"
          onConfirm={async () => {
            forms.showTips = false;
            await getRegisterGoods();

            studentInfo.password = '';

            window.scrollTo({
              top: 0,
              behavior: 'smooth'
            });
          }}
        />

        <MMessageTip
          show={otherParams.showOtherSchool}
          // showCloseButton={otherParams.showCloseButton}
          messageAlign={otherParams.messageAlign}
          message={otherParams.showOtherMessage}
          showCancelButton={otherParams.showCancelButton}
          cancelButtonColor={otherParams.cancelButtonColor}
          cancelButtonText={otherParams.cancelButtonText}
          confirmButtonColor={otherParams.confirmButtonColor}
          confirmButtonText={otherParams.confirmButtonText}
          onClose={() => (otherParams.showOtherSchool = false)}
          onCancel={() => {
            otherParams.showOtherSchool = false;
            if (otherParams.otherType === 'nickname') {
              forms.isRegister = 'create'; // 新建
              changeTipStatus(false, false);
              onSubmit();
            }
          }}
          onConfirm={() => {
            otherParams.showOtherSchool = false;
            // 名字
            if (otherParams.otherType === 'nickname') {
              forms.isRegister = 'update'; // 修改
              changeTipStatus(false, false);
              // 直接注册
              onSubmit();
            } else if (otherParams.otherType === 'change') {
              // 学校更换
              forms.isChangeSchool = true;
              // 直接注册
              onSubmit();
            } else if (otherParams.otherType === 'limit') {
              // 人数超限制
              changeTipStatus(
                forms.isRegister === 'create' && !forms.studentItem.userId
                  ? false
                  : true,
                false
              );
            }
          }}
        />

        <Popup
          v-model:show={forms.showSelectStudent}
          round
          position="bottom"
          safeAreaInsetBottom
          closeable
          class={styles.selectStudentPopup}>
          <SelectStudent
            studentItem={forms.studentItem}
            list={forms.studentList}
            onClose={() => (forms.showSelectStudent = false)}
            onConfirm={(val: any) => {
              if (val.userId) {
                forms.studentItem = val;
                const firstStudent = val;
                studentInfo.extra.nickname = firstStudent.nickname;
                const tempGrade: any = gradeList.value[0] || [];

                studentInfo.extra.currentGradeNum = '';
                forms.gradeNumText = '';

                tempGrade?.forEach((i: any) => {
                  if (i.value === firstStudent.currentGradeNum) {
                    // forms.instrumentCode = i.instrumentCode;
                    forms.gradeNumText = i.text;
                    studentInfo.extra.currentGradeNum =
                      firstStudent.currentGradeNum;
                    // if (forms.schoolInstrumentSetType === 'CLASS') {
                    //   forms.classList = i.classList;
                    // }
                  }
                });

                forms.currentClassText = '';
                studentInfo.extra.currentClass = '';
                classList.forEach((i: any) => {
                  if (i.value === firstStudent.currentClass) {
                    forms.currentClassText = i.text;
                    studentInfo.extra.currentClass = firstStudent.currentClass;
                  }
                });
                studentInfo.extra.gender = firstStudent.gender;
                forms.isRegister = 'update';
                changeTipStatus(true, false);
                forms.showSelectStudent = false;
              } else {
                // 判断新建学员是否上限了
                if (forms.studentList.length >= forms.multi_user_limit) {
                  otherParams.showOtherMessage = `同一手机号最多创建${forms.multi_user_limit}个学生`;
                  otherParams.showOtherSchool = true;
                  otherParams.showCancelButton = false;
                  otherParams.showCloseButton = true;
                  otherParams.confirmButtonColor =
                    'linear-gradient( 305deg, #40C8FF 0%, #3192FF 100%)';
                  otherParams.confirmButtonText = '我知道了';
                  otherParams.otherType = 'limit';
                  otherParams.messageAlign = 'center';
                  return true;
                } else {
                  forms.studentItem = val;
                  forms.isRegister = 'create';
                  changeTipStatus(false, false);
                  studentInfo.extra.nickname = '';
                  studentInfo.extra.currentGradeNum = '';
                  studentInfo.extra.currentClass = '';
                  studentInfo.extra.gender = 1;
                  forms.currentClassText = '';
                  forms.gradeNumText = '';
                  forms.showSelectStudent = false;
                }
              }
            }}
          />
        </Popup>
      </div>
    );
  }
});
