import {useEffect, useState} from "react";
import {Map} from '@tarojs/components'
import Taro, {useRouter} from '@tarojs/taro'
import {DatePicker, Button, type PickerOption} from '@nutui/nutui-react-taro'
import {getHjmCarByCode} from "@/api/hjm/hjmCar";
import {HjmCar} from "@/api/hjm/hjmCar/model";
import './trajectory.scss'
import {pageHjmGpsLog} from "@/api/hjm/hjmGpsLog";
import {formatCurrentDate, getCurrentHour} from "@/utils/time";
import GPS from '@/utils/gpsUtil.js';
import tricycleIcon from '@/assets/icons/delivery_tricycle.png';

/**
 * 文章终极列表
 * @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 [hjmGpsLog, setHjmGpsLog] = useState<any[]>([])
  const [ddmmyy, setDdmmyy] = useState<string>(formatCurrentDate())
  const [hhmmss, setHhmmss] = useState<string>(getCurrentHour())
  const [show1, setShow1] = useState(false)
  const defaultValue = new Date()
  const defaultDescription = `${defaultValue.getFullYear()}年${defaultValue.getMonth() + 1}月${defaultValue.getDate()}日`
  const [desc1, setDesc1] = useState(defaultDescription)
  // 选择时分秒
  const startDate = new Date(2025, 0, 1)
  const endDate = new Date(2030, 10, 1)
  const [show, setShow] = useState(false)

  // 通用的坐标字符串转数组函数
  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 onKeywords = (keywords: string) => {
  //   setKeywords(keywords)
  // }

  // @ts-ignore
  const confirm = (values: any, options: PickerOption[]) => {
    // 截取字符串后2位
    console.log(`${String(values[2]).padStart(2, '0')}${String(values[1]).padStart(2, '0')}${String(values[0]).slice(-2)}`, 'options')
    setDdmmyy(`${String(values[2]).padStart(2, '0')}${String(values[1]).padStart(2, '0')}${String(values[0]).slice(-2)}`);
    setDesc1(options.map((option) => option.text).join(' '))
    // const v = values.join('-')
    // setValue(v)
    getLocationRecord(item)
  }

  const onAfter = () => {
    setHhmmss(`${String(Number(hhmmss) + 1).padStart(2, '0')}`)
    getLocationRecord(item)
  }
  const onBefore = () => {
    setHhmmss(`${String(Number(hhmmss) - 1).padStart(2, '0')}`)
    getLocationRecord(item)
  }
  // const change = (options: PickerOption[], values: (string | number)[]) => {
  //   // console.log(values,'values')
  //   // 截取字符串后2位
  //   // console.log(`${String(values[2]).padStart(2, '0')}${String(values[1]).padStart(2, '0')}${String(values[0]).slice(-2)}`,'options')
  //   setDdmmyy(`${String(values[2]).padStart(2, '0')}${String(values[1]).padStart(2, '0')}${String(values[0]).slice(-2)}`);
  //   // const v = values.join('-')
  //   // if (v) {
  //   //   setValue(v)
  //   // }
  //   // setDesc1(options.map((option) => option.text).join(''))
  // }

  const getLocationRecord = (data?: HjmCar) => {
    const where = {
      gpsNo: data?.gpsNo,
      ddmmyy: ddmmyy,
      hhmmss: hhmmss,
      limit: 200
    }
    Taro.showLoading({title: '加载中...'});
    pageHjmGpsLog(where).then(res => {
      console.log(res?.list, 'list')
      // 转换轨迹点坐标
      const transformedPoints = (res?.list || []).map(item => {
        // 转换WGS84坐标到GCJ02坐标
        const lat = Number(item.latitude);
        const lng = Number(item.longitude);
        
        if (item.latitude && item.longitude &&
            !isNaN(lat) &&
            !isNaN(lng) &&
            isFinite(lat) &&
            isFinite(lng)) {
          try {
            const transformed = GPS.gcj_encrypt(lat, lng);
            if (transformed && !isNaN(transformed.lat) && !isNaN(transformed.lng)) {
              return {
                ...item,
                latitude: transformed.lat,
                longitude: transformed.lng
              };
            }
          } catch (error) {
            console.error('轨迹点坐标转换错误:', error);
          }
        }
        return item;
      });
      setHjmGpsLog(transformedPoints);
    }).finally(() => {
      Taro.hideLoading();
    })
  }

  const reload = () => {
    const code = params.id;
    setScale(16)
    // 执行搜索
    if (keywords) {
      getHjmCarByCode(keywords).then(data => {
        console.log('执行搜索', data)
        setItem(data)
        
        // 转换WGS84坐标到GCJ02坐标
        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)) {
              setLatitude(transformed.lat);
              setLongitude(transformed.lng);
            } else {
              setLatitude(data.latitude);
              setLongitude(data.longitude);
            }
          } catch (error) {
            console.error('坐标转换错误:', error);
            setLatitude(data.latitude);
            setLongitude(data.longitude);
          }
        } else {
          setLatitude(data.latitude);
          setLongitude(data.longitude);
        }
        
        setKeywords(data.code)
        // 获取车辆轨迹信息
        getLocationRecord(data);
        if (data.fence) {
          // 方法2：使用实际的 fence 数据（如果是字符串格式）
          const coordStr = data.fence.points || '';

          // 使用通用函数解析坐标字符串
          const {points} = parseCoordinateString(coordStr);
          console.log('解析结果 - 多边形点:', points);
          setShowCircles(true)
        }
      })
      return false;
    }
    // 获取车辆信息
    if (code) {
      getHjmCarByCode(code).then(data => {
        setItem(data)
        
        // 转换WGS84坐标到GCJ02坐标
        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)) {
              setLatitude(transformed.lat);
              setLongitude(transformed.lng);
            } else {
              setLatitude(data.latitude);
              setLongitude(data.longitude);
            }
          } catch (error) {
            console.error('坐标转换错误:', error);
            setLatitude(data.latitude);
            setLongitude(data.longitude);
          }
        } else {
          setLatitude(data.latitude);
          setLongitude(data.longitude);
        }
        
        setKeywords(data.code)
        // 获取车辆轨迹信息
        getLocationRecord(data);
        if (data.fence) {
          // 方法2：使用实际的 fence 数据（如果是字符串格式）
          const coordStr = data.fence.points || '';

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

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

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

  return (
    <>
      <div className={'fixed z-20 top-0 left-0 w-full'}>
        <div className={'px-0'}>
          <div
            style={{
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              background: '#ffffff',
              borderTop: '1px solid #f7f7f7',
              borderBottom: '1px solid #f7f7f7',
            }}
          >
            <DatePicker
              title="日期选择"
              visible={show1}
              value={defaultValue}
              showChinese
              defaultValue={new Date(`${defaultDescription}`)}
              onClose={() => setShow1(false)}
              threeDimensional={false}
              onConfirm={(options, values) => confirm(values, options)}
            />
            <div className={'flex w-full justify-between items-center p-2'}>
              <Button type="info" size={'mini'} onClick={onBefore}>
                前一小时
              </Button>
              <div className={'gap-1 flex'}>
                <span onClick={() => setShow1(true)}>{desc1}</span>
                <span onClick={() => setShow(true)}>{(Number(hhmmss) + 8) + ':00'}</span>
              </div>
              <Button type="info" size={'mini'} onClick={onAfter}>
                后一小时
              </Button>
            </div>
            <DatePicker
              title="时间选择"
              type="hour-minutes"
              defaultValue={new Date(`${defaultDescription}`)}
              startDate={startDate}
              endDate={endDate}
              visible={show}
              onClose={() => setShow(false)}
              // @ts-ignore
              onConfirm={(options, values) => confirm(options, values)}
            />
          </div>
        </div>
      </div>
      <Map
        id="map"
        longitude={longitude}
        latitude={latitude}
        scale={scale}
        markers={[{
          id: 1,
          title: '车辆编号XXX',
          label: {
            content: `${item?.code}`,
            color: '#000000',
            fontSize: 12,
            borderRadius: 5,
            bgColor: '#FFFFFF',
            // @ts-ignore
            padding: '5px 5px',
            borderWidth: 1
          },
          latitude: latitude,
          longitude: longitude,
          iconPath: tricycleIcon,
          width: 32,
          height: 32,
          // @ts-ignore
          name: '位置'
        }]}
        polyline={[
          {
            points: hjmGpsLog,
            color: '#FF0000',
            width: 2,
            dottedLine: false
          }
        ]}
        onTap={() => {
          console.log('map tap')
        }}
        style={{width: '100%', height: '100vh'}}
      />

    </>
  )
}
export default Location
