import Header from './Header'
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 {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 {pageByQQMap, pageHjmCar} from "@/api/hjm/hjmCar";
import {HjmCar} from "@/api/hjm/hjmCar/model";
// 导入GPS坐标转换工具
import GPS from '@/utils/gpsUtil.js';
import tricycleIcon from '@/assets/icons/delivery_tricycle.png';

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

function Home() {
  const [loading, setLoading] = useState<boolean>(false)
  const [IsLogin, setIsLogin] = useState<boolean>(true)
  const [isAdmin, setIsAdmin] = useState<boolean>(false)
  const [search, setSearch] = useState(false)
  const [userInfo, setUserInfo] = useState<User>()
  const [longitude, setLongitude] = useState<any>()
  const [latitude, setLatitude] = useState<any>()
  const [markers, setMarkers] = useState<Market[]>([])
  const [scale, setScale] = useState<any>(12)
  const [keywords, setKeywords] = useState<string>('')
  const [list, setList] = useState<HjmCar[]>([])

  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: 'wgs84' // 使用WGS84坐标系，然后手动转换为GCJ02
      })

      // 转换WGS84坐标到GCJ02坐标
      if (res.latitude && res.longitude &&
          !isNaN(res.latitude) &&
          !isNaN(res.longitude) &&
          isFinite(res.latitude) &&
          isFinite(res.longitude)) {
        try {
          const lat = Number(res.latitude);
          const lng = Number(res.longitude);
          const transformed = GPS.gcj_encrypt(lat, lng);
          // 确保转换结果有效
          if (transformed && !isNaN(transformed.lat) && !isNaN(transformed.lng)) {
            setLatitude(transformed.lat);
            setLongitude(transformed.lng);
          } else {
            // 如果转换结果无效，使用原始坐标
            setLatitude(res.latitude);
            setLongitude(res.longitude);
          }
        } catch (error) {
          console.error('坐标转换错误:', error);
          setLatitude(res.latitude);
          setLongitude(res.longitude);
        }
      } else {
        setLatitude(res.latitude);
        setLongitude(res.longitude);
      }

      // 已认证用户
      if (Taro.getStorageSync('Certification')) {
        setIsAdmin(true)
        setScale(11)
        // pageHjmCarByMap(res.latitude, res.longitude)
      }

      // 游客
      if (!Taro.getStorageSync('access_token') || Taro.getStorageSync('RoleName') == '注册用户') {
        setScale(15)
      }
      return res;
    } catch (err) {
      console.error('获取位置失败：', err);
    }
  }

  const onQuery = () => {
    if (!keywords) {
      Taro.showToast({
        title: '请输入关键字',
        icon: 'none'
      });
      return false;
    }
    reload();
  }

  const pageHjmCarByMap = async (latitude?: any, longitude?: any) => {
    // 搜索条件
    const where = {}

    const user = await getUserInfo();

    if (latitude) {
      // @ts-ignore
      where.latitude = latitude
    }
    if (longitude) {
      // @ts-ignore
      where.longitude = longitude
    }
    // 判断身份
    const roleCode = Taro.getStorageSync('RoleCode');
    if (roleCode == 'kuaidiyuan') {
      // @ts-ignore
      where.driverId = user.userId;
    }
    if (roleCode == 'zhandian') {
      // @ts-ignore
      where.organizationId = user.organizationId;
    }
    // 邮管（youzheng）可以查看管辖范围内车辆，通过 organizationParentId 查询
    if (roleCode == 'youzheng') {
      // @ts-ignore
      // where.organizationParentId = undefined;
      where.limit = 1000;
      // @ts-ignore
      where.status = 1;
    }
    if (roleCode == 'kuaidi') {
      // @ts-ignore
      where.organizationParentId = user.organizationId;
    }

    pageByQQMap(where).then(res => {
      console.log(res?.count, 'pageByQQMap')
      if (res?.list && res?.list.length > 0) {
        const data = res?.list;
        const arr = []
        data?.map((item: HjmCar) => {
          // 转换WGS84坐标到GCJ02坐标
          let markerLat = item.latitude;
          let markerLng = item.longitude;

          if (item.latitude && item.longitude &&
              !isNaN(item.latitude) &&
              !isNaN(item.longitude) &&
              isFinite(item.latitude) &&
              isFinite(item.longitude)) {
            try {
              const lat = Number(item.latitude);
              const lng = Number(item.longitude);
              const transformed = GPS.gcj_encrypt(lat, lng);
              if (transformed && !isNaN(transformed.lat) && !isNaN(transformed.lng)) {
                markerLat = transformed.lat;
                markerLng = transformed.lng;
              }
            } catch (error) {
              console.error('标记点坐标转换错误:', error);
            }
          }

          // @ts-ignore
          arr.push({
            id: item.id,
            latitude: markerLat,
            longitude: markerLng,
            iconPath: tricycleIcon,
            width: 32,
            height: 32,
            label: {
              content: `${item?.code}`,
              color: '#000000',
              fontSize: 12,
              borderRadius: 5,
              bgColor: '#FFFFFF',
              // @ts-ignore
              padding: '5px 5px',
              borderWidth: 1
            },
            title: `${item.organization}`,
            name: item.organization
          })
        })
        setMarkers(arr)
      }
    })
  }

  const reload = async () => {
    setLoading(true)
    if (!Taro.getStorageSync('access_token')) {
      return false;
    }

    pageHjmCarByMap(latitude, longitude)
    if (!isAdmin) {
      return false;
    }
    setMarkers([])
    setScale(12)
    pageHjmCar({keywords, deleted: 0}).then(res => {
      if (res?.count == 0) {
        Taro.showToast({
          title: '没有搜索结果',
          icon: 'none'
        });
        return false
      }
      setList(res?.list || [])
      if (res?.list && res?.list.length > 0) {
        const data = res?.list[0];

        // 转换WGS84坐标到GCJ02坐标
        let displayLat = data.latitude;
        let displayLng = data.longitude;

        if (data.latitude && data.longitude &&
            !isNaN(data.latitude) &&
            !isNaN(data.longitude) &&
            isFinite(data.latitude) &&
            isFinite(data.longitude)) {
          try {
            const lat = Number(data.latitude);
            const lng = Number(data.longitude);
            const transformed = GPS.gcj_encrypt(lat, lng);
            if (transformed && !isNaN(transformed.lat) && !isNaN(transformed.lng)) {
              displayLat = transformed.lat;
              displayLng = transformed.lng;
            }
          } catch (error) {
            console.error('搜索结果坐标转换错误:', error);
          }
        }

        setLongitude(displayLng)
        setLatitude(displayLat)
        if (isAdmin) {
          setMarkers([{
            id: data.id,
            latitude: displayLat,
            longitude: displayLng,
            iconPath: tricycleIcon,
            width: 32,
            height: 32,
            // @ts-ignore
            label: {
              content: `${data?.code}`,
              color: '#000000',
              fontSize: 12,
              borderRadius: 5,
              bgColor: '#FFFFFF',
              // @ts-ignore
              padding: '5px 5px',
              borderWidth: 1
            },
            title: `${data.organization}`,
            name: `${data.organization}`
          }])
        }
      }
      console.log(list.length, 'carList.length')
    })
  };

  useEffect(() => {
    // Taro.hideTabBar()
    getLocation().then()
    // 获取站点信息
    getSiteInfo().then((data) => {
      console.log(data, 'siteInfo')
      if (data.search) {
        setSearch(false);
      }
    })
    // Taro.getSetting：获取用户的当前设置。返回值中只会出现小程序已经向用户请求过的权限。
    Taro.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          // 用户已经授权过，可以直接获取用户信息
          console.log('用户已经授权过，可以直接获取用户信息')
          reload().then(() => {
            setLoading(false)
          });
        } 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) {
            // 是否管理员
            if (data.certification) {
              setIsAdmin(true)
            }
            // 是否交警
            if (Taro.getStorageSync('Certification') == 'jj') {
              console.log('交警', '12312')
              setIsAdmin(true)
            }
            if (Taro.getStorageSync('RoleCode') == 'Installer') {
              setIsAdmin(true)
            }
            setUserInfo(data)
            setIsLogin(true);
            Taro.setStorageSync('UserId', data.userId)
            // 获取openId
            if (!data.openid) {
              Taro.login({
                success: (res) => {
                  // 排查交警和邮政角色不保存openid
                  if (Taro.getStorageSync('RoleCode') !== 'jiaojing' || Taro.getStorageSync('RoleCode') !== 'youzheng' || Taro.getStorageSync('RoleCode') !== 'Installer') {
                    getWxOpenId({code: res.code}).then(() => {
                    })
                  }
                }
              })
            }
          }
        }).catch(() => {
          setIsLogin(false);
          console.log('未登录')
        });
      }
    });
  }, []);

  return (
    <>
      {!IsLogin && search ? (<Login done={handleLogin}/>) : (<>
        <Header user={userInfo}/>
        <ExpirationTime/>
        <div className={'fixed z-20 top-24 left-0 w-full'}>
          <div className={'px-2'}>
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                background: '#fff',
                padding: '0 7px',
                borderRadius: '20px'
              }}
            >
              <Search className={'mx-2'}/>
              <Input
                placeholder="车辆编号"
                value={keywords}
                onChange={onKeywords}
                onConfirm={onQuery}
              />
              <div
                className={'flex items-center'}
              >
                <Button type="warning" onClick={onQuery}>
                  查询
                </Button>
              </div>
            </div>
          </div>
        </div>
        {!loading && (
          <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'}}
          />
        )}
      </>)}
    </>
  )
}

export default Home
