import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref,
  watch
} from 'vue';
import styles from './index.module.less';
import infoTitle from '../images/new/r-title.png';
import giftTip from '../images/new/gift-tip.png';
import iconGift from '../images/new/icon-gift.png';
import {
  Button,
  CountDown,
  Field,
  Form,
  Picker,
  Popup,
  Radio,
  RadioGroup,
  Tag,
  showToast
} from 'vant';
import MProtocol from '@/components/m-protocol';
import { state as baseState, setLogin } from '@/state';
import qs from 'query-string';
import MImgCode from '@/components/m-img-code';
import { browser, checkPhone, moneyFormat } from '@/helpers/utils';
import request from '@/helpers/request';
import { useStudentRegisterStore } from '@/store/modules/student-register-store';
import { setLoginInit, state } from '@/state';
import deepClone from '@/helpers/deep-clone';
import { useRoute, useRouter } from 'vue-router';
import { ACCESS_TOKEN } from '@/store/mutation-types';
import { storage } from '@/helpers/storage';
import OWxTip from '@/components/m-wx-tip';
import MDialog from '@/components/m-dialog';
import { CurrentTime, useCountDown } from '@vant/use';
import QrcodePayment from '../qrcode-payment';
import UserAuth from '../component/user-auth';
import Payment from '@/views/adapay/payment';
import { beforeSubmit } from '../order-state';
import OPopup from '@/components/m-popup';
import MSticky from '@/components/m-sticky';
import MMessageTip from '@/components/m-message-tip';
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',
  setup() {
    // const studentDetails = sessionStorage.getItem('register-student');
    const countDownRef = ref();
    const route = useRoute();
    const router = useRouter();
    const gradeList = ref([]);
    const forms = reactive({
      schoolId: route.query.schoolId as any,
      countDownStatus: true,
      countDownTime: 1000 * 120, // 倒计时时间
      modelValue: false, // 是否选中协议
      imgCodeStatus: false,
      gradeNumText: '',
      currentClassText: '',
      gradeStatus: false,
      classStatus: false,
      loading: false,
      details: {} as any,
      schoolType: '', // 学校类型
      gradeYear: '', // 学制
      bugGoods: false, // 是否购买AI
      registerType: '', // 报名类型
      giftVipDay: 0, // 赠送天数
      dialogStatus: false,
      dialogMessage: '',
      dialogConfirmStatus: false,
      paymentType: '', // 支付类型
      contract_sign: false, // 是否实名认证
      countDownTimePay: 60 * 1000,
      dialogConfig: {} as any,
      showMore: true,
      showOtherSchool: false,
      showOtherMessage: '',
      showTips: false,
      showButton: false,
      showMessage: '请使用微信扫描二维码'
    });
    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
    });
    const studentInfo = reactive({
      autoRegister: true,
      client_id: 'cooleshow-student',
      client_secret: 'cooleshow-student',
      extra: {
        nickname: '',
        currentGradeNum: '',
        currentClass: '',
        gender: 1,
        registerType: null as any, // 报名类型
        giftVipDay: 0 // 赠送会员天数
      },
      grant_type: 'password',
      loginType: 'SMS',
      password: '',
      username: ''
    });

    const countDown = useCountDown({
      // 倒计时 60 秒
      time: forms.countDownTimePay,
      onChange(current: CurrentTime) {
        forms.dialogMessage = `有待支付订单，请在${Math.ceil(
          current.total / 1000
        )}s后重试`;
      },
      onFinish() {
        forms.dialogStatus = 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 orderType = computed(() => {
      return state.orderInfo.orderType;
    });

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

    const onSubmit = async (isRegister = false) => {
      try {
        if (checkForm()) return;
        forms.loading = true;
        const { extra, ...res } = studentInfo;
        if (!isRegister) {
          const checkSchool = await request.get(
            `/edu-app/open/student/studentSchool?mobile=${studentInfo.username}&code=${studentInfo.password}&type=REGISTER`
          );
          if (checkSchool.data?.schoolId !== forms.schoolId) {
            forms.showOtherSchool = true;
            forms.showOtherMessage = `您已绑定【${
              forms.details.schoolName || ''
            }】，提交后将更换到【${
              checkSchool.data?.schoolName
            }】，是否确认提交？`;
            return;
          }
        }

        const result = await request.post('/edu-app/userlogin', {
          // hideLoading: false,
          requestType: 'form',
          data: {
            ...res,
            extra: JSON.stringify({
              ...extra,
              schoolId: forms.schoolId
            })
          }
        });

        if (result.code !== 200) {
          // sessionStorage.setItem(
          //   'register-student',
          //   JSON.stringify({
          //     ...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 = result.message;
            forms.showButton = true;
          }
        } else {
          studentRegisterStore.setToken(
            result.data.token_type + ' ' + result.data.access_token
          );
          setLoginInit();

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

          await onRegisterSubmit();
        }
      } 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;
    };

    const getGradeList = () => {
      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 getRegisterGoods = async () => {
      try {
        const { data } = await request.get(
          '/edu-app/open/userOrder/registerGoods/' + forms.schoolId,
          {
            noAuthorization: true // 是否请求接口的时候添加toekn
          }
        );
        // 默认选中商品
        studentRegisterStore.setVip(data.details || []);
        const details = deepClone(data.details || []);
        if (details.length > 0) {
          forms.giftVipDay = details[0].membershipDays;
        }
        forms.bugGoods = data.bugGoods;
        forms.schoolType = data.schoolType;
        forms.gradeYear = data.gradeYear;
        forms.registerType = data.registerType;
        studentInfo.extra.giftVipDay = forms.giftVipDay;
        studentInfo.extra.registerType = forms.registerType;
        if (browser().weixin) {
          if (
            data.schoolStatus === 0 &&
            forms.schoolId == '1770035687490105346'
          ) {
            forms.showTips = true;
            forms.showMessage = '团购时间已截止，感谢您的参与';
            forms.showButton = false;
            return;
          }
          if (data.registerType !== 'BUG_GOODS' || data.schoolStatus === 0) {
            forms.showTips = true;
            forms.showMessage = '二维码已经失效，详情请咨询学校老师';
            forms.showButton = false;
            return;
          }
        } else {
          forms.showTips = true;
        }
      } catch {}
    };

    // 计算金额
    const calcPrice = computed(() => {
      let amount: number = 0; //现价
      let originAmount: number = 0; // 原价
      const vipList: any[] = studentRegisterStore.getVip;
      vipList.forEach((vip: any) => {
        amount += Number(vip.currentPrice);
        originAmount += Number(vip.originalPrice);
      });

      // const goodsList: any[] = studentRegisterStore.getGoods;
      // goodsList.forEach((good: any) => {
      //   amount += Number(good.price) * good.quantity;
      //   originAmount += Number(good.originalPrice) * good.quantity;
      // });
      // console.log(studentRegisterStore.getVip);
      return {
        amount,
        originAmount
      };
    });

    // 登记成功之后购买
    const onRegisterSubmit = async () => {
      try {
        // 请求是否有待支付订单，如果有则自动关闭
        const status = await paymentOrderUnpaid();
        if (status) return;
        const schoolInfo = await request.get(
          '/edu-app/userPaymentOrder/registerStatus/' + forms.schoolId
        );
        const vipList = studentRegisterStore.getVip;

        if (schoolInfo.data.hasBuyCourse && vipList.length > 0) {
          forms.dialogConfirmStatus = true;
          return;
        }
        await paymentContinue();
      } catch {
        //
      }
    };

    // 查询未支付订单
    const paymentOrderUnpaid = async () => {
      let result = false;
      try {
        const { data } = await request.get('/edu-app/userPaymentOrder/unpaid');
        // 判断是否有待支付订单

        if (!data.id) return false;

        // 判断是否可以取消订单
        if (data.cancelPayment) {
          await request.post(
            '/edu-app/userPaymentOrder/cancelPayment/' + data.orderNo
          );
          return false;
        } else {
          forms.countDownTime = data.cancelTimes;
          countDown.reset(Number(data.cancelTimes));
          countDown.start();
          forms.dialogMessage = `有待支付订单，请在${Math.ceil(
            countDown.current.value.total / 1000
          )}s后重试`;
          forms.dialogStatus = true;
          forms.dialogConfig = data;
          result = true;
        }
      } catch {
        //
      }
      return result;
    };

    const paymentContinue = async () => {
      try {
        const vipList = studentRegisterStore.getVip;
        const goodsList = studentRegisterStore.getGoods;
        const params: any[] = [];
        vipList.forEach((vip: any) => {
          params.push({
            giftVipDay: vip.membershipDays,
            goodsId: vip.goodsId,
            goodsNum: 1,
            goodsType: vip.goodsType,
            paymentCashAmount: vip.currentPrice, // 现金支付金额
            paymentCouponAmount: 0 // 优惠券金额
          });
        });

        goodsList.forEach((goods: any) => {
          params.push({
            goodsId: goods.productId,
            goodsNum: goods.quantity,
            goodsType: 'INSTRUMENTS',
            paymentCashAmount: goods.price, // 现金支付金额
            paymentCouponAmount: 0, // 优惠券金额
            goodsSkuId: goods.productSkuId
          });
        });
        // 创建订单
        const result = await request.post(
          '/edu-app/userPaymentOrder/executeOrder',
          {
            // hideLoading: false,
            data: {
              registerType: forms.registerType,
              paymentType: forms.paymentType,
              bizId: forms.schoolId, // 乐团编号
              orderType: 'SCHOOL_REGISTER',
              paymentCashAmount: calcPrice.value.amount || 0,
              paymentCouponAmount: 0,
              goodsInfos: params,
              orderName: '学生登记',
              orderDesc: '学生登记'
            }
          }
        );

        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 {
          state.config = {
            ...result.data.paymentConfig,
            paymentType: result.data.paymentType
          };
          state.orderNo = result.data.orderNo;

          await lastSubmit();
        }
      } catch (e: any) {
        console.log(e, 'any');
      }
    };

    const lastSubmit = async () => {
      try {
        const users = baseState.user.data;
        // 判断是否需要实名认证, 姓名，卡号 - 参数设置可以控制
        if (
          forms.contract_sign &&
          (!users?.account.realName || !users?.account.idCardNo)
        ) {
          state.authShow = true;
          return;
        }
        const { data } = await request.post(
          '/edu-app/userPaymentOrder/updateReceiveAddress',
          {
            // hideLoading: false,
            data: {
              orderNo: state.orderNo,
              orderType: 'SCHOOL_REGISTER'
            }
          }
        );
        state.pay_channel = data.paymentChannel;
        if (data.status !== 'WAIT_PAY' && data.status !== 'PAYING') {
          router.replace({
            path: '/payment-result',
            query: {
              orderNo: state.orderNo
            }
          });
        } else {
          onCallback();
        }
      } catch {
        //
      }
    };

    /**
     * @description 回调，判断是否有支付渠道，如果有则直接去支付
     * @returns void
     */
    const onCallback = () => {
      const pt = state.pay_channel;
      // 判断是否有支付方式
      if (pt) {
        const payCode: string = beforeSubmit(state.pay_channel);
        onConfirm({
          payCode,
          pay_channel: pt
        });
      } else {
        if (orderType.value === 'VIP') {
          state.paymentStatus = true;
        } else {
          // 直接去拉取微信支付
          onConfirm({
            payCode: 'payResult',
            pay_channel: 'wx_pub'
          });
        }
      }
    };

    const onConfirm = (val: any) => {
      const config: any = state.config;
      state.pay_channel = val.pay_channel;

      const params = qs.stringify({
        pay_channel: val.pay_channel,
        wxAppId: config.wxAppId,
        alipayAppId: config.alipayAppId,
        paymentType: forms.paymentType,
        body: config.body,
        price: config.price,
        orderNo: config.merOrderNo,
        userId: config.userId
      });

      // console.log(params, state.config);
      // return;
      if (val.payCode === 'payResult') {
        window.location.href =
          window.location.origin + '/classroom-app/#/payResult?' + params;
      } else {
        state.qrCodeUrl =
          window.location.origin + '/classroom-app/#/payDefine?' + params;
        state.showQrcode = true;
        state.paymentStatus = false;

        setTimeout(() => {
          getPaymentOrderStatus();
        }, 300);
      }
    };

    // 放弃支付时，则取消订单
    const onBackOut = async () => {
      try {
        await request.post(
          '/edu-app/userPaymentOrder/cancelPayment/' + state.orderNo
        );
        // router.back();
      } catch {
        //
      }
    };

    // 轮询查询订单状态
    const getPaymentOrderStatus = async () => {
      // 循环查询订单
      // const orderNo = state.orderNo
      const orderTimer = setInterval(async () => {
        // 判断是否在当前路由，如果不是则清除定时器
        if (route.name != 'student-register-form') {
          clearInterval(orderTimer);
          return;
        }
        state.orderTimer = orderTimer;
        try {
          const { data } = await request.post(
            '/edu-app/open/userOrder/paymentStatus/' + state.orderNo,
            {
              hideLoading: true
            }
          );

          if (data.status !== 'WAIT_PAY' && data.status !== 'PAYING') {
            // 默认关闭支付二维码弹窗
            state.showQrcode = false;
            clearInterval(state.orderTimer);
            setTimeout(() => {
              router.replace({
                path: '/payment-result',
                query: {
                  orderNo: state.orderNo
                }
              });
            }, 100);
          }
        } catch {
          //
          clearInterval(state.orderTimer);
        }
      }, 5000);
    };
    // 实名认证成功
    const onAuthSuccess = () => {
      //
      state.authShow = false;
      paymentContinue(); // 实名成功后自动支付
    };

    //
    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`
        );
        if (data) {
          if (!studentInfo.extra.nickname) {
            studentInfo.extra.nickname = data.nickname;
          }

          if (!studentInfo.extra.currentGradeNum) {
            studentInfo.extra.currentGradeNum = data.currentGradeNum;
          }

          if (!studentInfo.extra.currentClass) {
            studentInfo.extra.currentClass = data.currentClass;
          }
          // if (!studentInfo.extra.gender) {
          studentInfo.extra.gender =
            studentInfo.extra.gender !== data.gender
              ? data.gender
              : studentInfo.extra.gender;

          // studentInfo.username = data.nickname;

          classList.forEach((i: any) => {
            if (i.value === data.currentClass) {
              forms.currentClassText = i.text;
            }
          });

          const tempGrade: any = gradeList.value[0] || [];
          tempGrade?.forEach((i: any) => {
            if (i.value === data.currentGradeNum) {
              forms.gradeNumText = i.text;
            }
          });
        }
      } catch {
        //
      }
    };

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

        await getRegisterGoods();
      } catch {}
      gradeList.value = getGradeList();
      // if (studentDetails) {
      //   const studentJson = JSON.parse(studentDetails);
      //   const extraJson = studentJson.extra
      //     ? JSON.parse(studentJson.extra)
      //     : {};
      //   studentInfo.extra.nickname = extraJson.nickname;
      //   studentInfo.extra.currentGradeNum = extraJson.currentGradeNum;
      //   studentInfo.extra.currentClass = extraJson.currentClass;
      //   studentInfo.extra.gender = extraJson.gender;
      //   studentInfo.username = studentJson.username;

      //   classList.forEach((i: any) => {
      //     if (i.value === extraJson.currentClass) {
      //       forms.currentClassText = i.text;
      //     }
      //   });

      //   const tempGrade: any = gradeList.value[0] || [];
      //   tempGrade?.forEach((i: any) => {
      //     if (i.value === extraJson.currentGradeNum) {
      //       forms.gradeNumText = i.text;
      //     }
      //   });

      //   sessionStorage.removeItem('register-student');
      // }
    });

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

          <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}>
              {{
                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>
            <Field
              clearable={false}
              required
              inputAlign="right"
              label="学生姓名"
              placeholder="请输入学生姓名"
              autocomplete="off"
              maxlength={14}
              v-model={studentInfo.extra.nickname}
            />
            <Field
              clearable={false}
              required
              inputAlign="right"
              label="学生性别"
              placeholder="请选择性别"
              autocomplete="off"
              // v-model={studentInfo.extra.nickname}
            >
              {{
                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
              readonly
              clickable={false}
              modelValue={forms.gradeNumText}
              onClick={() => (forms.gradeStatus = true)}
            />
            <Field
              clearable={false}
              required
              inputAlign="right"
              label="所在班级"
              placeholder="请选择班级"
              isLink
              readonly
              clickable={false}
              modelValue={forms.currentClassText}
              onClick={() => (forms.classStatus = true)}
            />
            {forms.giftVipDay > 0 && (
              <div class={styles.memberNumer}>
                <img src={iconGift} class={styles.iconGift} />

                <p>
                  注册成功即可获得乐器AI学练工具
                  <span>{forms.giftVipDay || 0}</span>天有效期
                </p>
              </div>
            )}
          </Form>
          {/* <MProtocol
          center
          v-model:modelValue={forms.modelValue}
          prototcolType="REGISTER"
        /> */}

          <MSticky position="bottom">
            <div class={styles.paymentContainer}>
              <div class={styles.payemntPrice}>
                <img src={giftTip} class={styles.giftTip} />
                <div>
                  <span class={styles.needPrice}>
                    <i style="font-style: normal">¥ </i>
                    <span>{moneyFormat(calcPrice.value.amount)}</span>
                    <i style="font-style: normal">/年</i>
                  </span>
                  {calcPrice.value.originAmount > calcPrice.value.amount ? (
                    <del class={styles.allPrice}>
                      ¥ {moneyFormat(calcPrice.value.originAmount)}
                    </del>
                  ) : (
                    ''
                  )}
                </div>
              </div>
              <div class={styles.paymentBtn} onClick={() => onSubmit()}>
                <Button round disabled={forms.loading} loading={forms.loading}>
                  立即支付
                </Button>
              </div>
            </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.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>

        {/* 已经购买过样品 */}
        <MDialog
          title="提示"
          v-model:show={forms.dialogConfirmStatus}
          message={'已购买会员，是否确认购买？'}
          primaryColor="#FF8057"
          allowHtml={true}
          confirmButtonText="确定"
          showCancelButton
          onConfirm={async () => {
            await paymentContinue();
          }}
        />

        <MDialog
          title="提示"
          v-model:show={forms.dialogStatus}
          message={forms.dialogMessage}
          allowHtml={true}
          primaryColor="#FF8057"
          confirmButtonText="继续支付"
          onConfirm={async () => {
            // const paymentConfig = forms.dialogConfig.paymentConfig;
            // router.push({
            //   path: '/order-detail',
            //   query: {
            //     pm: 1, // h5乐团报名
            //     config: JSON.stringify(paymentConfig.paymentConfig),
            //     orderNo: paymentConfig.orderNo
            //   }
            // });
            // console.log(forms.dialogConfig, 'dialogConfig');

            countDown.pause();
            const paymentConfig = forms.dialogConfig.paymentConfig;
            state.config = paymentConfig?.paymentConfig;
            state.orderNo = paymentConfig?.orderNo;

            await lastSubmit();
          }}
          onCancel={(val: any) => {
            countDown.pause();
          }}
        />

        <Popup
          show={state.paymentStatus}
          closeOnClickOverlay={false}
          position="bottom"
          round
          closeOnPopstate
          safeAreaInsetBottom
          style={{ minHeight: '30%' }}>
          <Payment
            paymentConfig={state.orderInfo}
            onClose={() => (state.paymentStatus = false)}
            onBackOut={onBackOut}
            onConfirm={(val: any) => onConfirm(val)}
          />
        </Popup>

        <Popup
          v-model:show={state.showQrcode}
          round
          onClose={() => {
            // 二维码关闭时清除定时器
            clearInterval(state.orderTimer);
          }}>
          <QrcodePayment
            url={state.qrCodeUrl}
            pay_channel={state.pay_channel}
            orderType={orderType.value}
          />
        </Popup>

        <OPopup v-model:modelValue={state.authShow}>
          <UserAuth onSuccess={onAuthSuccess} hideHeader={!browser().isApp} />
        </OPopup>

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

        <MMessageTip
          show={forms.showOtherSchool}
          messageAlign="left"
          message={forms.showOtherMessage}
          showCancelButton
          onCancel={() => (forms.showOtherSchool = false)}
          onConfirm={() => {
            forms.showOtherSchool = false;
            // 直接注册
            onSubmit(true);
          }}
        />
      </div>
    );
  }
});
