import Header from './Header'
// import BestSellers from "./BestSellers";
import './index.scss'
import Taro from '@tarojs/taro';
import {Map} from '@tarojs/components'
import {Search} from '@nutui/icons-react-taro'
import {Button, Input} from '@nutui/nutui-react-taro'
// import {InfiniteLoading} from '@nutui/nutui-react-taro'
import {useShareAppMessage, useShareTimeline} from "@tarojs/taro"
import {useEffect, useState} from "react";
import ExpirationTime from "./ExpirationTime";
import {User} from "@/api/system/user/model";
import {getSiteInfo, getUserInfo, getWxOpenId} from "@/api/layout";
import Login from "./Login";
import {CmsWebsite} from "@/api/cms/cmsWebsite/model";
import {pageByQQMap, pageHjmCar} from "@/api/hjm/hjmCar";
import {HjmCar} from "@/api/hjm/hjmCar/model";

export interface Market {
  // 自增ID
  id?: number;
  latitude?: number;
  longitude?: number;
  name?: string;
  title?: string;
}

function Home() {
  const [website, setWebsite] = useState<CmsWebsite>()
  const [IsLogin, setIsLogin] = useState<boolean>(true)
  const [userInfo, setUserInfo] = useState<User>()
  const [longitude, setLongitude] = useState<any>(108.374959)
  const [latitude, setLatitude] = useState<any>(22.767024)
  const [markers, setMarkers] = useState<Market[]>([])
  const [scale, setScale] = useState<any>(16)
  const [keywords, setKeywords] = useState<string>('')
  const [list, setList] = useState<HjmCar[]>([])
  console.log(userInfo?.nickname)
  console.log(website?.websiteName)
  console.log(list.length)
  // const [hasMore, setHasMore] = useState(true)
  // const [list, setList] = useState<BszxPay[]>([])
  // const [page, setPage] = useState(1)

  useShareTimeline(() => {
    return {
      title: '注册即可开通 - webSoft云应用',
      path: `/pages/index/index`
    };
  });

  useShareAppMessage(() => {
    return {
      title: '注册即可开通 - webSoft云应用',
      path: `/pages/index/index`,
      success: function (res) {
        console.log('分享成功', res);
      },
      fail: function (res) {
        console.log('分享失败', res);
      }
    };
  });

  // const reloadMore = async () => {
  //   setPage(page + 1)
  // }

  const showAuthModal = () => {
    Taro.showModal({
      title: '授权提示',
      content: '需要获取您的用户信息',
      confirmText: '去授权',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          // 用户点击确认，打开授权设置页面
          openSetting();
        }
      }
    });
  };

  const openSetting = () => {
    // Taro.openSetting：调起客户端小程序设置界面，返回用户设置的操作结果。设置界面只会出现小程序已经向用户请求过的权限。
    Taro.openSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          // 用户授权成功，可以获取用户信息
          reload();
        } else {
          // 用户拒绝授权，提示授权失败
          Taro.showToast({
            title: '授权失败',
            icon: 'none'
          });
        }
      }
    });
  };

  const onKeywords = (keywords: string) => {
    setKeywords(keywords)
  }

  // 登录成功后回调
  const handleLogin = (data: User) => {
    setIsLogin(true)
    setUserInfo(data)
    Taro.showTabBar()
    reload();
  }

  // 获取当前位置
  const getLocation = async () => {
    try {
      const res = await Taro.getLocation({
        type: 'gcj02' //返回可以用于wx.openLocation的经纬度
      })
      pageByQQMap({
        latitude: res.latitude,
        longitude: res.longitude,
      }).then(res => {
        if (res?.list && res?.list.length > 0) {
          const data = res?.list;
          const arr = []
          data?.map((item: HjmCar) => {
            // @ts-ignore
            arr.push({
              id: item.id,
              latitude: item.latitude,
              longitude: item.longitude,
              title: `${item.organization}`,
              name: item.organization
            })
          })
          setMarkers(arr)
        }
      })
      if (res.latitude) {
        setLatitude(res.latitude)
      }
      if (res.longitude) {
        setLongitude(res.longitude)
      }
      console.log(res)
      console.log('当前位置：', res.latitude, res.longitude);
      return res;
    } catch (err) {
      console.error('获取位置失败：', err);
    }
  }

  const reload = () => {
    setMarkers([])
    pageHjmCar({keywords}).then(res => {
      setList(res?.list || [])
      if (res?.list && res?.list.length > 0) {
        setScale(16)
        const data = res?.list[0];
        setLongitude(data?.longitude)
        setLatitude(data?.latitude)
        setMarkers([{
          id: data.id,
          latitude: data.latitude,
          longitude: data.longitude,
          title: `${data.organization}`,
          name: `${data.organization}`
        }])
      }
    })
  };

  useEffect(() => {
    // Taro.hideTabBar()
    setScale(14)
    getLocation().then()
    // 获取站点信息
    getSiteInfo().then((data) => {
      console.log(data, 'siteInfo')
      setWebsite(data)
    })
    // Taro.getSetting：获取用户的当前设置。返回值中只会出现小程序已经向用户请求过的权限。
    Taro.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          // 用户已经授权过，可以直接获取用户信息
          console.log('用户已经授权过，可以直接获取用户信息')
          reload();
        } else {
          // 用户未授权，需要弹出授权窗口
          console.log('用户未授权，需要弹出授权窗口')
          showAuthModal();
        }
      }
    });
    // 获取用户信息
    Taro.getUserInfo({
      success: (res) => {
        const avatar = res.userInfo.avatarUrl;
        setUserInfo({
          avatar,
          nickname: res.userInfo.nickName,
          sexName: res.userInfo.gender == 1 ? '男' : '女'
        })
        getUserInfo().then((data) => {
          if (data) {
            setUserInfo(data)
            setIsLogin(true);
            Taro.setStorageSync('UserId', data.userId)
            // 获取openId
            if (!data.openid) {
              Taro.login({
                success: (res) => {
                  getWxOpenId({code: res.code}).then(() => {
                  })
                }
              })
            }
          }
        }).catch(() => {
          setIsLogin(false);
          console.log('未登录')
        });
      }
    });
  }, []);

  return (
    <>
      {!IsLogin ? (<Login done={handleLogin}/>) : (<>
        <Header user={userInfo}/>
        <ExpirationTime/>
        <div className={'fixed z-20 top-24 left-0 w-full'}>
          <div className={'px-4'}>
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                background: '#fff',
                padding: '0 10px',
                borderRadius: '20px'
              }}
            >
              <Search/>
              <Input
                placeholder="车辆编号"
                value={keywords}
                onChange={onKeywords}
                onConfirm={reload}
              />
              <div
                className={'flex items-center'}
              >
                <Button type="warning" onClick={reload}>
                  查询
                </Button>
              </div>
            </div>
          </div>
        </div>
        <Map
          id="map"
          longitude={longitude}
          latitude={latitude}
          scale={scale}
          // @ts-ignore
          markers={markers}
          onTap={(map) => {
            console.log('map tap',map)
          }}
          style={{width: '100%', height: '100vh'}}
        />
        {/*<InfiniteLoading*/}
        {/*  className={'w-full fixed left-0 top-40'}*/}
        {/*>*/}
        {/*  <BestSellers data={list}/>*/}
        {/*</InfiniteLoading>*/}
      </>)}
    </>
  )
}

export default Home
