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 {useRouter} from '@tarojs/taro'
import {getHjmCar, getHjmCarByCode} from "@/api/hjm/hjmCar";
import {HjmCar} from "@/api/hjm/hjmCar/model";
import './location.scss'

/**
 * 文章终极列表
 * @constructor
 */
const Location = () => {
  const {params} = useRouter();
  const [keywords, setKeywords] = useState<string>()
  const [item, setItem] = useState<HjmCar>()
  const [longitude, setLongitude] = useState<any>()
  const [latitude, setLatitude] = useState<any>()
  const [scale, setScale] = useState<any>(16)
  const [showCircles, setShowCircles] = useState<boolean>(false)
  const [points, setPoints] = useState<any[]>([])

  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(',');
        return {
          latitude: parseFloat(lat),
          longitude: parseFloat(lng)
        }
      });

      return { points };
    } catch (error) {
      console.error('解析坐标字符串失败:', error);
      return { points: [] };
    }
  }

  const reload = () => {
    const id = Number(params.id);
    setScale(14)
    // 执行搜索
    if (keywords) {
      getHjmCarByCode(keywords).then(data => {
        console.log('执行搜索', data)
        setItem(data)
        setLatitude(data.latitude)
        setLongitude(data.longitude)
        setKeywords(data.code)
        if (data.fence) {
          // 方法2：使用实际的 fence 数据（如果是字符串格式）
          const coordStr = data.fence.points || '';

          // 使用通用函数解析坐标字符串
          const { points } = parseCoordinateString(coordStr);
          console.log('解析结果 - 多边形点:', points);
          setPoints(points);
          setShowCircles(true)
        }
      })
      return false;
    }
    // 获取车辆信息
    if (id) {
      getHjmCar(id).then(data => {
        setItem(data)
        setLatitude(data.latitude)
        setLongitude(data.longitude)
        setKeywords(data.code)
        if (data.fence) {
          // 方法2：使用实际的 fence 数据（如果是字符串格式）
          const coordStr = data.fence.points || '';

          // 使用通用函数解析坐标字符串
          const { points } = parseCoordinateString(coordStr);
          console.log('解析结果 - 多边形点:', points);
          setPoints(points);
          setShowCircles(true)
        }
      })
    }
  }

  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-title'}>
              最后更新时间：{item?.updateTime}
            </div>
            <div className={'car-info-item-content'}>
              操作员：{item?.driver}
            </div>
            {/*<div className={'car-info-item-content pr-6'}>*/}
            {/*  位置信息：{item?.address}*/}
            {/*</div>*/}
          </div>
        </div>
      ) : ''}

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

    </>
  )
}
export default Location
