import {
  Tag,
  Button,
  Popup,
  Form,
  Field,
  RadioGroup,
  Radio,
  showToast,
  CountDown,
  Area,
  Picker
} from 'vant';
import {
  computed,
  defineComponent,
  nextTick,
  onBeforeMount,
  onMounted,
  onUnmounted,
  reactive,
  ref,
  watch
} from 'vue';
import styles from './new-index.module.less';
import MSticky from '@/components/m-sticky';
// import MVideo from '@/components/m-video';
import { useRoute, useRouter } from 'vue-router';
import request from '@/helpers/request';
import loginSuccess from './images/login-success.png';
import bannerBg from './images/banner1.png';

import SelectStudent from '@/views/student-register/modal/select-student';
import { checkPhone } from '@/helpers/utils';
import MImgCode from '@/components/m-img-code';
import { api_sysAreaQueryAllProvince } from '@/views/school-register/api';
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 countDownRef = ref();
    const forms = reactive({
      statusShow: false,
      countDownStatus: true,
      countDownTime: 1000 * 120, // 倒计时时间
      // modelValue: false, // 是否选中协议
      imgCodeStatus: false,
      submitLoading: false,
      schoolName: '',
      areaName: '',
      schoolAreaId: null, // 学校区域编号
      gradeNumText: '',
      currentClassText: '',
      gradeStatus: false,
      classStatus: false,

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

      showPicker: false,
      areaList: [] as any,
      gradeList: [] as any,
      classList: [] as any,
      gradePopupShow: false,
      gradePopupIndex: [] as any, // 年级下拉索引
      classPopupShow: false,
      classPopupIndex: [] as any, // 班级下拉索引
      registerFlag: false // 是否全部登记
    });

    const studentInfo = reactive({
      phone: '',
      password: '',
      nickname: '',
      currentGradeNum: '' as any,
      currentClass: '' as any,
      gender: 1 as any
    });

    const btnText = computed(() => {
      if (forms.registerFlag) {
        return '已登记';
      }
      return '登记';
    });

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

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

    const validatePhone = computed(() => {
      return checkPhone(studentInfo.phone) ? true : false;
    });

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

    const getUserInfos = async () => {
      if (studentInfo.password.length !== 6 || !checkPhone(studentInfo.phone)) {
        return;
      }
      try {
        const { data } = await request.get(
          `/edu-app/open/instrumentRegister/recordQuery?phone=${studentInfo.phone}&code=${studentInfo.password}`
        );
        if (data?.id) {
          forms.registerFlag = true;
        }
      } catch {
        //
      }
    };

    const phoneChangeEmptyInfo = () => {
      studentInfo.password = '';
    };

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

    const onSubmit = async () => {
      forms.submitLoading = true;
      try {
        if (checkForm()) {
          forms.submitLoading = false;
          return;
        }
        await request.post('/edu-app/open/instrumentRegister/save', {
          data: {
            phone: studentInfo.phone,
            name: studentInfo.nickname,
            gender: studentInfo.gender,
            schoolAreaId: forms.schoolAreaId,
            currentGradeNum: studentInfo.currentGradeNum,
            currentClass: studentInfo.currentClass,
            code: studentInfo.password
          }
        });

        forms.statusShow = true;
      } catch {}
      forms.submitLoading = 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/open/schoolArea/list', {
          data: {
            name,
            testFlag: true,
            provinceCode: forms.provinceCode,
            cityCode: forms.cityCode,
            regionCode: forms.regionCode
          }
        });
        forms.schoolAreaList = data;
      } catch {
        //
      }
      forms.schoolLoading = false;
    };

    watch(
      () => [
        studentInfo.phone,
        studentInfo.nickname,
        studentInfo.gender,
        forms.schoolAreaId,
        forms.gradeNumText,
        forms.schoolName,
        forms.areaName,
        forms.provinceCode,
        forms.cityCode,
        forms.regionCode,
        forms.currentClassText,
        studentInfo.currentGradeNum,
        studentInfo.currentClass
      ],
      () => {
        // 缓存数据到 localStorage
        localStorage.setItem(
          'activationRegistration-form',
          JSON.stringify({
            phone: studentInfo.phone,
            name: studentInfo.nickname,
            gender: studentInfo.gender,
            schoolAreaId: forms.schoolAreaId,
            gradeNumText: forms.gradeNumText,
            schoolName: forms.schoolName,
            areaName: forms.areaName,
            provinceCode: forms.provinceCode,
            cityCode: forms.cityCode,
            regionCode: forms.regionCode,
            currentClassText: forms.currentClassText,
            currentGradeNum: studentInfo.currentGradeNum,
            currentClass: studentInfo.currentClass
          })
        );
      }
    );

    onMounted(() => {
      forms.gradeList = getGradeList();
      forms.classList = classList;
      getAreaList();

      let localForm: any = localStorage.getItem('activationRegistration-form');
      if (localForm) {
        localForm = JSON.parse(localForm);

        studentInfo.phone = localForm.phone;
        studentInfo.nickname = localForm.name;
        studentInfo.gender = localForm.gender;
        forms.schoolAreaId = localForm.schoolAreaId;
        forms.gradeNumText = localForm.gradeNumText;
        forms.schoolName = localForm.schoolName;
        forms.areaName = localForm.areaName;
        forms.provinceCode = localForm.provinceCode;
        forms.cityCode = localForm.cityCode;
        forms.regionCode = localForm.regionCode;
        forms.currentClassText = localForm.currentClassText;
        studentInfo.currentGradeNum = localForm.currentGradeNum;
        studentInfo.currentClass = localForm.currentClass;

        if (forms.cityCode && forms.regionCode && forms.provinceCode) {
          getSchoolAreaList();
        }
      }
    });

    return () => (
      <div class={[styles['student-register']]}>
        <img src={bannerBg} class={styles.bannerBg} />
        <div class={styles.studentRegisterContainer}>
          <div class={[styles.studentSection]}>
            <Form labelAlign="left" class={styles.registerForm}>
              <Field
                clearable={false}
                required
                inputAlign="right"
                label="学生姓名"
                placeholder="请输入学生姓名"
                autocomplete="off"
                maxlength={14}
                v-model={studentInfo.nickname}></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.gender}
                      direction="horizontal">
                      <Tag
                        size="large"
                        type="primary"
                        color={
                          !(studentInfo.gender === 1)
                            ? '#F5F6FA'
                            : 'linear-gradient( 135deg, #31C7FF 0%, #007AFE 100%)'
                        }
                        textColor={
                          !(studentInfo.gender === 1) ? '#626264' : '#fff'
                        }
                        class={styles.radioSection}>
                        <Radio class={styles.radioItem} name={1}></Radio>男
                      </Tag>
                      <Tag
                        size="large"
                        type="primary"
                        color={
                          !(studentInfo.gender === 0)
                            ? '#F5F6FA'
                            : 'linear-gradient( 135deg, #31C7FF 0%, #007AFE 100%)'
                        }
                        textColor={
                          !(studentInfo.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.areaName}
                onClick={() => {
                  forms.showPicker = true;
                  forms.areaPopupIndex =
                    forms.regionCode || forms.cityCode || forms.provinceCode;
                }}
              />
              <Field
                clearable={false}
                required
                inputAlign="right"
                label="互通学校"
                placeholder="请选择互通学校"
                isLink
                readonly
                clickable={false}
                modelValue={forms.schoolName}
                onClick={() => {
                  if (!forms.areaName) {
                    showToast('请选择地区');
                    return;
                  }

                  if (forms.schoolAreaId) {
                    forms.schoolPopupIndex = [forms.schoolAreaId];
                  }
                  forms.schoolStatus = true;
                }}
              />
              <Field
                clearable={false}
                required
                inputAlign="right"
                label="所在年级"
                placeholder="请选择年级"
                readonly
                isLink
                clickable={false}
                modelValue={forms.gradeNumText}
                onClick={() => {
                  forms.gradePopupIndex = [studentInfo.currentGradeNum];
                  forms.gradeStatus = true;
                }}
              />
              <Field
                clearable={false}
                required
                inputAlign="right"
                label="所在班级"
                placeholder="请选择班级"
                readonly
                isLink
                clickable={false}
                modelValue={forms.currentClassText}
                onClick={() => {
                  forms.classPopupIndex = [studentInfo.currentClass];
                  forms.classStatus = true;
                }}
              />

              <Field
                clearable={false}
                label="联系方式"
                placeholder="请输入手机号码"
                type="digit"
                required
                autocomplete="off"
                inputAlign="right"
                v-model={studentInfo.phone}
                maxlength={11}
                onUpdate:modelValue={() => {
                  forms.registerFlag = false;

                  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>
            </Form>
          </div>

          <MSticky position="bottom">
            <div class={styles.paymentContainer}>
              <Button
                onClick={() => {
                  onSubmit();
                }}
                round
                block
                disabled={forms.submitLoading || forms.registerFlag}
                loading={forms.submitLoading}>
                {btnText.value}
              </Button>
            </div>
          </MSticky>
        </div>

        {/* 互通学校 */}
        <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.schoolPopupIndex}
                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 = selectedOption.schoolId || null;
                  forms.schoolAreaId = selectedOption.id;
                  forms.schoolName = selectedOption.name;
                  forms.schoolStatus = false;

                  // forms.gradeNumText = '';
                  // studentInfo.extra.currentGradeNum = null;
                  // forms.currentClassText = '';
                  // studentInfo.extra.currentClass = null;
                  // getSchoolAreaDetail();
                }}>
                {{
                  '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.currentGradeNum = selectedOption.value;
                forms.gradeNumText = selectedOption.text;
                forms.gradeStatus = false;
              }}
            />
          )}
        </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.currentClass = selectedOption.value;
                forms.currentClassText = selectedOption.text;
                forms.classStatus = false;
              }}
            />
          )}
        </Popup>
        <Popup
          v-model:show={forms.showPicker}
          position="bottom"
          round
          class={'popupBottomSearch'}>
          <Area
            v-model={forms.areaPopupIndex}
            areaList={forms.areaList}
            onCancel={() => (forms.showPicker = false)}
            onConfirm={({ selectedOptions }) => {
              forms.provinceCode = selectedOptions[0].value;
              forms.cityCode = selectedOptions[1].value;
              forms.regionCode = selectedOptions[2]?.value;
              forms.areaName = selectedOptions
                .map((item: any) => item?.text)
                .join(' ');
              forms.showPicker = false;
              // forms.schoolId = null;
              forms.schoolAreaId = null;
              forms.schoolName = '';
              getSchoolAreaList();
            }}
          />
        </Popup>
        {/* <Popup
          v-model:show={forms.showSelectStudent}
          round
          position="bottom"
          safeAreaInsetBottom
          closeable>
          <SelectStudent
            showAdd={false}
            studentItem={forms.studentItem}
            list={forms.studentList}
            onClose={() => (forms.showSelectStudent = false)}
            onConfirm={(val: any) => {
              console.log(val, 'val');
              formatData(val);
              forms.studentItem = val;
            }}
          />
        </Popup> */}

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

        <Popup
          show={forms.statusShow}
          style={{
            background: 'transparent',
            overflow: 'visible !important'
          }}>
          <div class={styles.popupContainer}>
            {/* <img class={styles.title} src={loginSuccess} /> */}

            <div class={styles.content} style={{ textAlign: 'center' }}>
              乐器的实际发放将以
              <span>
                最终的
                <br />
                审核结果
              </span>
              为准。
            </div>
            <div class={styles.pBtnGroup}>
              <div
                class={styles.btnSubmit}
                onClick={() => {
                  forms.registerFlag = true;
                  forms.statusShow = false;
                }}></div>
            </div>
          </div>
        </Popup>
      </div>
    );
  }
});
