import React, { useState, useEffect } from 'react'
import NavHeader from '@/components/NavHeader/index'
import { Swiper, SwiperItem, Text } from '@tarojs/components'
import request, { apis } from '@/utils/request'
import { useModel } from '@/store'
import useUserMounted from '@/utils/hooks/useUserMounted'
import Taro from '@tarojs/taro'
import Page from '@/layouts'
import '@/assets/css/reset.less'
import '@/assets/css/iconfont.less'
import './index.less'

export default function Index (props) {

  const { user } = useModel('user')
  const [ShowAdvLayer, setShowAdvLayer] = useState(false)
  const [IsPull, setIsPull] = useState(false)
  const [OwnerList] = useState([
    { icon: 'iconjiaofei', name: '物业缴费', id: 1, router: '/pages/WuYe/index', isTab: true },
    { icon: 'icontongzhi', name: '物业通知', id: 2, router: '/pages/WuYe/index', isTab: true },
    { icon: 'iconbaoxiu', name: '物业报修', id: 3, router: '/pages/WuYe/index', isTab: true },
    { icon: 'iconrenzheng', name: '业主认证', id: 4, router: '/pages/WoDe/WoDeRenZheng/index', isTab: false }
  ])
  const [NavList] = useState([
    { icon: 'iconhuodong1', name: '活动', id: 1, router: '/pages/ShouYe/HuoDong/index', isTab: false },
    { icon: 'iconfuli', name: '福利', id: 2, router: '/pages/FuLi/index', isTab: true },
    { icon: 'iconfuwu', name: '服务', id: 3, router: '/pages/WuYe/index', isTab: true },
    { icon: 'iconxinwen', name: '资讯', id: 4, router: '/pages/ShouYe/ZiXun/index', isTab: false }
  ])
  const [BannerList, setBannerList] = useState([])
  const [ActivityList, setActivityList] = useState([])
  const [NewsList, setNewsList] = useState([])

  // useEffect(() => {
  //   if (user) {
  //     console.log(user, `user`)
  //     OnRefresh()
  //   }
  // }, [user])

  useUserMounted(() => {
    console.log(user, `user`)
    OnRefresh()
  })

  const Init = (done = () => { }) => { // 初始化
    let DownCount = 0
    GetBanner(() => { // 获取轮播图
      DownCount += 1
      if (CheckDownCount(DownCount)) {
        done()
      }
    })
    GetActivityList(() => { // 获取活动列表
      DownCount += 1
      if (CheckDownCount(DownCount)) {
        done()
      }
    })
    GetNewsList(() => { // 获取资讯列表
      DownCount += 1
      if (CheckDownCount(DownCount)) {
        done()
      }
    })
  }

  const GetBanner = (done = () => { }) => { // 获取轮播图
    setBannerList([])
    request({ ...apis.getBanner, params: { contentType: `activity` } }).then((res) => {
      setBannerList([...res.records])
      done()
    }).catch(() => {
      done()
    })
  }

  const GetActivityList = (done = () => { }) => { // 获取活动列表
    setActivityList([])
    request({ ...apis.getActivityList, params: { pageNum: 1, pageSize: 1 } }).then((res) => {
      setActivityList([...res.list])
      done()
    }).catch(() => {
      done()
    })
  }

  const GetNewsList = (done = () => { }) => { // 获取资讯列表
    setNewsList([])
    request({ ...apis.getNewsList, params: { pageNum: 1, pageSize: 10 } }).then((res) => {
      setNewsList([...res.records])
      done()
    }).catch(() => {
      done()
    })
  }

  const CheckDownCount = (num) => { // 检测请求接口数量
    return num >= 3
  }

  const NavClick = (item) => {
    return () => {
      if (item.isTab) {
        Taro.switchTab({ url: item.router })
      } else {
        Taro.navigateTo({ url: item.router })
      }
    }
  }

  const OnRefresh = () => { // 页面下拉刷新
    setIsPull(true)
    Init(() => {
      setIsPull(false)
    })
  }

  const OnPullUp = () => { // 上拉加载
    // console.log(111)
  }

  const OwnerClick = (item) => {
    return () => {
      if (item.isTab) {
        Taro.switchTab({ url: item.router })
      } else {
        Taro.navigateTo({ url: item.router })
      }
    }
  }

  return (
    <Page>
      <view className='ShouYe flex-v'>
        <NavHeader BgColor='#f35844' Title='首页'></NavHeader>
        <view className='flex-item'>

          {/* 广告 */}
          <view className='AdvLayer' style={{ display: ShowAdvLayer ? 'block' : 'none' }}>
            <view className='centerLabel'>
              <image mode='aspectFit' src={null}></image>
              <Text className='iconfont iconguanbi'></Text>
            </view>
          </view>

          {/* 正文 */}
          <view className='PageContainer'>
            <scroll-view scroll-y='true' style='height: 100%;' refresher-enabled={true} onscrolltolower={OnPullUp} onrefresherrefresh={OnRefresh} refresher-triggered={IsPull} refresher-background='#f35844'>
              <view className='Content'>

                {/* 背景图 */}
                <view className='TopBg'></view>

                <view>

                  {/* 欢迎词 */}
                  <Text className='Welcome'>欢迎来到远道智慧社区！</Text>

                  {/* banner */}
                  <view className='BannerContainer'>
                    <view>
                      <view>
                        <Swiper className='BannerSwiper' autoplay circular indicator-dots indicator-color='rgba(0,0,0,0.4)' indicator-active-color='rgba(255,255,255,0.8)'>
                          {
                            BannerList.map((item, index) => (
                              <SwiperItem className='SwiperItem' key={`Banner-${index}`}>
                                <view className='BannerItem'>
                                  <image mode='aspectFill' src={item.img}></image>
                                </view>
                              </SwiperItem>
                            ))
                          }
                        </Swiper>
                      </view>
                    </view>
                  </view>

                  {/* 导航 */}
                  <view className='NavContainer flex-h'>
                    {
                      NavList.map((item, index) => (
                        <view key={`Nav-${index}`} className='flex-item'>
                          <view onClick={NavClick(item)}>
                            <view className='centerLabel'>
                              <Text className={`iconfont ${item.icon}`}></Text>
                              <Text>{item.name}</Text>
                            </view>
                          </view>
                        </view>
                      ))
                    }
                  </view>

                  {/* 热门活动 */}
                  {
                    ActivityList.length > 0 &&
                    <view className='HotActivityContainer'>
                      <view>
                        <view className='Title'>
                          <Text onClick={() => { Taro.navigateTo({ url: '/pages/ShouYe/HuoDong/index' }) }}>热门活动</Text>
                          <Text className='iconfont icongengduo' onClick={() => { Taro.navigateTo({ url: '/pages/ShouYe/HuoDong/index' }) }}></Text>
                        </view>
                        <view className='Activity' onClick={() => { Taro.navigateTo({ url: `/pages/HuoDong/HuoDongDetail/index?id=${ActivityList[0].dynamicId}` }) }}>
                          <image className='centerLabel' mode='aspectFill' src={ActivityList[0].imgUrl}></image>
                        </view>
                      </view>
                    </view>
                  }

                  {/* 业主专区 */}
                  <view className='OwnerContainer'>
                    <view>
                      <view className='Title'>
                        <Text>业主专区</Text>
                      </view>
                      <view className='OwnerList flex-h'>
                        {
                          OwnerList.map((item, index) => (
                            <view className='flex-item' key={`Owners-${index}`} onClick={OwnerClick(item)}>
                              <Text className={`iconfont ${item.icon}`}></Text>
                              <Text>{item.name}</Text>
                            </view>
                          ))
                        }
                      </view>
                    </view>
                  </view>

                  {/* 热门资讯 */}
                  <view className='NewsContainer'>
                    <view>
                      <view className='Title flex-h'>
                        <Text className='flex-item'>热门资讯</Text>
                        <Text onClick={() => { Taro.navigateTo({ url: '/pages/ShouYe/ZiXun/index' }) }}>查看全部</Text>
                        <Text className='iconfont iconjiantouright'></Text>
                      </view>
                      <view className='List'>
                        {
                          NewsList.map((item, index) => (
                            <view key={`News-${index}`} className='flex-h' onClick={() => { Taro.navigateTo({ url: `/pages/HuoDong/ZiXunDetail/index?id=${item.newsId}` }) }}>
                              <view className='Img'>
                                <image mode='aspectFill' src={item.newsImg} className='centerLabel'></image>
                              </view>
                              <view className='flex-item'>
                                <Text>{item.newsName}</Text>
                                <Text>{item.desc || ''}</Text>
                              </view>
                            </view>
                          ))
                        }
                      </view>
                    </view>
                  </view>

                  <view className='PageBottom'></view>

                </view>

              </view>
            </scroll-view>
          </view>

        </view>
      </view >
    </Page>
  )
}
