import {
  Image,
  Cell,
  Tag,
  Button,
  Popup,
  showToast,
  Form,
  Field,
  CountDown,
  RadioGroup,
  Radio,
  Picker,
  closeToast,
  Popover,
  Area,
  CellGroup,
  showConfirmDialog
} from 'vant';
import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  onUnmounted,
  reactive,
  ref
} from 'vue';
import qs from 'query-string';
import {
  state as baseState,
  goWechatAuth,
  setLogin,
  setLoginInit
} from '@/state';
import styles from './index.module.less';
import MSticky from '@/components/m-sticky';
// import MVideo from '@/components/m-video';
import { useRoute, useRouter } from 'vue-router';
import { useStudentRegisterStore } from '@/store/modules/student-register-store';
import request from '@/helpers/request';
import { browser, checkPhone, getUrlCode, moneyFormat } from '@/helpers/utils';
import deepClone from '@/helpers/deep-clone';
import OWxTip from '@/components/m-wx-tip';
import MDialog from '@/components/m-dialog';
// import f1 from './images/new/f-1.png';
// import f2 from './images/new/f-2.png';
// import f3 from './images/new/f-3.png';
// import iconTip2 from './images/new/icon-tip2.png';
// import functionBg from './images/new/function-bg.png';
// import tuangou from './images/new/tuangou.png';
// import icon3 from './images/new/icon-3.png';
// import icon5 from './images/new/icon-5.png';
// import icon10 from './images/new/icon-10.png';
// import icon6 from './images/new/icon-6.png';
// import giftTip from './images/new/icon-9.png';
// import iconGift from './images/new/icon-gift.png';
// import vipGiftTIps from './images/new/vip_gift_tips.png';
import dayjs from 'dayjs';
// import MMessageTip from '@/components/m-message-tip';
import { CurrentTime, useCountDown } from '@vant/use';

import MImgCode from '@/components/m-img-code';
import { useInterval, useIntervalFn } from '@vueuse/core';
import MMessageTip from '@/components/m-message-tip';
import SelectStudent from '@/views/student-register/modal/select-student';
import { api_sysAreaQueryAllProvince } from '@/views/school-register/api';
import CodeDialog from '../modal/code-dialog';
import MSearch from '@/components/m-search';

const classList: any = [];
for (let i = 1; i <= 40; i++) {
  classList.push({ text: i + '班', value: i });
}

const GRADE_ENUM = {
  '1': '一年级',
  '2': '二年级',
  '3': '三年级',
  '4': '四年级',
  '5': '五年级',
  '6': '六年级',
  '7': '七年级',
  '8': '八年级',
  '9': '九年级'
} as any;
const getGradeList = (gradeYear?: string, instrumentCode?: string) => {
  let tempList: any = [];
  const five = [
    { text: '一年级', value: 1, instrumentCode },
    { text: '二年级', value: 2, instrumentCode },
    { text: '三年级', value: 3, instrumentCode },
    { text: '四年级', value: 4, instrumentCode },
    { text: '五年级', value: 5, instrumentCode }
  ];
  const one = [{ text: '六年级', value: 6, instrumentCode }];
  const three = [
    { text: '七年级', value: 7, instrumentCode },
    { text: '八年级', value: 8, instrumentCode },
    { text: '九年级', value: 9, instrumentCode }
  ];
  if (gradeYear === 'FIVE_YEAR_SYSTEM') {
    tempList.push(...[...five]);
  } else if (gradeYear === 'SIX_YEAR_SYSTEM') {
    tempList.push(...[...five, ...one]);
  } else if (gradeYear === 'THREE_YEAR_SYSTEM') {
    tempList.push(...[...three]);
  } else if (gradeYear === 'FORE_YEAR_SYSTEM') {
    tempList.push(...[...one, ...three]);
  } else {
    tempList.push(...[...five, ...one, ...three]);
  }
  return tempList;
};

