import { defineComponent, onMounted, reactive, ref, nextTick } from 'vue';
import styles from './index.module.less';
import {
  Cell,
  CellGroup,
  Col,
  List,
  Picker,
  Popup,
  Row,
  Tab,
  Tabs,
  DatePicker,
  Button,
  DropdownMenu,
  DropdownItem,
  Popover
} from 'vant';
import MSticky from '@/components/m-sticky';
import personIcon from './images/personIcon.png';
import homeIcon from './images/homeIcon.png';
import memberIcon from './images/memberIcon.png';
import memberRateIcon from './images/memberRateIcon.png';
// import sanIcon from './images/san.png';
import iconArrow from './images/icon-arrow.png';
import iconArrowActive from './images/icon-arrow-active.png';
import iconQrcode from './images/icon-qrcode.png';
import qrcodeBg from './images/qrcode-bg.png';
import qrbg from './images/qr-bg.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';
import MQrcode from '@/components/m-qrcode';
import html2canvas from 'html2canvas';
import MWxTip from '@/components/m-wx-tip';
import deepClone from '@/helpers/deep-clone';
import { number } from 'echarts';
export default defineComponent({
  name: 'tenant-apply-data',
  setup() {
    const route = useRoute();
    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,
        classNum: 0,
        registerMemberShipNum: 0
      } as any,
      perponStatus: false,
      sortKey: 'CLASS' as 'CLASS' | 'MEMBER',
      sortId: 'desc',
      sortName: '报名人数降序',
      sortType: 'desc',
      sortList: [
        { value: 'desc', text: '报名人数降序' },
        { value: 'asc', text: '报名人数升序' },
        { value: 'mdesc', text: '会员人数降序' },
        { value: 'masc', text: '会员人数升序' }
      ] as any,
      page: 1,
      rows: 20,
      isClick: false,
      showDropdown: false,
      qrcodeStatus: false,
      url: '1', // 二维码
      urlItem: {} as any,

      provinceList: [] as any, // 省
      cityList: [] as any, // 市
      areaList: [] as any, // 区
      // 确认之后
      searchConfirmObj: {
        type: 'province' as 'province' | 'city' | 'area' | '',
        label: '全部地区',
        value: null as any,
        list: [] as any
      },
      // 弹窗
      searchObj: {
        type: 'province' as 'province' | 'city' | 'area' | '',
        label: '全部地区',
        value: null as any,
        list: [] as any
      }
    });

    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 params: any = {
          tenantId: forms.id,
          page: forms.page,
          rows: forms.rows,
          year: forms.yearName,
          keyword: forms.keyword,
          sort: forms.sortId,
          sortKey: forms.sortKey
        };

        if (forms.searchConfirmObj.type === 'province') {
          params.provinceCode = forms.searchConfirmObj.value;
        } else if (forms.searchConfirmObj.type === 'city') {
          params.cityCode = forms.searchConfirmObj.value;
        } else if (forms.searchConfirmObj.type === 'area') {
          params.regionCode = forms.searchConfirmObj.value;
        }
        const res = await request.post(
          '/edu-app/open/school/schoolRegisterPage',
          {
            data: params
          }
        );

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

    const imgs = reactive({
      saveLoading: false,
      image: null as any,
      shareLoading: false
    });
    const downImg = () => {
      if (imgs.saveLoading) {
        return;
      }
      imgs.saveLoading = true;
      // 判断是否已经生成图片
      // if (imgs.image) {
      //   saveImg();
      // } else {
      const container: any = document.getElementById(`preview-container`);
      // console.log('1212121', container);
      html2canvas(container, {
        allowTaint: true,
        useCORS: true,
        backgroundColor: null
      })
        .then(async canvas => {
          const url = canvas.toDataURL('image/png');
          imgs.image = url;
          // saveImg();
          forms.qrcodeStatus = true;
          imgs.saveLoading = false;
        })
        .catch(() => {
          // console.log(e, 'e');
          imgs.saveLoading = false;
          // console.log('222');
        });
      // }
    };

    const saveImg = async () => {
      // showLoadingToast({ message: '图片生成中...', forbidClick: true });
      setTimeout(() => {
        imgs.saveLoading = false;
      }, 100);
      const link = document.createElement('a');
      link.setAttribute('download', forms.urlItem.schoolName + '统计' + '.png');
      // 添加时间戳，防止浏览器缓存图

      link.href = imgs.image;
      link.click();
    };

    // 计算会员占比
    const formatMemberRate = (studentNum: any, memberNum: any) => {
      if (studentNum <= 0 || memberNum <= 0) {
        return 0;
      }
      // console.log(studentNum, memberNum);
      return Math.round((memberNum / studentNum) * 1000) / 10;
    };

    const dropdownItemRef = ref();
    const getAreas = async () => {
      try {
        const { data } = await request.get(
          '/edu-app/open/sysArea/queryProvince?tenantId=' + forms.id
        );
        forms.provinceList = data || [];
      } catch {
        //
      }
    };

    const formatParentAreaId = (id: any, list: any, ids = [] as any) => {
      for (const item of list) {
        if (item.code == id) {
          return [...ids, id];
        }
        if (item.areas && item.areas.length > 0) {
          const cIds: any = formatParentAreaId(id, item.areas, [
            ...ids,
            item.code
          ]);
          if (cIds.includes(id)) {
            return cIds;
          }
        }
      }
      return ids;
    };

    /** 切换状态 */
    const onChangeArea = (type: 'province' | 'city' | 'area', item: any) => {
      forms.searchObj.type = type;
      forms.searchObj.value = item.code;
      forms.searchObj.label = item.name;
      forms.searchObj.list = formatParentAreaId(item.code, forms.provinceList);
      if (type === 'province') {
        forms.cityList = item.areas || [];
        forms.areaList = [];
      } else if (type === 'city') {
        forms.areaList = item.areas || [];
      } else if (type === 'area') {
        //
      }
    };

    const formatAreaDefaultData = (index: number, ids: number[], item: any) => {
      const type: any = ['province', 'city', 'area'];
      if (ids.length <= 0) return;
      item.forEach((item: any) => {
        if (item.code === ids[index]) {
          onChangeArea(type[index], item);

          if (ids[index]) {
            formatAreaDefaultData(index + 1, ids, item.areas || []);
          }
        }
      });
    };

    onMounted(async () => {
      if (route.query.name) {
        document.title = route.query.name + '报名统计';
      } else {
        document.title = '学生报名统计';
      }

      // await getSchoolList();
      getAreas();
      await getStat();
      await getList();
    });
    const getStat = async () => {
      try {
        const params: any = {
          tenantId: forms.id,
          year: forms.yearName
        };

        if (forms.searchConfirmObj.type === 'province') {
          params.provinceCode = forms.searchConfirmObj.value;
        } else if (forms.searchConfirmObj.type === 'city') {
          params.cityCode = forms.searchConfirmObj.value;
        } else if (forms.searchConfirmObj.type === 'area') {
          params.regionCode = forms.searchConfirmObj.value;
        }
        const { data } = await request.post(
          '/edu-app/open/school/schoolRegisterStat',
          {
            data: params
          }
        );
        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, styles.topHeadIndex]}>
                <img src={topDot} class={styles.topDot} alt="" />
                汇总数据
              </div>

              <DropdownMenu>
                <DropdownItem
                  ref={dropdownItemRef}
                  onOpen={() => {
                    forms.searchObj = deepClone(forms.searchConfirmObj);

                    if (forms.searchObj.list.length > 0) {
                      formatAreaDefaultData(
                        0,
                        forms.searchObj.list,
                        forms.provinceList
                      );
                    }
                  }}>
                  {{
                    title: () => (
                      <div class={[styles.areaWrap, 'areaWrapActive']}>
                        <i class={styles.iconAddress}></i>
                        <span>{forms.searchConfirmObj.label}</span>
                        <i class={[styles.iconArrow, 'iconArrowActive']}></i>
                      </div>
                    ),
                    default: () => (
                      <div class={styles.areaSection}>
                        <div class={[styles.areaList]}>
                          {forms.provinceList.length > 0 && (
                            <div
                              class={[
                                styles.areaItem,
                                forms.cityList.length > 0 &&
                                  'van-hairline--right'
                              ]}>
                              {forms.provinceList.map((item: any) => (
                                <span
                                  onClick={() => onChangeArea('province', item)}
                                  class={[
                                    styles.areaItemChild,
                                    forms.searchObj.list.includes(item.code) &&
                                      styles.areaItemChildActive
                                  ]}>
                                  {item.name}
                                </span>
                              ))}
                            </div>
                          )}

                          {forms.cityList.length > 0 && (
                            <div
                              class={[
                                styles.areaItem,
                                forms.areaList.length > 0 &&
                                  'van-hairline--right'
                              ]}>
                              {forms.cityList.map((item: any) => (
                                <span
                                  onClick={() => onChangeArea('city', item)}
                                  class={[
                                    styles.areaItemChild,
                                    forms.searchObj.list.includes(item.code) &&
                                      styles.areaItemChildActive
                                  ]}>
                                  {item.name}
                                </span>
                              ))}
                            </div>
                          )}

                          {forms.areaList.length > 0 && (
                            <div class={[styles.areaItem]}>
                              {forms.areaList.map((item: any) => (
                                <span
                                  onClick={() => onChangeArea('area', item)}
                                  class={[
                                    styles.areaItemChild,
                                    forms.searchObj.list.includes(item.code) &&
                                      styles.areaItemChildActive
                                  ]}>
                                  {item.name}
                                </span>
                              ))}
                            </div>
                          )}
                        </div>
                        <div class={[styles.btnGroup, 'van-hairline--top']}>
                          <Button
                            round
                            block
                            onClick={async () => {
                              forms.searchObj.type = '';
                              forms.searchObj.label = '全部地区';
                              forms.searchObj.value = null;
                              forms.searchObj.list = [];
                              forms.searchConfirmObj = deepClone(
                                forms.searchObj
                              );
                              dropdownItemRef.value?.toggle(false);
                              forms.page = 1;
                              refreshing.value = true;
                              forms.cityList = [];
                              forms.areaList = [];

                              await getStat();
                              await getList();
                            }}>
                            重置
                          </Button>
                          <Button
                            round
                            type="primary"
                            block
                            onClick={async () => {
                              forms.searchConfirmObj = deepClone(
                                forms.searchObj
                              );
                              dropdownItemRef.value?.toggle(false);
                              forms.page = 1;
                              refreshing.value = true;
                              await getStat();
                              await getList();
                            }}>
                            确定
                          </Button>
                        </div>
                      </div>
                    )
                  }}
                </DropdownItem>
              </DropdownMenu>
            </div>
            <div class={[styles.cardWrap, styles.cardWrapIndex]}>
              {/* <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 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.memberCard, styles.cardItem]}>
                <div class={styles.cardNum}>
                  {numeral(forms.statObj.registerMemberShipNum).format('0,0')}
                </div>
                <div class={styles.cardInfo}>
                  <img src={memberIcon} class={styles.cardInfoImg} alt="" />
                  数字化人数
                </div>
                <div class={styles.cardLine}></div>
              </div>
              {/* <div class={[styles.memberRateCard, styles.cardItem]}>
                <div class={styles.cardNum}>
                  {numeral(
                    formatMemberRate(
                      forms.statObj.registerNum || 0,
                      forms.statObj.registerMemberShipNum || 0
                    )
                  ).format('0.0')}
                  %
                </div>
                <div class={styles.cardInfo}>
                  <img src={memberRateIcon} 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>

              <Popover
                v-model:show={forms.perponStatus}
                showArrow={false}
                placement="bottom-end"
                offset={[0, 12]}>
                {{
                  reference: () => (
                    <div
                      class={[
                        styles.timerWrap,
                        forms.perponStatus && styles.timerWrapActive
                      ]}
                      // onClick={() => (forms.perponStatus = true)}
                    >
                      {forms.sortName}
                      <img
                        src={forms.perponStatus ? iconArrowActive : iconArrow}
                        class={[styles.sanIcon]}
                        alt=""
                      />
                    </div>
                  ),
                  default: () => (
                    <div class={styles.popSearchList}>
                      {forms.sortList.map((item: any, index: number) => (
                        <div
                          class={[
                            styles.popSearchItem,
                            index < forms.sortList.length - 1 &&
                              'van-hairline--bottom'
                          ]}>
                          <div
                            class={[
                              styles.popSearchItemChild,
                              forms.sortType === item.value &&
                                styles.popSearchItemActive
                            ]}
                            onClick={() => {
                              const selectedOption = item;
                              if (
                                selectedOption.value === 'desc' ||
                                selectedOption.value === 'asc'
                              ) {
                                forms.sortId = selectedOption.value;
                                forms.sortKey = 'CLASS';
                              }
                              if (selectedOption.value === 'mdesc') {
                                forms.sortId = 'desc';
                                forms.sortKey = 'MEMBER';
                              }
                              if (selectedOption.value === 'masc') {
                                forms.sortId = 'asc';
                                forms.sortKey = 'MEMBER';
                              }

                              forms.sortType = selectedOption.value;
                              forms.sortName = selectedOption.text;
                              refreshing.value = true;
                              getList();
                              forms.perponStatus = false;
                            }}>
                            {item.text}
                          </div>
                        </div>
                      ))}
                    </div>
                  )
                }}
              </Popover>
            </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, styles.schoolItemOther]}>
                    <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.personNum}>
                          {numeral(item.registerNum || 0).format('0,0')}
                        </p>
                        <p class={styles.title}>报名人数</p>
                      </div> */}
                      <div>
                        <p class={styles.personNum}>
                          {numeral(item.classNum || 0).format(
                            '0,0'
                          )}
                        </p>
                        <p class={styles.title}>班级数量</p>
                      </div>
                      <div>
                        <p class={styles.personNum}>
                          {numeral(item.registerMemberShipNum || 0).format(
                            '0,0'
                          )}
                          {/* {item.registerMemberShipNum || 0} */}
                        </p>
                        <p class={styles.title}>数字化人数</p>
                      </div>
                      {/* <div>
                        <p class={styles.personNum}>
                          {numeral(
                            formatMemberRate(
                              item.registerNum || 0,
                              item.registerMemberShipNum || 0
                            )
                          ).format('0.0')}
                          %
                        </p>
                        <p class={styles.title}>数字化普及率</p>
                      </div> */}
                      <div
                        onClick={() => {
                          forms.urlItem = item;
                          forms.url = `${location.origin}/classroom-app/#/tenantDataShool?id=${item.schoolId}&name=${item.schoolName}`;

                          nextTick(() => {
                            downImg();
                          });
                        }}>
                        <p class={styles.personNum}>
                          <img src={iconQrcode} />
                        </p>
                        <p class={styles.title}>统计二维码</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) => {
              const selectedOption = val.selectedOptions[0];
              if (
                selectedOption.value === 'desc' ||
                selectedOption.value === 'asc'
              ) {
                forms.sortId = selectedOption.value;
                forms.sortKey = 'CLASS';
              }
              if (selectedOption.value === 'mdesc') {
                forms.sortId = 'desc';
                forms.sortKey = 'MEMBER';
              }
              if (selectedOption.value === 'masc') {
                forms.sortId = 'asc';
                forms.sortKey = 'MEMBER';
              }

              forms.sortName = selectedOption.text;
              refreshing.value = true;
              getList();
              forms.perponStatus = false;
            }}
          />
        </Popup> */}

        <Popup v-model:show={forms.qrcodeStatus} class={styles.popupQrcode}>
          <i
            class={styles.iconClose}
            onClick={() => (forms.qrcodeStatus = false)}></i>

          <div class={[styles.shareContaienr]}>
            {/* <img src={qrcodeBg} class={styles.qrcodeBg} /> */}
            <div class={styles.qrcodeBgDom}></div>

            <div class={styles.sectionGroup}>
              {/* <div class={styles.section}> */}
              {/* <div class={styles.memo}>{forms.urlItem.schoolName}</div>
                <div class={styles.qrcodeSection}>
                  <img src={qrbg} class={styles.qrbg} />
                  <MQrcode
                    class={styles.mqrcode}
                    text={forms.url}
                    logoSize={'small'}
                    size={'100%'}
                  />
                </div> */}
              <img src={imgs.image} class={styles.image} />
              {/* </div> */}
            </div>
          </div>

          <p class={styles.btnText}>长按保存二维码</p>
        </Popup>

        <div class={styles.templateSection}>
          <div class={[styles.shareContaienr]}>
            <img src={qrcodeBg} class={styles.qrcodeBg} />
            <div class={styles.sectionGroup}>
              <div class={styles.section} id="preview-container">
                <div class={styles.memo}>{forms.urlItem.schoolName}</div>
                <div class={styles.qrcodeSection}>
                  <img src={qrbg} class={styles.qrbg} />
                  <MQrcode
                    class={styles.mqrcode}
                    text={forms.url}
                    logoSize={'small'}
                    size={'100%'}
                    logoSrc={forms.urlItem.schoolLogo}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>

        <MWxTip />
      </div>
    );
  }
});
