import { defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import {
  Area,
  Button,
  CellGroup,
  Checkbox,
  Field,
  Form,
  Popup,
  showToast
} from 'vant';
import icon_title from './images/icon_title.png';
import icon_school from './images/icon_school.png';
import icon_logo from './images/logo.png';
import icon_man from './images/icon_man.png';
import icon_woman from './images/icon_woman.png';
import icon_toggle from './images/icon_toggle.png';
import icon_arrow from './images/icon_arrow.png';
import {
  api_openSendSms,
  api_teacherAdd,
  api_sysAreaQueryAllProvince
} from './api';
import { useRoute } from 'vue-router';
import { postMessage } from '@/helpers/native-message';
import Success from './component/success/index';

export default defineComponent({
  name: 'SchoolRegister',
  setup() {
    const route = useRoute();
    const forms = reactive({
      regionCode: '', // 所属区域
      cityCode: '', // 所属城市
      provinceCode: '', // 所属省份
      code: '', // 验证码
      tenantId: route.query.tenantId || '', // 机构
      phone: null,
      schoolId: route.query.schoolId || '', // 学校id
      nickname: null,
      gender: 1
    });
    const data = reactive({
      schoolName: route.query.schoolName || '',
      cityName: '', // 所属城市
      showArea: false,
      checked: true,
      success: false,
      areaList: {} as any,
      sendMsg: '获取验证码'
    });
    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) {
          data.areaList = formateArea(res.data);
        }
      });
    };
    onMounted(() => {
      getAreaList();
    });
    /** 发送验证码 */
    const onSendSms = async () => {
      if (!forms.phone) {
        showToast('请输入手机号码');
        return;
      }
      if (!/^1[3456789]\d{9}$/.test(forms.phone)) {
        showToast('手机号码格式不正确');
        return;
      }
      if (data.sendMsg.includes('s')) return;
      try {
        await api_openSendSms({
          clientId: 'cooleshow-student',
          type: 'REGISTER',
          mobile: forms.phone
        });
        onCountDown();
        showToast({
          message: '验证码发送成功',
          duration: 2000
        });
      } catch {
        data.sendMsg = '重新发送';
      }
    };
    const onCountDown = () => {
      data.sendMsg = '30s';
      let count = 30;
      let timer = setInterval(() => {
        count--;
        data.sendMsg = `${count}s`;
        if (count <= 0) {
          data.sendMsg = '重新发送';
          clearInterval(timer);
        }
      }, 1000);
    };
    const handleSubmit = async () => {
      if (!data.checked) {
        showToast('请勾选注册协议');
        return;
      }
      if (!forms.nickname) {
        showToast('请输入老师姓名');
        return;
      }
      if (!forms.phone) {
        showToast('请输入手机号码');
        return;
      }
      if (!/^1[3456789]\d{9}$/.test(forms.phone)) {
        showToast('手机号码格式不正确');
        return;
      }
      if (!forms.code) {
        showToast('请输入验证码');
        return;
      }
      if (!forms.provinceCode) {
        showToast('请选择城市');
        return;
      }
      const res = await api_teacherAdd({ ...forms });
      if (res?.code === 200) {
        data.success = true;
      }
    };
    return () => (
      <div class={styles.container}>
        <img class={styles.titleIcon} src={icon_logo} />
        <img
          class={styles.titleIcon}
          style={{ margin: '16Px auto', height: '32Px' }}
          src={icon_title}
        />
        <div class={styles.schoolName}>
          <img
            style={{
              width: '16px',
              height: '16px',
              marginRight: '8px',
              verticalAlign: 'middle'
            }}
            src={icon_school}
          />
          {data.schoolName}
        </div>
        <div class={styles.teacherIcon}>
          <img src={forms.gender === 1 ? icon_man : icon_woman} />
          <div
            class={styles.toggleBtn}
            onClick={() => (forms.gender = forms.gender === 1 ? 0 : 1)}>
            <span>{forms.gender === 1 ? '男老师' : '女老师'}</span>
            <img src={icon_toggle} />
          </div>
        </div>

        <div class={styles.contentWrap}>
          <div class={styles.content}>
            <Form onSubmit={() => handleSubmit()}>
              <CellGroup class={styles.group} border={false}>
                <Field
                  border={false}
                  labelWidth="0"
                  placeholder="请输入老师姓名"
                  maxlength={20}
                  v-model={forms.nickname}
                />
                <Field
                  border={false}
                  labelWidth="0"
                  maxlength={11}
                  placeholder="请输入手机号码"
                  v-model={forms.phone}
                />
                <div class={styles.tips}>
                  该手机号码即为酷乐秀课堂乐器老师端登录账号
                </div>
                <Field
                  class={styles.inputCode}
                  border={false}
                  labelWidth={0}
                  placeholder="请输入验证码"
                  v-model={forms.code}
                  maxlength={6}>
                  {{
                    button: () => (
                      <Button
                        disabled={data.sendMsg.includes('s')}
                        class={styles.sendBtn}
                        onClick={() => onSendSms()}>
                        {data.sendMsg}
                      </Button>
                    )
                  }}
                </Field>
                <Field
                  border={false}
                  labelWidth={0}
                  placeholder="请选择城市"
                  readonly
                  v-model={data.cityName}
                  onClick={() => (data.showArea = true)}>
                  {{
                    button: () => (
                      <img
                        style={{
                          display: 'block',
                          width: '8px',
                          height: '6px',
                          marginRight: '10px'
                        }}
                        src={icon_arrow}
                      />
                    )
                  }}
                </Field>
                <div class={styles.xieyiWrap}>
                  <Checkbox v-model={data.checked}>
                    <div class={styles.xieyi}>
                      <span>我已阅读并同意</span>
                      <span
                        style={{ color: '#1677FF' }}
                        onClick={(e: Event) => {
                          e.stopPropagation();
                          postMessage({
                            api: 'openWebView',
                            content: {
                              url: `${location.origin}${location.pathname}#/preview-protocol`,
                              orientation: 1,
                              isHideTitle: false
                            }
                          });
                        }}>
                        《酷乐秀课堂乐器学生端》
                      </span>
                      <span>注册协议</span>
                    </div>
                  </Checkbox>
                </div>
                <div class={styles.submit}>
                  <Button block native-type="submit">
                    注册
                  </Button>
                </div>
              </CellGroup>
            </Form>
            <Popup v-model:show={data.showArea} position="bottom">
              <Area
                areaList={data.areaList}
                onCancel={() => (data.showArea = 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('-');
                  data.showArea = false;
                }}
              />
            </Popup>

            <Popup
              style={{ margin: 0 }}
              class="popup-custom van-scale"
              transition="van-scale"
              closeOnClickOverlay={false}
              v-model:show={data.success}>
              <Success />
            </Popup>
          </div>
        </div>
      </div>
    );
  }
});
