import { defineComponent, onMounted, reactive, ref, nextTick, onUnmounted } from 'vue';
import styles from './index.module.less';
import { List, Popup, DatePicker, Popover, Picker } from 'vant';
import request from '@/helpers/request';
import { useRoute, useRouter } from 'vue-router';
import OEmpty from '@/components/m-empty';
import MWxTip from '@/components/m-wx-tip';
import OSearch from '@/components/m-search';
import positionIcon from './images/position_icon.png';
import scIcon1 from './images/sc_icon1.png';
import scIcon2 from './images/sc_icon2.png';
import scIcon3 from './images/sc_icon3.png';
import schoolIcon from './images/school_icon.png';
import gradeIcon from './images/class_icon.png';
import { number } from 'echarts';
import { drawCircle } from './drawGraph'
import OFullRefresh from '@/components/m-full-refresh';
import useWeChatShare from '@/hooks/useWeChatShare';
import { browser } from '@/helpers/utils';


export default defineComponent({
  name: 'statistics-detail',
  setup() {
    const route = useRoute();
    const router = useRouter();
    const areaTenantName = sessionStorage.getItem('areaTenantName') || ''
    const shareTitle = areaTenantName + '音乐（器乐）数字化转型问卷统计';
    const weChatShare = useWeChatShare(
      shareTitle,
      '科技赋能音乐（器乐）学习，在每一个孩子心中奏响美妙的乐章。',
      window.location.origin + '/classroom-app/shareImg/questionnaire-statistics-new.png'
    );

    const tabName = ref('all');
    const forms = reactive({
      schoolName: '',
      id: route.query.id,
      yearStatus: false,
      schoolId: null,
      
    });

    const refreshing = ref(false);
    const loading = ref(true);
    const finished = ref(false);


    const state = reactive({
      saveLoading: false,
      image: null as any,
      shareLoading: false,
      schoolInfo: {} as any,
      classList: [] as any,
      currentSort: 1, // 当前选中的排序方式
      currentAsc: false, // 是否生序，默认是降序
      gradeColumns: [],
      gradeStatus: false,
      gradePopShow: false,
      currentGrade: "",
      currentClass: "",
      gradeOptionIndex: [] as any,
      gradeContent: null as any,
      intervalOne: null as any, // 动画定时器
    });

    // 获取学校信息
    const queryInfo = async () => {
      try {
        const res = await request.post(
          '/edu-app/open/meetingQuestionSetting/schoolStat',
          {
            hideLoading: false,
            data: {
              schoolAreaId: forms.id
            }
          }
        );
        state.schoolInfo = res.data || {}
        // 构建年级、班级及联选择
        const columns: any = []
        res.data.classData.unshift({
          currentClassList: [],
          currentGrade: '全部年级'
        })
        res.data.classData.forEach((grade: any, index: number) => {
          let columnItem: any = {}
          columnItem.text = grade.currentGrade
          columnItem.value = 'grade' + index
          columnItem.children = []
          grade.currentClassList.unshift('全部班级')
          if (grade.currentClassList?.length) {
            grade.currentClassList.forEach((classObj: any, cIdx: number) => {
              columnItem.children.push({
                text: classObj,
                value: 'class' + cIdx
              })
            })
          }
          columns.push(columnItem)
        })
        state.gradeColumns = columns
        // console.log('555',res, state.gradeColumns)        
      } catch (error) {
        
      }

    }

    const queryList = async () => {
      try {
        const res = await request.post(
          '/edu-app/open/meetingQuestionSetting/schoolClass',
          {
            data: {
              schoolAreaId: forms.id,
              currentGrade: state.currentGrade,
              currentClass: state.currentClass,
              sortType: state.currentSort,
              asc: state.currentAsc
            }
          }
        );
        state.classList = res.data || []
        // console.log('222',res)        
      } catch (error) {
        
      }

    }

    const filterList = (num: number) => {
      if (state.currentSort !== num) {
        state.currentAsc = false
      } else {
        state.currentAsc = !state.currentAsc
      }
      state.currentSort = num;
      
      queryList()
    }

    const formatNumberWithComma = (num: number | string) => {
      // 将数字转换为字符串，去掉小数点后面的部分
      let [integer, decimal] = num.toString().split('.');
      
      // 使用正则表达式添加千分位分隔符
      integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
      
      // 如果有小数部分，则保留小数部分
      return decimal ? `${integer}.${decimal}` : integer;
    }

    const onRefresh = async () => {
      // console.log('刷新111')
      clearDataAnimation();
      finished.value = false;
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      loading.value = true;
      await initData()
      refreshing.value = false
    };

    const clearDataAnimation = () => {
      clearInterval(state.intervalOne); // 停止定时器
      state.intervalOne = null;
    }

    const initData = async () => {
      await queryInfo()
      queryList()
      nextTick(() => {
        let percentage = 0;
        state.intervalOne = setInterval(() => {
          if (percentage <= state.schoolInfo.supportStudentRate) {
            // console.log(percentage,state.schoolInfo.supportStudentRate)
            drawCircle('circle1', 1, percentage)
          }
          if (percentage <= state.schoolInfo.participationStudentRate) {
            drawCircle('circle2', 2, percentage)
          }
          if (percentage === Math.floor(Number(state.schoolInfo.supportStudentRate))) {
            drawCircle('circle1', 1, state.schoolInfo.supportStudentRate)
          }
          if (percentage === Math.floor(Number(state.schoolInfo.participationStudentRate))) {
            drawCircle('circle2', 2, state.schoolInfo.participationStudentRate)
          }
          percentage += 1; // 每次增加1%
          if (percentage > Math.max(state.schoolInfo.supportStudentRate, state.schoolInfo.participationStudentRate)) {
            clearDataAnimation();
            // percentage = 0;
          }
        }, 25); // 每25ms更新一次
      });
    }
    onMounted(async () => {
      if (browser().weixin) {
        weChatShare.getAppSignature()
      }
      initData()
    });
    onUnmounted(() => {
      clearDataAnimation();
    });

    return () => (
      <OFullRefresh
      freshDisabled={state.gradeStatus}
      v-model:modelValue={refreshing.value}
      onRefresh={onRefresh}
      class={styles.refreshC}>
      <div class={styles.detailBody}>
        <div class={styles.dbTitle}>
          <div class={styles.dtName}>
            <img src={schoolIcon} />
            <p>{state.schoolInfo.schoolName}</p>
          </div>
          <div class={styles.dtDesc}>共<span> {state.schoolInfo.classNum} </span>个班级，<span>{state.schoolInfo.studentNum}</span>人参与调查</div>
        </div>

        {/* <div class={styles.dbStatic}>
          <div class={styles.dsItem}>
            <div><span>{formatNumberWithComma(state.schoolInfo.supportStudentNum || 0)}</span><i>人</i></div>
            <p>支持学校开展</p>
            <i class={[styles.dsIcon, styles.dsIcon1]}></i>
          </div>
          <div class={styles.dsItem}>
            <div><span>{state.schoolInfo.supportStudentRate}%</span></div>
            <p>支持率</p>
            <i class={[styles.dsIcon, styles.dsIcon2]}></i>
          </div>          
        </div> */}

        {/** 圆环统计 */}
        <div class={styles.sRing}>
          <div class={[styles.srItem,styles.srItemOne]}>
            <div class={styles.siLeft}>
              <canvas id="circle1" width="85" height="85"></canvas>
              <p>支持率</p>
            </div>
            <div class={styles.siRight}>
              <div><span class={styles.sBlue}>{formatNumberWithComma(state.schoolInfo.supportStudentNum || 0)}</span><i>人</i></div>
              <p>支持开展</p>
            </div>
          </div>
          <div class={styles.srItem}>
            <div class={styles.siLeft}>
              <canvas id="circle2" width="85" height="85"></canvas>
              <p>参加率</p>
            </div>
            <div class={styles.siRight}>
              <div><span class={styles.sGreen}>{formatNumberWithComma(state.schoolInfo.participationStudentNum||0)}</span><i>人</i></div>
              <p>报名参加</p>
            </div>
          </div>
        </div>      

        {/** 选择年级班级 */}
        <div class={[styles.gradeColumn, state.gradeStatus && styles.openVal]} onClick={() => state.gradeStatus = true}>
          <span class={state.gradeContent && styles.gcText}>{state.gradeContent ? state.gradeContent : '请选择年级班级'}</span>
          <i></i>
        </div>

        {/** 排序栏 */}
        <ul class={styles.sortColumn}>
            <li class={state.currentSort === 1 && styles.sortActive} onClick={() => filterList(1)}>
              <span>参与调查人数</span>
              <i class={[(state.currentSort === 1 && !state.currentAsc) && styles.actDown, (state.currentSort === 1 && state.currentAsc) && styles.actUp]}></i>
            </li>
            <li class={state.currentSort === 2 && styles.sortActive} onClick={() => filterList(2)}>
              <span>支持人数</span>
              <i class={[(state.currentSort === 2 && !state.currentAsc) && styles.actDown, (state.currentSort === 2 && state.currentAsc) && styles.actUp]}></i>
            </li>
            <li class={state.currentSort === 3 && styles.sortActive} onClick={() => filterList(3)}>
              <span>支持率</span>
              <i class={[(state.currentSort === 3 && !state.currentAsc) && styles.actDown, (state.currentSort === 3 && state.currentAsc) && styles.actUp]}></i>
            </li>      
            <li class={state.currentSort === 4 && styles.sortActive} onClick={() => filterList(4)}>
              <span>参加人数</span>
              <i class={[(state.currentSort === 4 && !state.currentAsc) && styles.actDown, (state.currentSort === 4 && state.currentAsc) && styles.actUp]}></i>
            </li>   
            <li class={state.currentSort === 5 && styles.sortActive} onClick={() => filterList(5)}>
              <span>参加率</span>
              <i class={[(state.currentSort === 5 && !state.currentAsc) && styles.actDown, (state.currentSort === 5 && state.currentAsc) && styles.actUp]}></i>
            </li>                                             
        </ul>
        {/** 班级列表 */}
        <div class={styles.scList}>
          {
            state.classList.map((item: any) => (
              <div class={styles.sItem}>
              <div class={[styles.itemTile, styles.itemTileDetail]}>
                <img src={gradeIcon} />
                <p>{item.currentGrade||''}{item.currentClass || ''}</p>
                <div class={styles.itRight}><span class={styles.sRed}>{formatNumberWithComma(item.studentNum || 0)}</span> 人参与调查</div>
              </div>
              <ul class={styles.itemContent}>
                <li>
                  <div class={styles.icTop}>
                    <span class={styles.sBlue}>{formatNumberWithComma(item.supportStudentNum || 0)}</span><i>人</i>
                  </div>
                 <p>支持开展</p>
                </li>      
                <li>
                  <div class={styles.icTop}>
                    <span class={styles.sBlue}>{Number(item.supportStudentRate || 0).toFixed(2)}%</span>
                  </div>
                 <p>支持率</p>
                </li>  

                <li>
                  <div class={styles.icTop}>
                    <span class={styles.sGreen}>{formatNumberWithComma(item.participationStudentNum || 0)}</span><i>人</i>
                  </div>
                 <p>报名参加</p>
                </li>

                <li>
                  <div class={styles.icTop}>
                    <span class={styles.sGreen}>{Number(item.participationStudentRate || 0).toFixed(2)}%</span>
                  </div>
                 <p>参加率</p>
                </li>                                
              </ul>
            </div>
            ))
          }
        </div>

        {/* 班级 */}
        <Popup
          v-model:show={state.gradeStatus}
          position="bottom"
          round
          safeAreaInsetBottom
          lazyRender={false}
          class={'popupBottomSearch'}
          onOpen={() => {
            state.gradePopShow = true;
          }}
          onClosed={() => {
            state.gradePopShow = false;
          }}>
          {state.gradePopShow && (
            <Picker
              showToolbar
              v-model={state.gradeOptionIndex}
              columns={state.gradeColumns}
              onCancel={() => (state.gradeStatus = false)}
              onConfirm={(val: any) => {
                console.log('选择1111',val)
                state.currentGrade = val.selectedOptions[0].text === '全部年级' ? '' : val.selectedOptions[0].text
                state.currentClass = val.selectedOptions[1].text === '全部班级' ? '' : val.selectedOptions[1].text
                state.gradeOptionIndex = [val.selectedOptions[0].value, val.selectedOptions[1].value]
                state.gradeContent = state.currentGrade + state.currentClass
                state.gradeStatus = false;
                queryList()
              }}
            />
          )}
        </Popup> 

        {/* <MWxTip /> */}
      </div>
      </OFullRefresh>
    );
  }
});
