import {useEffect, useState} from "react";
import {Map} from '@tarojs/components'
// import {Search} from '@nutui/icons-react-taro'
// import {Button, Input} from '@nutui/nutui-react-taro'
import {pageByQQMap} from "@/api/hjm/hjmCar";
import {HjmCar} from "@/api/hjm/hjmCar/model";
import './location.scss'
import {HjmFence} from "@/api/hjm/hjmFence/model";
import {getHjmFence} from "@/api/hjm/hjmFence";
import {Market} from "../pages/index";
// 导入GPS坐标转换工具
import GPS from '@/utils/gpsUtil.js';
interface Where {
  latitude?: number;
  longitude?: number;
}
/**
 * 文章终极列表
 * @constructor
 */
const Location = () => {
  // const [keywords, setKeywords] = useState<string>()
  // const [item, setItem] = useState<HjmCar>()
  const [longitude, setLongitude] = useState<any>(108.374959)
  const [latitude, setLatitude] = useState<any>(22.767024)
  const [scale, setScale] = useState<any>(16)
  const [showCircles, setShowCircles] = useState<boolean>(false)
  const [points, setPoints] = useState<any[]>([])
  const [fence, setFence] = useState<HjmFence>()
  const [markers, setMarkers] = useState<Market[]>([])

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

  // 通用的坐标字符串转数组函数
  const parseCoordinateString = (coordStr: string) => {
    if (!coordStr) return {points: []};

    try {
      // 分割坐标点
      const coordPairs = coordStr.split(';');

      // 转为多边形点数组
      const points = coordPairs.map(coord => {
        const [lat, lng] = coord.split(',');
        const latitude = parseFloat(lat);
        const longitude = parseFloat(lng);
        
        // 确保解析后的坐标是有效数字
        if (isNaN(latitude) || isNaN(longitude)) {
          throw new Error(`无效坐标: ${lat}, ${lng}`);
        }
        
        // 转换WGS84坐标到GCJ02坐标
        try {
          const transformed = GPS.gcj_encrypt(latitude, longitude);
          if (transformed && !isNaN(transformed.lat) && !isNaN(transformed.lng)) {
            return {
              latitude: transformed.lat,
              longitude: transformed.lng
            };
          }
        } catch (error) {
          console.error('围栏坐标转换错误:', error);
        }
        
        return {
          latitude: latitude,
          longitude: longitude
        }
      });
      console.log(points,'pointspointspoints')
      return {points};
    } catch (error) {
      console.error('解析坐标字符串失败:', error);
      return {points: []};
    }
  }

  const reload = () => {
    setScale(11)
    
    // 设置初始坐标（需要转换）
    const initialLat = 22.857968;
    const initialLng = 108.355702;
    try {
      const transformed = GPS.gcj_encrypt(initialLat, initialLng);
      if (transformed && !isNaN(transformed.lat) && !isNaN(transformed.lng)) {
        setLongitude(transformed.lng);
        setLatitude(transformed.lat);
      } else {
        setLongitude(initialLng);
        setLatitude(initialLat);
      }
    } catch (error) {
      console.error('初始坐标转换错误:', error);
      setLongitude(initialLng);
      setLatitude(initialLat);
    }
    
    getHjmFence(4).then(data => {
      setFence(data)
      const coordStr = data.points || '';

      // 使用通用函数解析坐标字符串（已包含坐标转换）
      const {points} = parseCoordinateString(coordStr);
      console.log('解析结果 - 多边形点:', points);
      setPoints(points);
      setShowCircles(true)
      console.log(fence,'fencefencefence')
    })
    
    const where: Where = {}
    // 使用转换后的坐标
    where.latitude = latitude
    where.longitude = longitude
    
    pageByQQMap(where).then(res => {
      if (res?.count == 0) {
        const arr = []
        // 转换默认位置坐标
        const defaultLat = 22.813371;
        const defaultLng = 108.323885;
        let markerLat = defaultLat;
        let markerLng = defaultLng;
        
        try {
          const transformed = GPS.gcj_encrypt(defaultLat, defaultLng);
          if (transformed && !isNaN(transformed.lat) && !isNaN(transformed.lng)) {
            markerLat = transformed.lat;
            markerLng = transformed.lng;
          }
        } catch (error) {
          console.error('默认位置坐标转换错误:', error);
        }
        
        // @ts-ignore
        arr.push({
          id: 10001,
          latitude: markerLat,
          longitude: markerLng,
          title: '当前位置',
          name: '当前位置'
        })
        setMarkers(arr)
        return false
      }
      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) {
            try {
              const lat = Number(item.latitude);
              const lng = Number(item.longitude);
              if (!isNaN(lat) && !isNaN(lng) && isFinite(lat) && isFinite(lng)) {
                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,
            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)
      }
    })
  }

  useEffect(() => {
    reload()
  }, [])

  // 监听圈圈数据变化
  useEffect(() => {
  }, [showCircles])

  return (
    <>
      {/*<div className={'fixed z-20 top-5 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}*/}
      {/*      />*/}
      {/*      <div*/}
      {/*        className={'flex items-center'}*/}
      {/*      >*/}
      {/*        <Button type="warning" onClick={reload}>*/}
      {/*          查询*/}
      {/*        </Button>*/}
      {/*      </div>*/}
      {/*    </div>*/}
      {/*  </div>*/}
      {/*</div>*/}
      {/*{item ? (*/}
      {/*  <div className={'car-info fixed bottom-0 left-0 w-full z-20 bg-white p-4'}>*/}
      {/*    <div className={'car-info-item'}>*/}
      {/*      <div className={'car-info-item-content'}>*/}
      {/*        操作人员：{item?.driver}*/}
      {/*      </div>*/}
      {/*      <div className={'car-info-item-content pr-6'}>*/}
      {/*        电子围栏：{item?.fenceName} ({item?.inFence ? '围栏内' : '围栏外'})*/}
      {/*      </div>*/}
      {/*      <div className={'car-info-item-content pr-6'}>*/}
      {/*        当前车速：{item?.speed}*/}
      {/*      </div>*/}
      {/*      <div className={'car-info-item-title'}>*/}
      {/*        更新时间：{item?.updateTime}*/}
      {/*      </div>*/}
      {/*    </div>*/}
      {/*  </div>*/}
      {/*) : ''}*/}

      {markers.length > 0 && (
        <Map
          id="map"
          longitude={longitude}
          latitude={latitude}
          scale={scale}
          // @ts-ignore
          markers={markers}
          polygons={points.length > 0 ? [
            {
              points: points,
              color: '#ff0000',
              strokeWidth: 3
            }
          ] : []}
          onTap={() => {
            console.log('map tap')
          }}
          style={{width: '100%', height: '100vh'}}
        />
      )}
    </>
  )
}
export default Location
