import React, { useEffect, useState, useRef } from 'react';
import {PullToRefresh ,InfiniteScroll,List} from 'antd-mobile';
import {useNextPage,useLoading} from '@/hooks';
import {GET_USER_LIST} from '@/services/user';
import { useParams, useSearchParams,useNavigate } from 'react-router-dom';

import ProviderApp from '@/provider/app';
import moment from 'moment';
import ShowToast from '@/components/Toast';
import {useUserType} from '@/dictionary';
import {AuthShow} from '@/components/Auth';

import styles from './index.less';

const Page = () => {
  const navigate= useNavigate();
  const providerApp = ProviderApp.useContainer();
  const query = useParams();
  const [search] = useSearchParams();
  const request = useNextPage({
    service:GET_USER_LIST,
  })
  const [list,setList]= useState([]);
  const loading = useLoading();
  const loadingCanTouch = useLoading({canTouch:true});

  const emUserType= useUserType();

  useEffect(()=>{
    let ret=[];
    request?.data?.forEach(page=>{
      try{
      ret = [...ret,...page];
      }catch(ex){
        console.error(ex)
        debugger;
      }
    })
    setList(ret);

  },[request.data])


  const onReset= async ()=>{
    return request.reset();
  }

  const onNextPage= async ()=>{
    if(loading.loading>0){
      return;
    }
    loading.setLoading(true)
    let dom = document.querySelector('#wall');
    dom.scrollTop-=200;
    await request.nextPage();
    loading.setLoading(false)
    return true;
  }
  const refresh=async ()=>{
    loading.setLoading(true)
    await request.refresh(); 
    loading.setLoading(false);
  }
  useEffect(()=>{
    refresh();
  },[]);

  return (
    <section id="wall" className={styles.wall}>
      <PullToRefresh className={styles.wrap}
        onRefresh={async () => {
          await onReset();
          return true;
        }}
      >
        <List header='导航栏'>
          <List.Item key='navShow' onClick={()=>{
            providerApp.setNav({visible:!providerApp.nav.visible});
          }}>隐藏/隐藏导航栏</List.Item>

          <List.Item key='navTitle' onClick={()=>{
            providerApp.setNav({title:moment().format('YYYY-MM-DD HH:mm:ss')});
          }}>修改标题</List.Item>

          <List.Item key='navSyncTitle' onClick={()=>{
            providerApp.setNav({syncDocumentTitle:!providerApp.nav.syncDocumentTitle});
          }}>开启/关闭同步导航栏和网页标签标题</List.Item>

        </List>

        <List header='路由'>
          <List.Item key='query'>动态路由id:{query.id}</List.Item>
          <List.Item key='search'>url search:{search.toString()}</List.Item>
        </List>

        <List header='登录态'>
          <List.Item key='loginStatus'>登录状态：{providerApp?.user?.id?`已登录:${providerApp?.user?.id}`:'未登录'}</List.Item>
          {
            providerApp?.user?.id?
            <List.Item key='logout' onClick={()=>{
              providerApp.logout()}
            }>注销</List.Item>:
            <List.Item key='login' onClick={async ()=>{
                loading.setLoading(true);
                await providerApp.login();
                loading.setLoading(false)
              }
            }>登录</List.Item>
          }
          <List.Item key='toUserPage' onClick={()=>{
            navigate('/user');
          }}>前往用户信息页面</List.Item>

          <AuthShow name='normal'><List.Item key='user'>用户登录完才能看到这行</List.Item></AuthShow>
        </List>

        <List header='消息框'>
          <List.Item key='toast' onClick={()=>{ShowToast(`现在时间:${moment().format('HH:mm:ss')}`)}}>Toast</List.Item>
        </List>
        
        <List header='Loading'>
          <List.Item key='loading' onClick={async ()=>{
            loading.setLoading(true);
            await new Promise(resolve=>{
              setTimeout(resolve,3000);
            });
            loading.setLoading(false);
          }}>打开全局loading-持续3秒(阻止其它交互)</List.Item>
          <List.Item key='loadingCanTouch' onClick={async ()=>{
            loadingCanTouch.setLoading(true);
            await new Promise(resolve=>{
              setTimeout(resolve,3000);
            });
            loadingCanTouch.setLoading(false);
          }}>打开全局loading-持续3秒(不阻止交互)</List.Item>
        </List>
        
        <List header='字典'>
          {
            emUserType.isReady()&&emUserType.getList().map(item=>{
              return <List.Item key={item.key} data-value={item.value} onClick={ (e)=>{
                let value = e.currentTarget.getAttribute('data-value');
                let item = emUserType.getData({id:value});
                ShowToast(`${JSON.stringify(item)}`)
              }}>{item.label}</List.Item>
            })
          }
        </List>

        <List header='下拉刷新，滚动加载案例'>
          {
            list.map((item,idx)=>{
              return (
                <List.Item key={item.name}>{item.name}-{item.resetCount}</List.Item>
              )
            })
          }
        </List>
    
      </PullToRefresh>
      <InfiniteScroll threshold={40} loadMore={onNextPage} hasMore={request.pagination.more} />

    </section>
  )
}

export default Page;