import { defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import {
  Cell,
  CellGroup,
  Col,
  List,
  Picker,
  Popup,
  Row,
  Tab,
  Tabs,
  DatePicker
} from 'vant';
import MSticky from '@/components/m-sticky';
// import icon1 from './images/icon1.png';
// import icon2 from './images/icon2.png';
// import icon3 from './images/icon3.png';
// import icon4 from './images/icon4.png';
// import iconTimer from './images/icon-timer.png';
import personIcon from './images/personIcon.png';
import homeIcon from './images/homeIcon.png';
import sanIcon from './images/san.png';
import request from '@/helpers/request';
import topDot from './images/topDot.png';
import { useRoute, useRouter } from 'vue-router';
import { moneyFormat, numberFormat } from '@/helpers/utils';
import OFullRefresh from '@/components/m-full-refresh';
import OEmpty from '@/components/m-empty';
import arrowIcon from './images/arrowIcon.png';
import OHeader from '@/components/m-header';
import OSearch from '@/components/m-search';
import numeral from 'numeral';
export default defineComponent({
  name: 'tenant-apply-data',
  setup() {
    const route = useRoute();
    const router = useRouter();
    const tabName = ref('all');
    const forms = reactive({
      keyword: '',
      id: route.query.id,
      // id: '1687275949971763202',
      yearStatus: false,
      schoolId: null,
      year: [new Date().getFullYear()] as any,
      yearName: new Date().getFullYear(),
      classList: [] as any,
      statObj: {
        registerNum: 0,
        schoolNum: 0
      } as any,
      perponStatus: false,
      sortId: 'desc',
      sortName: '人数降序',
      sortList: [
        { value: 'desc', text: '人数降序' },
        { value: 'asc', text: '人数升序' }
      ] as any,
      page: 1,
      rows: 20,
      isClick: false
    });

    const refreshing = ref(false);
    const loading = ref(true);
    const finished = ref(false);
    const showContact = ref(false);
    const list = ref([]);

    const getSchoolList = async () => {
      try {
        const { data } = await request.get('/edu-app/open/school/list', {
          params: {
            tenantId: forms.id
          }
        });
        const temp = [
          {
            value: '',
            text: '全部学校'
          }
        ];
        if (Array.isArray(data)) {
          data.forEach((item: any) => {
            temp.push({
              value: item.id,
              text: item.name
            });
          });
          forms.classList = temp;
        }
      } catch {
        //
      }
    };

    const getList = async () => {
      if (forms.isClick) {
        return;
      }
      forms.isClick = true;
      if (refreshing.value) {
        list.value = [];
        forms.page = 1;
        refreshing.value = false;
      }
      try {
        const res = await request.post(
          '/edu-app/open/school/schoolRegisterPage',
          {
            data: {
              tenantId: forms.id,
              page: forms.page,
              rows: forms.rows,
              year: forms.yearName,
              keyword: forms.keyword,
              sort: forms.sortId
            }
          }
        );

        if (list.value.length > 0 && res.data.current === 1) {
          return;
        }

        list.value = list.value.concat(res.data.rows || []);
        forms.page = res.data.current + 1;
        showContact.value = list.value.length > 0;
        loading.value = false;
        finished.value = res.data.current >= res.data.pages;
      } catch {
        showContact.value = false;
        finished.value = true;
      } finally {
        loading.value = false;
      }
      forms.isClick = false;
    };
    const onRefresh = () => {
      finished.value = false;
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      loading.value = true;
      getList();
    };

    onMounted(async () => {
      document.title = '学生报名统计';
      // await getSchoolList();
      await getStat();
      await getList();
    });
    const gotoDetail = (item: any) => {
      router.push({
        path: '/tenamtDataDetail',
        query: {
          id: route.query.id,
          schoolId: item.schoolId,
          schoolName: item.schoolName
        }
      });
    };
    const getStat = async () => {
      try {
        const { data } = await request.post(
          '/edu-app/open/school/schoolRegisterStat',
          {
            data: {
              tenantId: forms.id,
              year: forms.yearName
            }
          }
        );
        forms.statObj = data;
      } catch {
        //
      }
    };
    return () => (
      <div class={styles.tenantAllData}>
        {/* <OHeader isBack={false} /> */}
        <MSticky position='top'>
          <div class={styles.top}>
            <div class={styles.topWrap}>
              <div class={styles.topHead}>
                <img src={topDot} class={styles.topDot} alt="" />
                汇总数据
              </div>
              {/* <div
                class={styles.timerWrap}
                onClick={() => {
                  forms.yearStatus = true;
                }}>
                {forms.yearName}年{' '}
                <img
                  src={sanIcon}
                  class={[
                    styles.sanIcon,
                    forms.yearStatus ? styles.routeSan : ''
                  ]}
                  alt=""
                />
              </div> */}
            </div>
            <div class={styles.cardWrap}>
              <div class={[styles.schoolCard, styles.cardItem]}>
                <div class={styles.cardNum}>
                  {' '}
                  {numeral(forms.statObj.schoolNum).format('0,0')}
                </div>
                <div class={styles.cardInfo}>
                  <img src={homeIcon} class={styles.cardInfoImg} alt="" />
                  学校数量
                </div>
                <div class={styles.cardLine}></div>
              </div>
              <div class={[styles.studentCard, styles.cardItem]}>
                <div class={styles.cardNum}>
                  {' '}
                  {numeral(forms.statObj.registerNum).format('0,0')}
                </div>
                <div class={styles.cardInfo}>
                  <img src={personIcon} class={styles.cardInfoImg} alt="" />
                  报名总人数
                </div>
                <div class={styles.cardLine}></div>
              </div>
            </div>
            <div class={styles.searchWrap}>
              <div class={styles.searechInfo}>
                <OSearch
                  class={styles.allDataWrap}
                  shape="round"
                  background="#F6F8F9"
                  inputBackground="white"
                  placeholder='请输入学校名称'
                  onSearch={val => {
                    forms.keyword = val;
                    forms.page = 1;
                    refreshing.value = true;
                    getList();
                  }}></OSearch>
              </div>

              <div
                class={styles.timerWrap}
                onClick={() => (forms.perponStatus = true)}>
                {forms.sortName}{' '}
                <img
                  src={sanIcon}
                  class={[
                    styles.sanIcon,
                    forms.perponStatus ? styles.routeSan : ''
                  ]}
                  alt=""
                />
              </div>
            </div>
            </div>
          </MSticky>

        <div class={styles.schoolList}>
          {showContact.value ? (
            <OFullRefresh
              v-model:modelValue={refreshing.value}
              onRefresh={onRefresh}
              class={styles.refreshC}>
              <List
                loading-text=" "
                finished={finished.value}
                finished-text=" "
                onLoad={getList}>
                {list.value.map((item: any) => (
                  <div
                    class={styles.schoolItem}
                    onClick={() => gotoDetail(item)}>
                    <div class={styles.schoolNameWrap}>
                      <p class={styles.title}>学校名称</p>
                      <p class={styles.schoolName}>{item.schoolName}</p>
                    </div>
                    <div class={styles.schoolCountWrap}>
                      <div>
                        <p class={styles.title}>报名人数</p>
                        <p class={styles.personNum}>{item.registerNum}</p>
                      </div>
                      <img class={[styles.arrow]} src={arrowIcon} alt="" />
                    </div>
                  </div>
                ))}
              </List>
            </OFullRefresh>
          ) : null}

          {!showContact.value && !loading.value && (
            <OEmpty description="暂无学校信息" class={styles.emptyC} />
          )}
        </div>
        <Popup
          v-model:show={forms.yearStatus}
          position="bottom"
          round
          class={'popupBottomSearch'}>
          <DatePicker
            showToolbar
            v-model={forms.year}
            columns-type={['year']}
            onCancel={() => (forms.yearStatus = false)}
            onConfirm={(val: any) => {
              console.log(val);
              // const selectedOption = val.selectedOptions[0];
              // console.log(selectedOption, 'selectedOption');
              // forms.schoolId = selectedOption.value;
              // // forms.schoolName = selectedOption.text;
              forms.year = [val.selectedValues[0]];
              forms.yearName = val.selectedValues[0];
              forms.page = 1;
              refreshing.value = true;
              getStat();
              getList();
              forms.yearStatus = false;
            }}
          />
        </Popup>

        <Popup
          v-model:show={forms.perponStatus}
          position="bottom"
          round
          class={'popupBottomSearch'}>
          <Picker
            showToolbar
            columns={forms.sortList}
            onCancel={() => (forms.perponStatus = false)}
            onConfirm={(val: any) => {
              console.log(val);
              const selectedOption = val.selectedOptions[0];
              forms.sortId = selectedOption.value;
              forms.sortName = selectedOption.text;
              refreshing.value = true;
              getList();
              forms.perponStatus = false;
            }}
          />
        </Popup>
      </div>
    );
  }
});