export default defineComponent({
  name: 'activation-register',
  setup() {
    const route = useRoute();
    const studentRegisterStore = useStudentRegisterStore();
    const router = useRouter();
    // 初始化学校编号
    // studentRegisterStore.setShoolId(route.query.sId as any);
    const countDownRef = ref();
    const forms = reactive({
      schoolId: null as any,
      schoolAreaId: null, // 学校区域编号
      activationCode: route.query.code as any, // 互通码
      paymentType: '', // 支付类型
      paymentChannel: '',
      multi_user_limit: 1, // 限制注册学生数量
      // popupShow: false,
      registerDetails: {} as any,
      details: [] as any[],
      // schoolType: '', // 学校类型
      gradeYear: '', // 学制
      schoolInstrumentSetType: null as any,
      // bugGoods: false, // 是否购买AI

      isRegister: 'create' as 'create' | 'update' | '', // 是否注册学生
      isDisabled: false,
      isTipRegister: false, // 是否显示名字不一致 - 默认显示
      isChangeSchool: false, // 是否切换学校

      schoolStatus: false,
      schoolPopupShow: false,
      schoolLoading: false,
      schoolAreaList: [] as any,
      provinceCode: null,
      cityCode: null,
      regionCode: null,

      showResultPopup: false,
      reslutPopupType: '' as any,
      resultPopupContent: '',
      registerType: '', // 报名类型
      detailVip: {} as any,
      giftVipDay: 0, // 赠送天数
      submitLoading: false,
      // showMore: true,
      showTips: false,
      showButton: false,
      showMessage: '请使用微信扫描二维码',
      countDownStatus: true,
      countDownTime: 1000 * 120, // 倒计时时间
      // modelValue: false, // 是否选中协议
      imgCodeStatus: false,
      gradeNumText: '',
      currentClassText: '',

      schoolName: '',
      areaName: '',

      gradeStatus: false,
      classStatus: false,
      loading: false,

      showConfirmPopup: false, // 二次确认用户信息
      showPicker: false,
      areaList: [] as any,
      tipStatus: true,
      dialogConfirmStatus: false,
      contract_sign: false, // 是否实名认证
      countDownTimePay: 60 * 1000,
      dialogConfig: {} as any,
      showSelectStudent: false, // 选择学生
      studentList: [], // 手机号关联学生列表
      studentItem: {} as any, // 选择的学生
      joinType: 'digitalize' as 'digitalize' | 'tradition',
      gradeList: [] as any,
      classList: [] as any,
      saveUserId: null as any,
      saveId: null as any,
      openId: null as any,
      code: null as any,
      registerExpireTime: null as any, // 结束时间
      instrumentCode: null as any, // 乐器编码
      activeOverTime: 0, // 活动结束时间
      activeOverStatus: true, // 活动是否结束 默认已结束
      gradePopupShow: false,
      gradePopupIndex: [] as any, // 年级下拉索引
      classPopupShow: false,
      classPopupIndex: [] as any // 班级下拉索引
    });

    const otherParams = reactive({
      showOtherSchool: false,
      showCloseButton: true, // 是否显示关闭按钮
      showOtherMessage: '',
      /**  limit 超限制，change 更换学生，nickname 名称不一致 member 会员购买, payment 支付方式 */
      otherType: '' as 'limit' | 'change' | 'nickname' | 'member' | 'payment',
      showCancelButton: true,
      cancelButtonColor: '',
      cancelButtonText: '取消',
      showConfirmButton: true,
      confirmButtonColor: '',
      confirmButtonText: '确定',
      messageAlign: 'left' as 'center' | 'left' | 'right'
    });

    const state = reactive({
      showQrcode: false,
      qrCodeUrl: '',
      pay_channel: '',
      orderInfo: {} as any, // 订单信息
      authShow: false,
      orderNo: null as any,
      config: {} as any,
      paymentStatus: false,
      orderTimer: null as any
    });

    /*
      新用户：
      autoRegister: true
      loginType: 'SMS'

      已存在用户：
      autoRegister： false
      loginType: 'TOKEN'
      password: xxx
    */

    const studentInfo = reactive({
      autoRegister: true,
      multiUser: true, // 是否为多用户
      client_id: 'cooleshow-student',
      client_secret: 'cooleshow-student',
      extra: {
        nickname: '',
        currentGradeNum: '' as any,
        currentClass: '' as any,
        gender: 1 as any,
        registerType: null as any, // 报名类型
        giftVipDay: 0 // 赠送会员天数
      },
      grant_type: 'password',
      loginType: 'SMS',
      password: '',
      username: ''
    });
    // 页面定时
    const pageTimer = useInterval(1000, { controls: true });
    pageTimer.pause();

    const overCountDown = useCountDown({
      time: forms.activeOverTime,
      onFinish() {
        forms.activeOverStatus = true;
        if (forms.submitLoading) return;
        applyOver();
      }
    });
    /** 报名结束提示 */
    const applyOver = () => {
      forms.showTips = true;
      // forms.showMessage = '团购时间已截止，感谢您的参与';
      forms.showMessage =
        '<p style="color: #F44541">报名已截止，感谢您的参与</p>';
      forms.showButton = false;
    };

    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 changeTipStatus = (register: boolean, school: boolean) => {
      forms.isTipRegister = register;
      forms.isChangeSchool = school;
    };

    const checkForm = (status = true) => {
      if (!checkPhone(studentInfo.username)) {
        status && showToast('请输入正确的手机号码');
        return true;
      } else if (!studentInfo.password) {
        status && showToast('请输入验证码');
        return true;
      } else if (!studentInfo.extra.nickname) {
        status && showToast('请输入学生姓名');
        return true;
      } else if (![0, 1].includes(studentInfo.extra.gender)) {
        status && showToast('请选择性别');
        return true;
      } else if (!studentInfo.extra.currentGradeNum) {
        status && showToast('请选择所在年级');
        return true;
      } else if (!studentInfo.extra.currentClass) {
        status && showToast('请选择所在班级');
        return true;
      } else if (!forms.activationCode) {
        status && showToast('请输入互通码');
        return true;
      }
      return false;
    };

    //
    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;
      }

      return false;
    };

    /**
     * 登记成功之后购买
     */
    const onSubmit = async () => {
      forms.submitLoading = true;
      try {
        if (checkForm() || checkSubmit()) {
          forms.submitLoading = false;
          return;
        }
        const { extra, loginType, autoRegister, password, multiUser, ...res } =
          studentInfo;
        /*
          新用户：
          autoRegister: true
          loginType: 'SMS'

          已存在用户：
          autoRegister： false
          loginType: 'TOKEN'
          password: xxx
        */
        let tLoginType = loginType,
          tAutoRegister = autoRegister,
          tPassword = password,
          tMultiUser = multiUser;
        if (forms.isRegister === 'update') {
          tLoginType = 'TOKEN';
          tAutoRegister = false;
          tPassword = forms.studentItem.token;
          tMultiUser = false;
        }
        const result = await request.post('/edu-app/userlogin', {
          requestType: 'form',
          data: {
            loginType: tLoginType,
            autoRegister: tAutoRegister,
            password: tPassword,
            multiUser: tMultiUser,
            ...res,
            extra: JSON.stringify({
              ...extra,
              // giftVipDay:
              //   forms.detailVip.membershipDays || 0 + forms.giftVipDay || 0,
              schoolId: forms.schoolId
            })
          }
        });

        if (result.code !== 200) {
          if (result.code === 5436) {
            forms.showTips = true;
            forms.showMessage = '二维码已经失效，详情请咨询学校老师';
            forms.showButton = false;
          } else if (result.code === 5435) {
            forms.showTips = true;
            forms.showMessage = result.message;
            forms.showButton = true;
          }
          // else if (result.code === 5437) {
          //   forms.showTips = true;
          //   forms.showMessage =
          //     '<p style="color: #F44541">报名已截止，感谢您的参与</p>'; //result.message;
          //   forms.showButton = false;
          // }
        } else {
          studentRegisterStore.setToken(
            result.data.token_type + ' ' + result.data.access_token
          );
          setLoginInit();

          // let joinType = 'NOT_REGISTER';
          // if (forms.joinType === 'digitalize') {
          //   joinType = 'SELECT_INSTRUMENT';
          // }
          // if (forms.joinType === 'tradition') {
          //   joinType = 'NOT_BUY_INSTRUMENT';
          // }

          // 获取用户信息
          const res = await request.get('/edu-app/user/getUserInfo', {
            requestType: 'form'
          });
          setLogin(res.data);

          // await onRegisterSubmit();

          await updateStudentInfo();
        }
      } catch {
        // 重置信息 - 如果是新建则不提示
        changeTipStatus(forms.isRegister === 'create' ? false : true, false);
      } finally {
        forms.submitLoading = false;
      }
    };

    const updateStudentInfo = async () => {
      try {
        const { extra, username } = studentInfo;
        const registerResult = await request.post('/edu-app/student/register', {
          data: {
            clientType: 'STUDENT',
            ...extra,
            activationCode: forms.activationCode,
            schoolId: forms.schoolId,
            schoolAreaId: forms.schoolAreaId,
            // giftVipFlag: forms.registerDetails.giftVipFlag || false,
            // giftVipDay: forms.giftVipDay || 0,
            schoolVerify: false,
            // firstVipDay: forms.detailVip.membershipDays || 0,
            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;
          } else if (registerResult.code === 5437) {
            forms.showTips = true;
            forms.showMessage =
              '<p style="color: #F44541">报名已截止，感谢您的参与</p>'; //result.message;
            forms.showButton = false;
          } else if (registerResult.code === 5442) {
            forms.showResultPopup = true;
            forms.reslutPopupType = 'EXPIRED';
            forms.resultPopupContent = registerResult.message;
          } else if (registerResult.code === 5443) {
            forms.showResultPopup = true;
            forms.reslutPopupType = 'CANCELLED';
            forms.resultPopupContent = registerResult.message;
          }
          return false;
        } else {
          forms.showResultPopup = true;
          forms.reslutPopupType = 'ACTIVATING';
          return true;
        }
      } catch {}
    };

    const getUserInfos = async () => {
      if (
        studentInfo.password.length !== 6 ||
        !checkPhone(studentInfo.username)
      ) {
        return;
      }
      try {
        // 15907120131;
        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 tempArea = [] as any;
          if (firstStudent.provinceName) {
            tempArea.push(firstStudent.provinceName);
            forms.provinceCode = firstStudent.provinceCode;
          }
          if (firstStudent.cityName) {
            tempArea.push(firstStudent.cityName);
            forms.cityCode = firstStudent.cityCode;
          }
          if (firstStudent.regionName) {
            tempArea.push(firstStudent.regionName);
            forms.regionCode = firstStudent.regionCode;
          }
          forms.areaName = tempArea.join(' ');
          forms.schoolName = firstStudent.schoolName;
          forms.schoolId = firstStudent.schoolId;
          forms.schoolAreaId = firstStudent.schoolAreaId;

          const tempGrade: any = forms.gradeList || [];
          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.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 phoneChangeEmptyInfo = () => {
      studentInfo.password = '';
      studentInfo.extra.nickname = '';
      studentInfo.extra.currentGradeNum = '';
      studentInfo.extra.currentClass = '';
      studentInfo.extra.gender = 1;
      forms.areaName = '';
      forms.schoolName = '';
      forms.currentClassText = '';
      forms.gradeNumText = '';
      forms.studentList = []; // 手机号关联学生列表
      forms.studentItem = {}; // 选择的学生
      forms.isRegister = 'create'; // 是否注册学生
      forms.isTipRegister = false; // 是否显示名字不一致 - 默认显示
      forms.isChangeSchool = false; // 是否切换学校
    };

    const formateArea = (area: any[]) => {
      const province_list: { [_: string]: string } = {};
      const city_list: { [_: string]: string } = {};
      const county_list: { [_: string]: string } = {};
      area.forEach((item: any) => {
        province_list[item.code] = item.name;
      });
      area.forEach((item: any) => {
        item.areas?.forEach((city: any) => {
          city_list[city.code] = city.name;
        });
      });
      area.forEach((item: any) => {
        item.areas?.forEach((city: any) => {
          city.areas?.forEach((county: any) => {
            county_list[county.code] = county.name;
          });
        });
      });
      return {
        province_list,
        city_list,
        county_list
      };
    };
    const getAreaList = () => {
      api_sysAreaQueryAllProvince().then(res => {
        if (res?.code === 200) {
          forms.areaList = formateArea(res.data);
        }
      });
    };

    const getSchoolAreaList = async (name?: string) => {
      forms.schoolLoading = true;
      try {
        const { data } = await request.post('/edu-app/schoolArea/list', {
          data: {
            name,
            provinceCode: forms.provinceCode,
            cityCode: forms.cityCode,
            regionCode: forms.regionCode
          }
        });
        forms.schoolAreaList = data;
      } catch {
        //
      }
      forms.schoolLoading = false;
    };
    onMounted(async () => {
      getAreaList();
      try {
        // 获取支付类型
        const { data } = await request.get(
          '/edu-app/open/paramConfig/queryByParamNameList',
          {
            requestType: 'form',
            params: {
              paramNames: 'multi_user_limit'
            }
          }
        );
        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;
            }
          });
        }
      } catch {}

      forms.gradeList = getGradeList();
      forms.classList = classList;
    });
    return () => (
      <div class={styles['student-register']}>
        <div class={styles.studentRegisterContainer}>
          <div class={[styles.studentSection]}>
            <Form labelAlign="left" class={styles.registerForm}>
              <Field
                clearable={false}
                label="联系方式"
                placeholder="请输入手机号码"
                type="tel"
                required
                autocomplete="off"
                inputAlign="right"
                v-model={studentInfo.username}
                maxlength={11}
                onUpdate:modelValue={() => {
                  phoneChangeEmptyInfo();
                }}></Field>

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

              <Field
                clearable={false}
                required
                inputAlign="right"
                label="学生姓名"
                placeholder="请输入学生姓名"
                autocomplete="off"
                maxlength={14}
                v-model={studentInfo.extra.nickname}>
                {{
                  extra: () =>
                    forms.studentList.length > 1 && (
                      <div
                        class={[
                          styles.selectStudentGroup,
                          forms.showSelectStudent &&
                            styles.selectStudentGroupChecked
                        ]}
                        onClick={() => (forms.showSelectStudent = true)}>
                        <span>
                          {forms.studentItem.userId ? '切换' : '新增'}
                        </span>
                      </div>
                    )
                }}
              </Field>
              <Field
                clearable={false}
                required
                inputAlign="right"
                label="学生性别"
                placeholder="请选择性别"
                autocomplete="off">
                {{
                  input: () => (
                    <RadioGroup
                      checked-color="linear-gradient( 135deg, #31C7FF 0%, #007AFE 100%)"
                      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}>
                        <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}>
                        <Radio class={styles.radioItem} name={0}></Radio>女
                      </Tag>
                    </RadioGroup>
                  )
                }}
              </Field>

              <Field
                clearable={false}
                required
                inputAlign="right"
                label="所在地区"
                placeholder="请选择所在地区"
                isLink={forms.isRegister !== 'update'}
                readonly
                clickable={false}
                modelValue={forms.areaName}
                onClick={() => {
                  if (forms.isRegister !== 'update') forms.showPicker = true;
                  // forms.gradePopupIndex = [studentInfo.extra.currentGradeNum];
                }}
              />

              <Field
                clearable={false}
                required
                inputAlign="right"
                label="互通学校"
                placeholder="请选择互通学校"
                isLink={forms.isRegister !== 'update'}
                readonly
                clickable={false}
                modelValue={forms.schoolName}
                onClick={() => {
                  if (forms.isRegister === 'update') return;

                  if (!forms.areaName) {
                    showToast('请选择地区');
                    return;
                  }

                  forms.schoolStatus = true;
                  // forms.gradeStatus = true;
                  // forms.gradePopupIndex = [studentInfo.extra.currentGradeNum];
                }}
              />

              <Field
                clearable={false}
                required
                inputAlign="right"
                label="所在年级"
                placeholder="请选择年级"
                isLink={forms.isRegister !== 'update'}
                readonly
                clickable={false}
                modelValue={forms.gradeNumText}
                onClick={() => {
                  if (forms.isRegister !== 'update') {
                    forms.gradePopupIndex = [studentInfo.extra.currentGradeNum];
                    forms.gradeStatus = true;
                  }
                }}
              />
              <Field
                clearable={false}
                required
                inputAlign="right"
                label="所在班级"
                placeholder="请选择班级"
                isLink={forms.isRegister !== 'update'}
                readonly
                clickable={false}
                modelValue={forms.currentClassText}
                onClick={() => {
                  if (forms.isRegister == 'update') {
                    return;
                  }
                  if (
                    forms.schoolInstrumentSetType === 'CLASS' &&
                    forms.classList.length <= 0
                  ) {
                    showToast('请先选择年级');
                    return;
                  }
                  forms.classPopupIndex = [studentInfo.extra.currentClass];
                  forms.classStatus = true;
                }}
              />

              <Field
                clearable={false}
                required
                inputAlign="right"
                label="互通码"
                placeholder="请选择互通码"
                readonly={route.query.code ? true : false}
                v-model={forms.activationCode}
              />
            </Form>
          </div>

          <MSticky position="bottom">
            <div class={styles.paymentContainer}>
              <Button
                onClick={() => {
                  // onSubmit();
                  if (checkForm() || checkSubmit()) {
                    forms.submitLoading = false;
                    return;
                  }
                  forms.showConfirmPopup = true;
                }}
                round
                block
                disabled={forms.submitLoading}
                loading={forms.submitLoading}>
                提交
              </Button>
            </div>
          </MSticky>
        </div>

        {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.schoolStatus}
          position="bottom"
          round
          safeAreaInsetBottom
          lazyRender={false}
          class={'popupBottomSearch'}
          onOpen={() => {
            forms.schoolPopupShow = true;
          }}
          onClosed={() => {
            forms.schoolPopupShow = false;
          }}>
          {forms.schoolPopupShow && (
            <div>
              <Picker
                showToolbar
                // v-model={forms.gradePopupIndex}
                columns={forms.schoolAreaList}
                loading={forms.schoolLoading}
                columnsFieldNames={{
                  text: 'name',
                  value: 'id'
                }}
                onCancel={() => (forms.schoolStatus = false)}
                onConfirm={(val: any) => {
                  const selectedOption = val.selectedOptions[0];
                  forms.schoolId = null;
                  forms.schoolAreaId = selectedOption.id;
                  forms.schoolName = selectedOption.name;
                  forms.schoolStatus = false;
                }}>
                {{
                  'columns-top': (
                    <MSearch
                      placeholder="请输入学校名称"
                      onSearch={(val: any) => {
                        getSchoolAreaList(val);
                      }}
                    />
                  )
                }}
              </Picker>
            </div>
          )}
        </Popup>

        {/* 年级 */}
        <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={forms.gradeList}
              onCancel={() => (forms.gradeStatus = false)}
              onConfirm={(val: any) => {
                const selectedOption = val.selectedOptions[0];
                studentInfo.extra.currentGradeNum = selectedOption.value;
                forms.gradeNumText = selectedOption.text;
                forms.gradeStatus = false;
                if (
                  ['SCHOOL', 'GRADE'].includes(forms.schoolInstrumentSetType)
                ) {
                  forms.instrumentCode = selectedOption.instrumentCode;
                }

                if (forms.schoolInstrumentSetType === 'CLASS') {
                  forms.classList = selectedOption.classList;
                }
                if (
                  ['CLASS', 'GRADE'].includes(forms.schoolInstrumentSetType)
                ) {
                  forms.currentClassText = '';
                  studentInfo.extra.currentClass = '';
                }
              }}
            />
          )}
        </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={forms.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;
                if (['CLASS'].includes(forms.schoolInstrumentSetType)) {
                  forms.instrumentCode = selectedOption.instrumentCode;
                }
              }}
            />
          )}
        </Popup>

        {/* 是否在微信中打开 */}
        <OWxTip
          show={forms.showTips}
          message={forms.showMessage}
          showButton={forms.showButton}
          buttonText="刷新"
          onConfirm={() => window.location.reload()}
        />

        <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={async () => {
            otherParams.showOtherSchool = false;
            if (otherParams.otherType === 'nickname') {
              forms.isRegister = 'create'; // 新建
              changeTipStatus(false, false);
              onSubmit();
            } else if (otherParams.otherType === 'member') {
              const updateStatus = await updateStudentInfo();
              if (!updateStatus) return;
              //取消支付，判断是否有结束时间，是否已经结束
              if (forms.registerExpireTime && forms.activeOverStatus) {
                applyOver();
              }
            } else if (otherParams.otherType === 'payment') {
              forms.joinType = 'tradition';
            }
          }}
          onConfirm={async () => {
            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
              );
            } else if (otherParams.otherType === 'member') {
              // await paymentContinue();
            }
          }}
        />

        <Popup
          v-model:show={forms.showSelectStudent}
          round
          position="bottom"
          safeAreaInsetBottom
          closeable>
          <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 = forms.gradeList || [];

                const tempArea = [] as any;
                if (firstStudent.provinceName) {
                  tempArea.push(firstStudent.provinceName);
                  forms.provinceCode = firstStudent.provinceCode;
                }
                if (firstStudent.cityName) {
                  tempArea.push(firstStudent.cityName);
                  forms.cityCode = firstStudent.cityCode;
                }
                if (firstStudent.regionName) {
                  tempArea.push(firstStudent.regionName);
                  forms.regionCode = firstStudent.regionCode;
                }
                forms.areaName = tempArea.join(' ');

                forms.schoolName = firstStudent.schoolName;
                forms.schoolId = firstStudent.schoolId;
                forms.schoolAreaId = firstStudent.schoolAreaId;

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

                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;
                    }
                  }
                });

                studentInfo.extra.currentClass = null;
                forms.currentClassText = '';

                forms.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>

        <Popup
          v-model:show={forms.showPicker}
          position="bottom"
          round
          class={'popupBottomSearch'}>
          <Area
            areaList={forms.areaList}
            onCancel={() => (forms.showPicker = false)}
            onConfirm={({ selectedOptions }) => {
              forms.provinceCode = selectedOptions[0].value;
              forms.cityCode = selectedOptions[1].value;
              forms.regionCode = selectedOptions[2].value;
              // data.cityName = selectedOptions
              //   .map((item: any) => item.text)
              //   .join(' ');
              forms.areaName = selectedOptions
                .map((item: any) => item.text)
                .join(' ');

              forms.showPicker = false;
              forms.schoolAreaId = null;
              forms.schoolName = '';

              getSchoolAreaList();
            }}
          />
        </Popup>

        <Popup
          show={forms.showConfirmPopup}
          style={{
            background: 'transparent',
            overflow: 'visible !important'
          }}>
          <CodeDialog type="INFO" showButton={false}>
            <div class={styles.studentInfo}>
              <Cell
                border={false}
                title="学生姓名"
                value={studentInfo.username}></Cell>
              <Cell
                border={false}
                title="学生性别"
                value={studentInfo.extra.gender === 1 ? '男' : '女'}></Cell>
              <Cell
                border={false}
                title="所在地区"
                value={forms.areaName}></Cell>
              <Cell
                border={false}
                title="互通学校"
                value={forms.schoolName}></Cell>
              <Cell
                border={false}
                title="所在年级"
                value={forms.gradeNumText}></Cell>
              <Cell
                border={false}
                title="所在班级"
                value={forms.currentClassText}></Cell>
              {route.query.code && (
                <Cell
                  border={false}
                  title="互通码"
                  value={forms.activationCode}></Cell>
              )}
            </div>
            <div class={styles.studentBtnGroup}>
              <Button
                round
                block
                onClick={() => (forms.showConfirmPopup = false)}>
                取消
              </Button>
              <Button
                round
                block
                disabled={forms.submitLoading}
                loading={forms.submitLoading}
                color="linear-gradient( 305deg, #40C8FF 0%, #3192FF 100%)"
                onClick={() => {
                  forms.showConfirmPopup = false;
                  onSubmit();
                }}>
                提交
              </Button>
            </div>
          </CodeDialog>
        </Popup>

        <Popup
          show={forms.showResultPopup}
          style={{
            background: 'transparent',
            overflow: 'visible !important'
          }}>
          <CodeDialog
            type={forms.reslutPopupType}
            btnText={
              forms.reslutPopupType === 'ACTIVATING'
                ? '立即下载激活码'
                : '我知道了'
            }
            onConfirm={() => {
              //
              if (forms.reslutPopupType === 'ACTIVATING') {
                router.push('/download');
              } else {
                forms.showResultPopup = false;
              }
            }}>
            {forms.reslutPopupType === 'ACTIVATING' && (
              <p>
                请下载
                <span style={{ color: '#2B85FF' }}>【音乐数字课堂App】</span>
                ，使用手机号激活，实现音乐课堂互通互联
              </p>
            )}

            {forms.reslutPopupType === 'CANCELLED' && (
              <p style={{ textAlign: 'center' }}>{forms.resultPopupContent}</p>
            )}
            {forms.reslutPopupType === 'EXPIRED' && (
              <p style={{ textAlign: 'center' }}>{forms.resultPopupContent}</p>
            )}
          </CodeDialog>
        </Popup>
      </div>
    );
  }
});
