import { defineComponent, onMounted, onUnmounted, reactive, ref, nextTick, computed } from 'vue';
import styles from './index.module.less';
import {
  Button,
  CellGroup,
  Field,
  Picker,
  Popup,
  closeToast,
  showToast,
  Loading,
  Form,
  CountDown,
  Cell,
  Area,
} 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, checkPhone } 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';
import MImgCode from '@/components/m-img-code';
import MSearch from '@/components/m-search';
import submitBtn from './images/submit_icon.png'
import signupBtn from './images/signup_icon.png'
import signSusIcon from './images/sign_icon.png'
import subSusIcon from './images/subsus_icon.png'
import doneIcon from './images/done_icon.png'
import { subscribe } from 'diagnostics_channel';
import { api_sysAreaQueryAllProvince } from '@/views/school-register/api';

export default defineComponent({
  name: 'fill-questionnaire',
  setup() {
    const router = useRouter();
    const route = useRoute();  

    const classList: any = [];
    for (let i = 1; i <= 40; i++) {
      classList.push({ text: i + '班', value: i });
    }
    const gradeList = route.query.meetingType === 'primarySchoolNo' || route.query.meetingType === 'primarySchoolYes' ? [
      {
        text: '一年级',
        value: 1
      },
      {
        text: '二年级',
        value: 2
      },
      {
        text: '三年级',
        value: 3
      },
      {
        text: '四年级',
        value: 4
      },
      {
        text: '五年级',
        value: 5
      },
      {
        text: '六年级',
        value: 6
      },
    ] : [
      {
        text: '六年级',
        value: 6
      },
      {
        text: '七年级',
        value: 7
      },
      {
        text: '八年级',
        value: 8
      },
      {
        text: '九年级',
        value: 9
      },
    ]

    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;
    };

    const countDownRef = ref();
    const forms = reactive({
      isPageHide: false,
      currentClassText: '',
      supportList: [
        {
          title: '支持',
          val: true
        },
        {
          title: '不支持',
          val: false
        }
      ],
      willingList: [
        {
          title: '愿意',
          val: true
        },
        {
          title: '不愿意',
          val: false
        }
      ],
      username: '',
      openId: null as any,
      participationFlag: null as any, // 是否愿意参加
      supportFlag: null as any, // 是否支持
      currentGrade: null as any,
      currentClass: null as any,
      provinceCode: '',
      cityCode: '',
      districtCode: '',
      phone: '',
      prePhone: '',
      smsCode: '',
      selectArea: '', // 所选地区
      selectSchool: '', // 所选学校
      selectClass: '',
      countDownStatus: true,
      countDownTime: 1000 * 120, // 倒计时时间
      imgCodeStatus: false,
      successPopShow: true, // 提交结果弹窗
      schoolStatus: false,
      schoolPopupShow: false,
      schoolLoading: false,
      schoolPopupIndex: [] as any,
      schoolAreaList: [] as any,
      schoolAreaId: null, // 学校区域编号
      schoolInstrumentSetType: null as any,
      gradeList: [] as any,
      classList: [] as any,
      schoolName: '',
      gradeNumText: '',
      areaName: '',
      gradeStatus: false,
      gradePopupShow: false,
      gradePopupIndex: [] as any, // 年级下拉索引
      classPopupShow: false,
      classPopupIndex: [] as any, // 班级下拉索引
      areaList: [] as any,
      showPicker: false,
      gradeAndClass: [gradeList, classList], 
      gradeAndClassIndex: [] as any,
      submitLoading: false,
      id: null as any,
      code: null as any,
    })

    onMounted(async () => {
      queryDetail();
      getAreaList();
    });

    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);

    const queryDetail = async () => {
      try {
        // 判断是否获取微信code码
        if (!forms.openId) return;
        const { data } = await request.get(
          '/edu-app/open/schoolMeetingQuestion/detail?openId=' + forms.openId
        );
        // console.log(12222,data)
        forms.provinceCode = data.provinceCode
        forms.cityCode = data.cityCode
        forms.districtCode = data.districtCode
        forms.currentClass = data.currentClass
        forms.currentGrade = data.currentGrade
        forms.phone = data.phone
        forms.prePhone = data.phone
        forms.username = data.username
        forms.schoolAreaId = data.schoolAreaId
        forms.schoolName = data.schoolName
        forms.supportFlag = data.supportFlag
        forms.participationFlag = data.participationFlag
        forms.areaName = data.provinceName + ' ' + data.cityName + ' ' + data.districtName
        const gradeIdx = gradeList.find(item => item.text === data.currentGrade)?.value || 1
        // @ts-ignore
        const classIdx = classList.find(item => item.text === data.currentClass)?.value || 1
        forms.gradeAndClassIndex = [gradeIdx, classIdx]
        getSchoolAreaList()
      } catch {
        //
      }
    }
    
    /** 手机号变更时清空验证码信息，用户信息 */
    const phoneChangeEmptyInfo = () => {

    };

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

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

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

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

    const checkForm = (status = true) => {
      if (!forms.schoolAreaId) {
        showToast('请选择学校');
        return false;
      }
      if (!forms.username) {
        showToast('请输入姓名');
        return false;
      }
      if (!forms.currentClass) {
        showToast('请选择年级班级');
        return false;
      }
      if (forms.supportFlag === null) {
        showToast('请勾选是否支持学校数字化转型');
        return false;
      }
      if (forms.participationFlag === null) {
        showToast('请勾选是否愿意学生参加数字化转型');
        return false;
      }
      if (forms.participationFlag) {
        if (!checkPhone(forms.phone)) {
          status && showToast('请输入正确的手机号码');
          return false;
        } else if (!forms.smsCode) {
          status && showToast('请输入验证码');
          return false;
        }
      }
      return true;
    };

    const submitFill = async () => {
      if (checkForm()) {
        try {
          forms.submitLoading = true;
          const { currentClass, districtCode, currentGrade, participationFlag,cityCode, openId,provinceCode,smsCode,phone,schoolAreaId,supportFlag,username,id} = forms
          let params: any = {
            currentClass, districtCode, currentGrade, participationFlag,cityCode, openId,provinceCode,schoolAreaId,supportFlag,username
          }
          if (id) {
            params.id = id
          }
          if (participationFlag) {
            params.phone = phone
            params.smsCode = smsCode
          }
          const res = await request.post('/edu-app/open/schoolMeetingQuestion/save', {
            data: params
          });
          if (res.code === 200) {
            forms.successPopShow = true;
            forms.prePhone = forms.phone
          }
          forms.submitLoading = false;
          forms.countDownStatus = true;
        } catch {
          //
          forms.submitLoading = false;
          forms.countDownStatus = true;
        }
      }
    }
    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 openAreaPop = () => {
      console.log(11111)
      forms.schoolStatus = true
      // 如果没有选省市区，默认打开省市区弹窗
      if (!forms.areaName) {
        forms.showPicker = true
      }
    }

    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,
            districtCode: forms.districtCode
          }
        });
        forms.schoolAreaList = data;
      } catch {
        //
      }
      forms.schoolLoading = false;
    };

    const switchParticipationFlag = (val: boolean) => {
      forms.participationFlag = val
      if (!forms.participationFlag) {
        forms.phone = ''
        forms.smsCode = ''
        forms.countDownStatus = true
      }
      if (forms.participationFlag) {
        forms.phone = forms.prePhone
      }
    }

    // 获取地区学校详情
    const getSchoolAreaDetail = async () => {
      try {
        const { data } = await request.get(
          '/edu-app/open/schoolArea/detail/' + forms.schoolAreaId
        );
        console.log(data, 'data');

        if (data.school) {
          const schoolInfo = data.school || {};
          const schoolInstrumentList = schoolInfo.schoolInstrumentList || [];
          forms.schoolInstrumentSetType = schoolInfo.instrumentSetType;
          if (schoolInfo.instrumentSetType === 'SCHOOL') {
            const instrumentCode = schoolInstrumentList[0]?.instrumentCode;
            forms.gradeList = getGradeList(
              schoolInfo.gradeYear,
              instrumentCode
            );
            forms.classList = classList;
          } else if (schoolInfo.instrumentSetType === 'GRADE') {
            forms.gradeList = [];
            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 (schoolInfo.instrumentSetType === '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(schoolInfo.gradeYear);
            forms.classList = classList;
          }
        } else {
          forms.schoolInstrumentSetType = '';
          forms.gradeList = getGradeList();
          forms.classList = classList;
        }
      } catch {
        //
      }
    };    

    onUnmounted(() => {
      window.removeEventListener('pageshow', onPageShow);
      window.removeEventListener('pagehide', onPageHide);
    });
    return () => (
      <div class={styles['intention-page']}>
        <div class={styles.formBox}>
          <div class={styles.formItem}>
            <p>1. 学校</p>
            {
              forms.areaName || forms.schoolName ? 
              <div class={[styles.valDone, forms.schoolName && styles.valDone2]} onClick={() => forms.schoolStatus = true}>
                {forms.schoolName && <span class={styles.vdSchool}>{forms.schoolName}</span>}
                <span class={styles.vdArea}>{forms.areaName}</span>
                <i></i>
              </div> :
              <div class={[styles.valDot, styles.grayText, forms.schoolStatus && styles.openVal]} onClick={openAreaPop}>请选择学校<i></i></div>
            }
            <div></div>
          </div>
          <div class={styles.formItem}>
            <p>2. 学生姓名</p>
            <Field
              class={styles.valDot}
              clearable={false}
              inputAlign="left"
              placeholder="请输入学生姓名"
              autocomplete="off"
              maxlength={14}
              v-model={forms.username}>
						</Field>
          </div>
          <div class={styles.formItem}>
            <p>3. 年级班级</p>
            <div class={[styles.valDot, !forms.currentClass && styles.grayText, forms.gradeStatus && styles.openVal]}
             onClick={()=> forms.gradeStatus = true}>{forms.currentClass ? forms.currentGrade+forms.currentClass : '请选择年级班级'}<i></i></div>
          </div>     
          <div class={styles.formItem}>
            <p>4. 在您了解以上数字化转型事项后，您是否支持学校开展音乐（器乐）课堂数字化转型</p>
            <div class={styles.selectItem}>
              {
                forms.supportList.map(item => 
                  <div onClick={() => (forms.supportFlag = item.val)}>
                    <i class={forms.supportFlag === item.val && styles.selectedIcon}></i>
                    <span>{item.title}</span>
                  </div>
                )
              }
            </div>
          </div>    
          <div class={styles.formItem}>
            <p>5. 您是否愿意学生参加数字化转型<span>（注：以学生及家长自愿参加为原则。如愿意参加，家长需自行为学生准备好“器乐数字Ai”应用软件，市面上均有提供，大约300多元一年，学校不涉及任何收费行为。如不参加，学生按原有方式进行器乐课程学习）</span></p>
            <div class={styles.selectItem}>
              {
                forms.willingList.map(item => 
                  <div onClick={() => switchParticipationFlag(item.val)}>
                    <i class={forms.participationFlag === item.val && styles.selectedIcon}></i>
                    <span>{item.title}</span>
                  </div>
                )
              }
            </div>            
          </div> 
          {
            forms.participationFlag && 
            <div class={styles.formItem}>
              <p>联系方式</p>
              <Field
                class={styles.valDot}
                clearable={false}
                placeholder="请输入手机号码"
                type="digit"
                autocomplete="off"
                inputAlign="left"
                v-model={forms.phone}
                maxlength={11}
                onUpdate:modelValue={(val: any) => {
                  phoneChangeEmptyInfo();
                }}>
              </Field>
              <Field
                class={[styles.valDot, styles.codeItem]}
                center
                clearable={false}
                inputAlign="left"
                placeholder="请输入验证码"
                autocomplete="off"
                type="number"
                v-model={forms.smsCode}
                maxlength={6}>
                {{
                  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>                            
          </div>            
          }    
   
          {
            forms.participationFlag !== null && 
            <img class={styles.bottomBtn} src={forms.participationFlag ? signupBtn : submitBtn}
              onClick={() => {
                if (forms.submitLoading) return;
                submitFill()
              }}
            />      
          }
        </div>

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

        {forms.imgCodeStatus ? (
          <MImgCode
            v-model:value={forms.imgCodeStatus}
            phone={forms.phone}
            type="MEETING_QUESTION"
            onClose={() => {
              forms.imgCodeStatus = false;
            }}
            onSendCode={onCodeSend}
          />
        ) : null}
        {
          forms.successPopShow && 
          <div class={styles.successPop}>
            <div class={styles.successBox}>
              <img class={styles.sTitle} src={forms.participationFlag ? signSusIcon : subSusIcon} />
              <p>{forms.participationFlag ? '您已报名成功，感谢您的参与' : '感谢您的宝贵意见'}</p>
              <img class={styles.sDone} src={doneIcon} onClick={() => {
                forms.successPopShow = false
              }} />
            </div>
          </div>
        }

        <Popup
          zIndex={2010}
          v-model:show={forms.showPicker}
          position="bottom"
          round
          class={'popupBottomSearch'}>
          <Area
            visibleOptionNum={9}
            optionHeight={46}
            areaList={forms.areaList}
            onCancel={() => (forms.showPicker = false)}
            onConfirm={({ selectedOptions }) => {
              forms.provinceCode = selectedOptions[0].value;
              forms.cityCode = selectedOptions[1].value;
              forms.districtCode = selectedOptions[2]?.value;

              forms.areaName = selectedOptions
                .map((item: any) => item?.text)
                .join(' ');

              forms.showPicker = false;
              forms.schoolAreaId = null;
              forms.schoolName = '';
              forms.gradeNumText = '';
              forms.currentGrade = null;
              forms.currentClass = null;
              forms.currentClassText = '';
              // console.log('地址1')
              getSchoolAreaList();
            }}
          />
        </Popup>

        {/* 互通学校 */}
        <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.schoolAreaId = selectedOption.id || null;
                  forms.schoolName = selectedOption.name;
                  forms.schoolStatus = false;
                  forms.currentGrade = null;
                  forms.currentClass = null;
                  // console.log('学校id',forms.schoolAreaId,selectedOption)
                  // getSchoolAreaDetail();
                }}>
                {{
                  'columns-top': (
                    <div class={styles.columnsTop}>
                      <Cell border={false} clickable={false} title={forms.areaName || '请选择省市区'} isLink onClick={() => {
                        forms.showPicker = true;
                      }} />
                      <MSearch
                        placeholder="请输入学校名称"
                        onSearch={(val: any) => {
                          getSchoolAreaList(val);
                        }}
                      />
                    </div>
                  )
                }}
              </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.gradeAndClassIndex}
              columns={forms.gradeAndClass}
              onCancel={() => (forms.gradeStatus = false)}
              onConfirm={(val: any) => {
                // console.log('选择1111',val)
                forms.gradeAndClassIndex = [val.selectedOptions[0].value, val.selectedOptions[1].value]
                forms.currentGrade = val.selectedOptions[0].text;
                forms.currentClass = val.selectedOptions[1].text;
                forms.gradeStatus = false;
                
              }}
            />
          )}
        </Popup>
      </div>
    );
  }
});
