import {FC, useState} from "react";
import {Image, View, Text} from "@tarojs/components";
import styles from "./home.module.scss";
import Adware from "@/pages/home/components/adware";
import Feature from "@/pages/home/components/feature";
import FeatureRecommended from "@/pages/home/components/feature_recommended";
import CurRecommended from "@/pages/home/components/curRecommended";
import MyButton from "@/components/button/MyButton";
import {Profile} from "@/store";
import Taro from "@tarojs/taro";
import {HomeApi, HomeData} from "@/api";
import logo from '@/static/img/logo.svg'
import Spin from "@/components/spinner";
import NavigationBar from "@/components/navigationBar/navigationBar";
import {Search} from "@/pages/home/components/search";

const Home: FC = () => {
  const globalData = Taro.getApp().globalData
  const {token} = Profile.useContainer()
  const [data, setData] = useState<null | HomeData>(null)
  const [enable, setEnable] = useState(true)
  const [navbarOpacity, setNavbarOpacity] = useState('0')
  const navbarHeight = globalData.statusBarHeight + globalData.textBarHeight;

  function unLogin() {
    Taro.clearStorage()
    Taro.navigateTo({url: '/pages/login/login'})
  }

  Taro.useDidShow(() => {
    HomeApi.home().then(res => {
      setData(res)
    })
    setTimeout(() => {
      setEnable(false)
    }, 600)
  })

  Taro.usePageScroll((e) => {
    const v = (Math.min(e.scrollTop / navbarHeight, 1) * 0.9).toFixed(6)
    if (v != navbarOpacity) {
      setNavbarOpacity(v)
    }
  })

  return (
    <>
      <NavigationBar
        className={styles.header}
        backgroundColor={`rgba(255,255,255,${navbarOpacity})`}
        cancelBack
        leftNode={
          <>
            <Image src={logo} style={{height: "90%"}} mode='heightFix'/>
            <Text className='font-36 font-weight ml-2'>信桂</Text>
          </>
        }
      >
        <View className={styles.headerDivider}
              style={{borderBottom: `1px solid rgba(200,200,200,${navbarOpacity})`}}></View>
      </NavigationBar>
      <Spin enable={enable} overlay/>
      <View className={styles.content} style={{paddingBottom: token ? 0 : '100rpx'}}>
        <Search/>
        <Adware data={data?.adverts || []} only_flag='routine_home_top_banner' width={710}/>
        <Feature/>
        <FeatureRecommended
          illness={data?.illness.list || []}
          health={data?.health || []}
          brand={data?.brand.list || []}
          skill={data?.skill || []}
        />
        <Adware data={data?.adverts || []} only_flag='routine_home_recommend_banner' width={710}/>
        {data && <CurRecommended/>}
        {
          !token && <View className={styles.tipsLogin}>
            <View>登录后享受更多服务~</View>
            <MyButton fillet size='mini' onClick={unLogin}>立即登录</MyButton>
          </View>
        }
      </View>
    </>
  )
}

export default Home
