import { defineComponent, onMounted, onUnmounted, reactive, ref } from 'vue';
import styles from './index.module.less';
// import signinTips from './images/signin-tips.png';
import {
  Button,
  CellGroup,
  Field,
  Picker,
  Popup,
  closeToast,
  showToast
} from 'vant';
import { useRoute, useRouter } from 'vue-router';
import threeMan from './images/update/three-man.png'
import OWxTip from '@/components/m-wx-tip';
import { browser, getHttpOrigin, getUrlCode } from '@/helpers/utils';
import qs from 'query-string';
import request from '@/helpers/request';
import { goWechatAuth } from '@/state';
import { useInterval, useIntervalFn } from '@vueuse/core';
import MMessageTip from '@/components/m-message-tip';

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: 'pre-register',
  setup() {
    // 页面定时
    const pageTimer = useInterval(1000, { controls: true });
    pageTimer.pause();
    const router = useRouter();
    const route = useRoute();
    const forms = reactive({
      loading: true,
      schoolId: route.query.id,
      code: null,
      showPicker: false,
      classPicker: false,

      gradeStatus: false,
      classStatus: false,
      gradePopupShow: false,
      gradePopupIndex: [] as any, // 年级下拉索引
      classPopupShow: false,
      classPopupIndex: [] as any, // 班级下拉索引
      gradeList: [] as any,
      classList: [] as any,
      schoolInstrumentSetType: null as any,
      nameReg: /^[\u4E00-\u9FA5]+$/,
      openId: '' as any,
      id: null,
      videoBrowseData: null,
      videoBrowsePoint: null,
      username: '',
      currentGrade: '', // 年级
      currentClass: '', // 班级
      intervalFnRef: null as any,
      applyStatus: false,
      isPageHide: false,
      parentConferencesAgenda: ''
    });

    const showPopup = ref(false);
    const showPopupMessage = ref('');

    const message = (value: string) => {
      if (!value) {
        return '请填写学生真实姓名';
      } else if (!forms.nameReg.test(value)) {
        return '学员姓名必须为中文';
      } else if (value.length < 2 || value.length > 15) {
        return '学员姓名必须为2~15个字';
      }
    };

    const onSubmit = async () => {
      try {
        if (forms.applyStatus) {
          showToast('家长会调查问卷已结束');
          return;
        }

        if (message(forms.username)) {
          showToast(message(forms.username));
          return;
        }

        if (!forms.currentGrade) {
          showToast('请选择年级');
          return;
        }

        if (!forms.currentClass) {
          showToast('请选择班级');
          return;
        }
        // 暂停回调
        forms.intervalFnRef?.pause();
        // 页面计时暂停
        pageTimer.pause();
        await request.post('/edu-app/open/studentBrowseRecord/updateStat', {
          data: {
            id: forms.id,
            pageBrowseTime: pageTimer.counter.value,
            username: forms.username,
            currentGrade: forms.currentGrade,
            currentClass: forms.currentClass ? Number(forms.currentClass) : null
          }
        });

        router.push({
          path: '/pre-register-video',
          query: {
            saveId: forms.id,
            id: forms.schoolId, // 乐团编号
            openId: forms.openId //
          }
        });
      } catch {
        // 还原
        forms.intervalFnRef?.resume();
        pageTimer.resume();
      }
      // router.push('/pre-register-video')
    };

    const formatterClass = (value: any, list: any[]) => {
      let txt = '';
      list.forEach((listItem: any) => {
        if (listItem.value == value) {
          txt = listItem.text;
        }
      });
      return txt;
    };

    // 更新时间
    const updateStat = async (pageBrowseTime = 10) => {
      try {
        await request.post('/edu-app/open/studentBrowseRecord/updateStat', {
          data: {
            id: forms.id,
            pageBrowseTime // 固定10秒
          }
        });
      } catch {
        //
      }
    };

    onMounted(async () => {
      try {
        if (!forms.schoolId) {
          showToast('信息获取失败，请联系老师');
        }
        const { data } = await request.get(
          '/edu-app/open/schoolExtend/detail?id=' + forms.schoolId
        );
        const schoolExtend = data.schoolExtend;
        forms.parentConferencesAgenda = schoolExtend.parentConferencesAgenda;
        forms.schoolInstrumentSetType = data.school?.instrumentSetType;
        const schoolInstrumentList = data.school?.schoolInstrumentList || [];
        if (forms.schoolInstrumentSetType === 'SCHOOL') {
          const instrumentCode = schoolInstrumentList[0]?.instrumentCode;
          forms.gradeList = getGradeList(data.school?.gradeYear, instrumentCode);
          forms.classList = classList;
        } else if (forms.schoolInstrumentSetType === 'GRADE') {
          schoolInstrumentList.forEach((item: any) => {
            forms.gradeList.push({
              text: GRADE_ENUM[item.gradeNum],
              value: item.gradeNum,
              instrumentId: item.instrumentId,
              instrumentCode: item.instrumentCode
            });
          });
          forms.gradeList.sort((a: any, b: any) => a.value - b.value);
          forms.classList = classList;
        } else if (forms.schoolInstrumentSetType === 'CLASS') {
          // 班级
          const tempGradeList: any[] = [];
          schoolInstrumentList.forEach((item: any) => {
            if (!tempGradeList.includes(item.gradeNum)) {
              tempGradeList.push(item.gradeNum);
            }
          });

          const lastGradeList: any[] = [];
          tempGradeList.forEach((temp: any) => {
            const list = {
              text: GRADE_ENUM[temp],
              value: temp,
              instrumentId: '',
              instrumentCode: '',
              instrumentName: '',
              classList: [] as any
            };
            schoolInstrumentList.forEach((item: any) => {
              if (temp === item.gradeNum) {
                list.instrumentId = item.instrumentId;
                list.instrumentCode = item.instrumentCode;
                list.instrumentName = item.instrumentName;
                list.classList.push({
                  text: item.classNum + '班',
                  value: item.classNum,
                  instrumentCode: item.instrumentCode
                });
              }
            });
            // 排序班级
            list.classList.sort((a: any, b: any) => a.value - b.value);
            lastGradeList.push(list);
          });
          lastGradeList.sort((a: any, b: any) => a.value - b.value);
          forms.gradeList = lastGradeList;
          forms.classList = [];
        } else {
          forms.gradeList = getGradeList(data.school.gradeYear);
          forms.classList = classList;
        }
        // 判断是否获取微信code码
        if (!forms.code) return;

        // // 乐团注册
        // if (data.status !== 'PRE_REGISTER') {
        //   showToast('家长会调查问卷已结束')
        //   forms.applyStatus = true
        //   return
        // }

        // 家长会注册
        // 'DOING' | 'DONE'
        // if (
        //   data.orchestraRegisterType === 'PARENT_CONFERENCES' &&
        //   data.status !== 'PARENT_TEACHER_REGISTRATION' &&
        //   data.status !== 'DOING' &&
        //   data.status !== 'DONE'
        // ) {
        //   showToast('家长会调查问卷已结束')
        //   forms.applyStatus = true
        //   return
        // }

        // if (!forms.schoolId) {
        //   // 提示乐团报名失败
        //   showPopupMessage.value = '二维码已过期';
        //   showPopup.value = true;
        //   return;
        // }

        const recordAdd = await request.post(
          '/edu-app/open/studentBrowseRecord/add',
          {
            data: {
              schoolId: forms.schoolId,
              code: forms.code,
              openId: forms.openId
            }
          }
        );
        const recordObj = recordAdd.data;
        forms.currentClass = recordObj.currentClass;
        forms.currentGrade = recordObj.currentGrade;
        forms.openId = recordObj.openId;
        forms.username = recordObj.username;
        forms.videoBrowseData = recordObj.videoBrowseData;
        forms.videoBrowsePoint = recordObj.videoBrowsePoint;
        forms.id = recordObj.id;

        sessionStorage.setItem('active-open-id', recordObj.openId);


        console.log(forms, 'forms')

        pageTimer.resume();
        // 间隔10秒更新停留时间
        forms.intervalFnRef = useIntervalFn(() => {
          // 页面时间恢复
          pageTimer.counter.value = 0;
          pageTimer.resume();
          updateStat();
        }, 10000);
      } catch {
        //
      }
    });

    const getAppIdAndCode = async (url?: string) => {
      try {
        const { data } = await request.get(
          '/edu-app/open/paramConfig/wechatAppId'
        );
        // 判断是否有微信appId
        if (data) {
          closeToast();
          goWechatAuth(data, url);
        }
      } catch(e) {
        //
        console.log(e)
      }
    };

    if (browser().weixin) {
      //授权
      const openId = sessionStorage.getItem('active-open-id');
      forms.openId = openId;
      const code = getUrlCode();
      console.log(code, 'code')
      if (!code) {
        const newUrl =
          getHttpOrigin() +
          window.location.pathname +
          '#' +
          route.path +
          '?' +
          qs.stringify({
            ...route.query
          });
        getAppIdAndCode(newUrl);
        return '';
      } else {
        forms.code = code;
      }
    }

    const onPageShow = () => {
      console.log(forms.isPageHide, 'showInfo');
      if (forms.isPageHide) {
        window.location.reload();
      }
    };
    // 处理监听页面返回不刷新的问题
    window.addEventListener('pageshow', onPageShow);

    const onPageHide = () => {
      console.log(forms.isPageHide, 'showInfo');
      forms.isPageHide = true;
    };
    window.addEventListener('pagehide', onPageHide);

    onUnmounted(() => {
      window.removeEventListener('pageshow', onPageShow);
      window.removeEventListener('pagehide', onPageHide);
    });
    return () => (
      <div class={styles['per-register-active']}>
        <img class={styles.imgMan} src={threeMan} />
        <div class={styles.flowPath}>
          <i class={styles.flowPathTitle}></i>
          <div
            class={styles.flowPathContent}
            v-html={forms.parentConferencesAgenda}></div>
        </div>

        <div class={styles.signin}>
          <i class={styles.signinTitle}></i>

          <CellGroup class={styles.cellGroup} border={false}>
            <Field
              label="学生姓名"
              required
              labelAlign="top"
              placeholder="请输入学生姓名"
              autocomplete="off"
              v-model={forms.username}
              border={false}
            />
            <Field
              label="年级"
              required
              labelAlign="top"
              placeholder="请选择年级"
              rightIcon={!forms.gradeStatus ? "arrow-down" : "arrow-up"}
              readonly
              border={false}
              modelValue={formatterClass(forms.currentGrade, forms.gradeList)}
              clickable={false}
              onClick={() => {
                forms.gradePopupIndex = [forms.currentGrade];
                forms.gradeStatus = true;
              }}
            />
            <Field
              label="班级"
              required
              labelAlign="top"
              placeholder="请选择班级"
              rightIcon={!forms.classStatus ? "arrow-down" : "arrow-up"}
              readonly
              border={false}
              modelValue={formatterClass(forms.currentClass, forms.classList)}
              clickable={false}
              onClick={() => {
                if (
                  forms.schoolInstrumentSetType === 'CLASS' &&
                  forms.classList.length <= 0
                ) {
                  showToast('请先选择年级');
                  return;
                }
                forms.classPopupIndex = [forms.currentClass];
                forms.classStatus = true;
              }}
            />

            <div class={styles.submitBtn} onClick={onSubmit}></div>
          </CellGroup>
        </div>

        {/* 是否在微信中打开 */}
        <OWxTip />

        {/* 年级 */}
        <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];
                forms.currentGrade = selectedOption.value;
                forms.gradeStatus = false;

                if (forms.schoolInstrumentSetType === 'CLASS') {
                  forms.classList = selectedOption.classList;
                }

                if (
                  ['CLASS', 'GRADE'].includes(forms.schoolInstrumentSetType)
                ) {
                  forms.currentClass = '';
                }
              }}
            />
          )}
        </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={({ selectedValues }) => {
                forms.currentClass = selectedValues[0];
                forms.classStatus = false;
              }}
            />
          )}
        </Popup>

        {/* <Popup
          v-model:show={showPopup.value}
          round
          style={{ width: '88%' }}
          closeOnClickOverlay={false}
          class={styles.wxPopupDialog}>
          <div class={styles.popupContainer}>
            <p class={styles.title}>温馨提示</p>
            <p class={styles.popupTips} v-html={showPopupMessage.value}></p>
          </div>
        </Popup> */}
        <MMessageTip show={showPopup.value} title='温馨提示' message={showPopupMessage.value} showCloseButton={false} showConfirmButton={false} />
      </div>
    );
  }
});
