import { defineComponent, nextTick, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import {
  Button,
  Cell,
  CellGroup,
  CountDown,
  Field,
  Popup,
  showToast
} from 'vant';
import banner from './images/banner.png';
import iconSchool from './images/icon-school.png';
import iconTips from './images/icon-tips.png';
import bannerPopup from './images/banner-popup.png';
import MSticky from '@/components/m-sticky';
import MProtocol from '@/components/m-protocol';
import { useRoute, useRouter } from 'vue-router';
import request from '@/helpers/request';
import { checkPhone } from '@/helpers/utils';
import { EShoolStaffType } from '@/helpers/constant';
import MImgCode from '@/components/m-img-code';

export default defineComponent({
  name: 'school-register',
  setup() {
    const route = useRoute();
    const router = useRouter();
    const forms = reactive({
      id: route.query.id,
      imgCodeStatus: false,
      type: (route.query.type || '') as string,
      username: '',
      nameReg: /^[\u4E00-\u9FA5]+$/,
      phone: '',
      isAgree: false,
      smsCode: '',
      registerStatus: false,
      countDownStatus: true,
      schoolDetail: {} as any,
      countDownTime: 1000 * 120, // 倒计时时间
      btnLoading: false
    });
    const countDownRef = ref();

    const getDetail = async () => {
      try {
        const { data } = await request.get('/api-web/open/school/cooperation', {
          params: {
            id: forms.id
          }
        });
        forms.schoolDetail = data || {};
      } catch {
        //
      }
    };

    const onSubmit = async () => {
      // console.log(forms.isAgree, 'forms.isAgree');
      // if (!forms.isAgree) {
      //   showToast('请阅读并同意注册协议');
      //   return;
      // }
      if (!forms.username) {
        showToast('请输入真实姓名');
        return;
      }
      if (!forms.nameReg.test(forms.username)) {
        showToast('姓名必须为中文');
        return;
      }
      if (!checkPhone(forms.phone)) {
        showToast('请输入正确的手机号');
        return;
      }

      if (!forms.smsCode) {
        showToast('请输入验证码');
        return;
      }

      try {
        forms.btnLoading = true;
        const res = await request.post('/api-web/open/school/staffSave', {
          // hideLoading: false,
          data: {
            schoolId: forms.id,
            userType: forms.type,
            username: forms.username,
            mobile: forms.phone,
            smsCode: forms.smsCode
          }
        });
        if (res.code === 999) {
          setTimeout(() => {
            showToast('您已注册');
            // router.push('/download');
          }, 100);
        } else {
          forms.registerStatus = true;
        }
      } catch {
        //
      } finally {
        forms.btnLoading = false;
      }
    };

    const onDownload = () => {
      forms.registerStatus = false;
      router.push('/download');
    };

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

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

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

    onMounted(() => {
      if (!forms.id) {
        showToast('链接有误');
        return;
      }
      document.title = EShoolStaffType[forms.type] + '注册';

      getDetail();
    });
    return () => (
      <div class={styles['school-register']}>
        <div class={styles.banner}>
          <img src={banner} alt="banner" />
          <div class={styles.bannerContainer}>
            <div class={styles.bannerTitle}>
              {EShoolStaffType[forms.type]}注册
            </div>
            <div class={styles.bannerSchool}>
              <img src={iconSchool} class={styles.iconSchool} />
              <p class={styles.schoolName}>
                {forms.schoolDetail?.cooperation?.name}
              </p>
            </div>
          </div>
        </div>

        <CellGroup inset>
          <Field
            labelAlign="top"
            class="border"
            v-model={forms.username}
            placeholder="请填写您的真实姓名"
            autocomplete="off"
            maxlength={8}>
            {{
              label: () => (
                <>
                  真实姓名<i class={styles.required}>*</i>
                </>
              )
            }}
          </Field>
          <Field
            labelAlign="top"
            v-model={forms.phone}
            placeholder="请填写您的手机号码"
            autocomplete="off"
            maxlength={11}>
            {{
              label: () => (
                <>
                  手机号码<i class={styles.required}>*</i>
                </>
              )
            }}
          </Field>

          <Cell border={false}>
            <div class={styles.tips}>
              <img src={iconTips} class={styles.iconTips} />
              提示：手机号码将成为您管乐迷管理端登录账户
            </div>
          </Cell>
          <Field
            labelAlign="top"
            class="border"
            v-model={forms.smsCode}
            placeholder="请输入验证码"
            autocomplete="off"
            maxlength={6}>
            {{
              label: () => (
                <>
                  验证码<i class={styles.required}>*</i>
                </>
              ),
              button: () =>
                forms.countDownStatus ? (
                  <span class={styles.codeText} onClick={onSendCode}>
                    获取验证码
                  </span>
                ) : (
                  <CountDown
                    ref={(e: any) => (countDownRef.value = e)}
                    auto-start={false}
                    time={forms.countDownTime}
                    onFinish={onFinished}
                    format="ss秒"
                  />
                )
            }}
          </Field>
        </CellGroup>

        {/* <MSticky position="bottom"> */}
        {/* <MProtocol
            style={{ textAlign: 'center' }}
            v-model:modelValue={forms.isAgree}
          /> */}
        <div
          class={['btnGroupFixed']}
          style={{
            'margin-top': '18px'
          }}>
          <Button
            round
            block
            type="primary"
            onClick={onSubmit}
            disabled={forms.btnLoading}
            loading={forms.btnLoading}>
            提交
          </Button>
        </div>
        {/* </MSticky> */}

        <Popup
          v-model:show={forms.registerStatus}
          class={styles.popup}
          closeOnClickOverlay={false}>
          <div class={styles.popupContainer}>
            <img src={bannerPopup} class={styles.bannerPopup} />
            <h3>注册成功</h3>
            <div class={styles.popupContent}>
              恭喜您在{forms.schoolDetail?.cooperation?.name}成功注册为
              <span>【{EShoolStaffType[forms.type]}】</span>
              {/* ，请下载管乐迷管理端App进行乐团管理吧～ */}
            </div>

            {/* <Button
              type="primary"
              round
              class={styles.popupBtn}
              onClick={onDownload}>
              立即下载
            </Button> */}
          </div>
        </Popup>

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