import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import MHeader from '@/components/m-header';
import { Area, Button, CellGroup, Field, Form, Popup, showToast } from 'vant';
import icon_school from './images/icon_school.png';
import icon_person from './images/icon_person.png';
import icon_submit from './images/icon_submit.png';
import icon_logo from './images/logo.png';
import icon_p1 from './images/icon_p1.png';
import icons from './images/icons.json';
import {
  api_openSendSms,
  api_schoolAdd,
  api_schoolSave,
  api_sysAreaQueryAllProvince
} from './api';
import { useRoute } from 'vue-router';
import MImgCode from '@/components/m-img-code';
import { browser } from '@/helpers/utils';

export default defineComponent({
  name: 'SchoolRegister',
  setup() {
    const route = useRoute();
    const browserInfo = browser();
    const formOptions = {
      /** 性质 */
      nature: [
        { label: '公立', value: 'PUBLIC' },
        { label: '私立', value: 'PRIVATE' }
      ],
      types: [
        { label: '小学', value: 'PRIMARY' },
        { label: '初中', value: 'JUNIOR' },
        { label: '小初一体', value: 'PRIMARY_JUNIOR' }
      ],
      grades: [
        { label: '六年制', value: 'SIX_YEAR_SYSTEM' },
        { label: '五年制', value: 'FIVE_YEAR_SYSTEM' }
      ],
      grades1: [
        { label: '三年制', value: 'THREE_YEAR_SYSTEM' },
        { label: '四年制', value: 'FORE_YEAR_SYSTEM' }
      ],
      genaral: [
        { label: '男', value: '1' },
        { label: '女', value: '0' }
      ]
    };
    const forms = reactive({
      id: '',
      name: '', // 学校名称
      regionCode: '', // 所属区域
      cityCode: '', // 所属城市
      provinceCode: '', // 所属省份
      schoolNature: 'PUBLIC' as 'PUBLIC' | 'PRIVATE' | string, // 学校性质
      schoolType: 'PRIMARY' as 'PRIMARY' | 'JUNIOR' | 'PRIMARY_JUNIOR' | string, // 学校类型
      gradeYear: 'SIX_YEAR_SYSTEM' as
        | 'FIVE_YEAR_SYSTEM'
        | 'SIX_YEAR_SYSTEM'
        | string, // 学年制
      emergencyContact: '', // 校长姓名
      emergencyContactPhone: '', // 校长联系方式
      educationalAdministrationUsername: '', // 负责人姓名
      educationalAdministrationPhone: '', // 负责人联系方式
      genaral: '1', // 性别
      code: '', // 验证码
      buyGoods: true, // 是否购买商品
      tenantId: route.query.id || '', // 机构
      sourceForm: 'TEACHER'
    });
    const data = reactive({
      cityName: '', // 所属城市
      showArea: false,
      success: false,
      areaList: {} as any,
      sendMsg: '发送验证码',
      imgCodeStatus: false,

      inputFouce: 0
    });
    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);
          console.log('🚀 ~ data.areaList:', data.areaList);
        }
      });
    };
    onMounted(() => {
      getAreaList();
    });
    /** 发送验证码 */
    const onSendSms = async () => {
      if (data.sendMsg.includes('s')) return;
      onCountDown();
      showToast('验证码已发送');
    };
    const onCountDown = () => {
      data.sendMsg = '60s';
      let count = 60;
      let timer = setInterval(() => {
        count--;
        data.sendMsg = `${count}s`;
        if (count <= 0) {
          data.sendMsg = '重新发送';
          clearInterval(timer);
        }
      }, 1000);
    };
    const formRef = ref();
    const handleSubmit = () => {
      forms.name = forms.name.trim();
      formRef.value
        .validate()
        .then(async () => {
          if (!forms.code) {
            showToast('请输入验证码');
            return;
          }
          const res = await api_schoolSave({ ...forms });
          if (res?.code === 200) {
            if (res?.data?.id) {
              forms.id = res.data.id;
            }
            data.success = true;
          }
        })
        .catch((err: any) => {
          console.log('🚀 ~ err:', err);
          formRef.value.scrollToField(err[0].name);
        });
      return;
    };
    return () => (
      <div class={styles.container}>
        <div class={styles.containerBg}>
          <img class={styles.titleIcon} src={icon_logo} />
          <div class={styles.title}>{route.query.name}</div>
          <div class={styles.tagWrap}>
            <div class={styles.tag}>
              <span>·</span> 音乐数字课堂学校登记 <span>·</span>
            </div>
          </div>

          <div class={styles.contentWrap}>
            <div class={styles.content}>
              <Form ref={formRef}>
                <CellGroup class={styles.group}>
                  <img src={icon_school} class={styles.icon} />
                  <Field
                    border
                    name="name"
                    label="学校全称"
                    rows="1"
                    autosize
                    // type="textarea"
                    placeholder="请输入学校全称"
                    inputAlign="right"
                    v-model={forms.name}
                    onUpdate:modelValue={(val: string) => {
                      forms.name = val.trim();
                    }}
                    autocomplete="off"
                    maxlength={20}
                    rules={[
                      {
                        required: true,
                        message: '请输入学校全称',
                        trigger: 'onBlur'
                      }
                    ]}
                    onFocus={() => {
                      data.inputFouce++;
                    }}
                  />
                  <Field
                    isLink
                    border
                    name="cityName"
                    label="所属城市"
                    placeholder="请选择"
                    readonly
                    inputAlign="right"
                    v-model={data.cityName}
                    onClick={() => {
                      if (browserInfo.ios && data.inputFouce < 2) {
                        data.inputFouce++;
                        setTimeout(() => {
                          data.showArea = true;
                        }, 700);
                      } else {
                        data.showArea = true;
                      }
                    }}
                    rules={[{ required: true, message: '请选择' }]}></Field>
                  <Field center border name="schoolNature" label="办学性质">
                    {{
                      input: () => (
                        <>
                          {formOptions.nature.map(item => {
                            return (
                              <Button
                                class={styles.radio}
                                size="small"
                                color={
                                  item.value === forms.schoolNature
                                    ? '#198CFE'
                                    : ''
                                }
                                onClick={() =>
                                  (forms.schoolNature = item.value)
                                }>
                                {item.label}
                              </Button>
                            );
                          })}
                        </>
                      )
                    }}
                  </Field>

                  <Field center border label="学校类型" labelWidth="70px">
                    {{
                      input: () => (
                        <>
                          {formOptions.types.map(item => {
                            return (
                              <Button
                                class={styles.radio}
                                size="small"
                                color={
                                  item.value === forms.schoolType
                                    ? '#198CFE'
                                    : ''
                                }
                                onClick={() => {
                                  forms.schoolType = item.value;
                                  forms.gradeYear =
                                    item.value === 'PRIMARY_JUNIOR'
                                      ? 'NINE_YEAR_SYSTEM'
                                      : item.value === 'JUNIOR'
                                      ? 'THREE_YEAR_SYSTEM'
                                      : 'SIX_YEAR_SYSTEM';
                                }}>
                                {item.label}
                              </Button>
                            );
                          })}
                        </>
                      )
                    }}
                  </Field>

                  {forms.schoolType ===
                  'PRIMARY_JUNIOR' ? null : forms.schoolType === 'JUNIOR' ? (
                    <Field center border label="学年制">
                      {{
                        input: () => (
                          <>
                            {formOptions.grades1.map(item => {
                              return (
                                <Button
                                  class={styles.radio}
                                  size="small"
                                  color={
                                    item.value === forms.gradeYear
                                      ? '#198CFE'
                                      : ''
                                  }
                                  onClick={() =>
                                    (forms.gradeYear = item.value)
                                  }>
                                  {item.label}
                                </Button>
                              );
                            })}
                          </>
                        )
                      }}
                    </Field>
                  ) : (
                    <Field center border label="学年制">
                      {{
                        input: () => (
                          <>
                            {formOptions.grades.map(item => {
                              return (
                                <Button
                                  class={styles.radio}
                                  size="small"
                                  color={
                                    item.value === forms.gradeYear
                                      ? '#198CFE'
                                      : ''
                                  }
                                  onClick={() =>
                                    (forms.gradeYear = item.value)
                                  }>
                                  {item.label}
                                </Button>
                              );
                            })}
                          </>
                        )
                      }}
                    </Field>
                  )}
                </CellGroup>

                <CellGroup class={styles.group}>
                  <img src={icon_person} class={styles.icon} />
                  <Field
                    border
                    name="emergencyContact"
                    label="校长姓名"
                    placeholder="请输入校长姓名"
                    inputAlign="right"
                    maxlength={14}
                    v-model={forms.emergencyContact}
                    onUpdate:modelValue={(val: string) => {
                      forms.emergencyContact = val.trim();
                    }}
                    rules={[{ required: true, message: '请输入校长姓名' }]}
                  />
                  <Field
                    border
                    name="emergencyContactPhone"
                    label="校长联系方式"
                    maxlength={11}
                    placeholder="请输入校长手机号码"
                    inputAlign="right"
                    v-model={forms.emergencyContactPhone}
                    rules={[
                      { required: true, message: '请输入校长手机号码' },
                      {
                        pattern: /^1[3456789]\d{9}$/,
                        message: '请输入正确的手机号码'
                      }
                    ]}
                  />
                  <Field
                    border
                    name="educationalAdministrationUsername"
                    label="负责人姓名"
                    placeholder="请输入负责人姓名"
                    inputAlign="right"
                    maxlength={14}
                    v-model={forms.educationalAdministrationUsername}
                    onUpdate:modelValue={(val: string) => {
                      forms.educationalAdministrationUsername = val.trim();
                    }}
                    rules={[
                      {
                        required: true,
                        message: '请输入负责人姓名',
                        trigger: 'onBlur'
                      }
                    ]}
                  />
                  <Field
                    border
                    name="educationalAdministrationPhone"
                    label="负责人联系方式"
                    labelWidth="40%"
                    inputAlign="right"
                    placeholder="请输入负责人手机号码"
                    maxlength={11}
                    v-model={forms.educationalAdministrationPhone}
                    rules={[
                      { required: true, message: '请输入负责人手机号码' },
                      {
                        pattern: /^1[3456789]\d{9}$/,
                        message: '请输入正确的手机号码'
                      }
                    ]}
                  />
                  <Field center border label="性别">
                    {{
                      input: () => (
                        <>
                          {formOptions.genaral.map(item => {
                            return (
                              <Button
                                class={styles.radio}
                                size="small"
                                color={
                                  item.value === forms.genaral ? '#198CFE' : ''
                                }
                                onClick={() => (forms.genaral = item.value)}>
                                {item.label}
                              </Button>
                            );
                          })}
                        </>
                      )
                    }}
                  </Field>
                  <Field
                    class={styles.codeWrap}
                    center
                    border
                    name="code"
                    label="验证码"
                    labelWidth={70}
                    placeholder="请输入验证码"
                    v-model={forms.code}
                    onUpdate:modelValue={(val: string) => {
                      forms.code = val.trim();
                    }}
                    maxlength={6}>
                    {{
                      button: () => (
                        <Button
                          disabled={data.sendMsg.includes('s')}
                          class={styles.sendBtn}
                          size="small"
                          type="primary"
                          color="#198CFE"
                          onClick={() => {
                            if (!forms.educationalAdministrationPhone) {
                              showToast('请输入负责人手机号码');
                              return;
                            }
                            if (
                              !/^1[3456789]\d{9}$/.test(
                                forms.educationalAdministrationPhone
                              )
                            ) {
                              showToast('手机号码格式不正确');
                              return;
                            }
                            data.imgCodeStatus = true;
                          }}>
                          {data.sendMsg}
                        </Button>
                      )
                    }}
                  </Field>
                  <div style={{ padding: '10px 16px' }}>
                    <div class={styles.tips}>
                      负责人即为该学校音乐数字课堂老师端管理员，手机号即为音乐数字课堂老师端账号，默认密码为：yyszkt+手机号后四位
                    </div>
                  </div>
                </CellGroup>

                <Button
                  class={styles.submit}
                  round
                  block
                  onClick={() => handleSubmit()}>
                  <img class={styles.submitIcon} src={icon_submit} />
                </Button>
              </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
                class="popup-custom van-scale"
                transition="van-scale"
                closeOnClickOverlay={false}
                v-model:show={data.success}>
                <div class={styles.successWrap}>
                  <img class={styles.p1} src={icon_p1} />
                  <img class={styles.p2} src={icons.icon_p2} />
                  <div class={styles.btnWrap}>
                    <div class={styles.btnTitle}>您已成功登记</div>
                    <div class={styles.btnDes}>欢迎您使用音乐数字课堂～</div>
                    <Button
                      class={styles.btn}
                      type="primary"
                      round
                      onClick={() => (data.success = false)}>
                      我知道了
                    </Button>
                  </div>
                </div>
              </Popup>

              {data.imgCodeStatus ? (
                <MImgCode
                  v-model:value={data.imgCodeStatus}
                  clientId="cooleshow-teacher"
                  phone={forms.educationalAdministrationPhone}
                  onClose={() => {
                    data.imgCodeStatus = false;
                  }}
                  onSendCode={onSendSms}
                />
              ) : null}
            </div>
          </div>
        </div>
      </div>
    );
  }
});
