import { NavBar, Toast } from 'antd-mobile';
import { useEffect, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import MeasurementCanvas, {
  BenchmarkShape,
  MeasurementCanvasRef,
} from '../components/konva/MeasurementCanvas';
import Bridge from '../utils/bridge';
import { Measurement } from '../services/apiTypes';
import { useAppDispatch, useAppSelector } from '../utils/hooks';
// import { XB_CODES } from '../utils/constant';
import { updateRailPoints } from '../store/features/baseData';

export default function MeasureRecord() {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const baseState = useAppSelector((state) => state.baseData);

  const params = useParams(); // params.recordId
  const [measure, setMeasure] = useState<Measurement | undefined>(undefined);
  const canvasRef = useRef<MeasurementCanvasRef>(null);
  const back = () => navigate(-1);

  useEffect(() => {
    Bridge.getMeasurementDetail({ id: +(params.recordId || '') }).then((res) => {
      if (res.success) {
        setMeasure({ ...res.data, extraDescObj: JSON.parse(res.data.extraDesc) });
      } else {
        Toast.show(res.message);
      }
    });
  }, [params.recordId]);

  function drawRailBaseLine(points: string) {
    const benchmarkShapes = JSON.parse(points) as BenchmarkShape[];
    if (canvasRef.current) {
      canvasRef.current.setBenchmarkData(benchmarkShapes);
    }
  }

  function drawMeasurePoints(leftPoints: string, rightPoints: string) {
    if (canvasRef.current) {
      canvasRef.current.setMeasurementDataLeft(JSON.parse(leftPoints));
      canvasRef.current.setMeasurementDataRight(JSON.parse(rightPoints));
    }
  }

  useEffect(() => {
    if (measure) {
      const r = baseState.railTypes.find((rail) => rail.code === measure.railSize);
      if (!r) return;
      if (!!r.points) {
        drawRailBaseLine(r.points);
        drawMeasurePoints(measure.leftPoints, measure.rightPoints);
        return;
      }
      Bridge.getTrackPoint({ code: r.code }).then((res) => {
        if (res.success) {
          dispatch(updateRailPoints(res.data));
          drawRailBaseLine(res.data.points!);
          drawMeasurePoints(measure.leftPoints, measure.rightPoints);
        } else {
          Toast.show(res.message);
        }
      });
    }
  }, [baseState.railTypes, dispatch, measure]);

  // function railType(code: string) {
  //   const rail = baseState.railTypes.find((rail) => rail.code === code);
  //   return rail;
  // }

  // function direction(directCode: string) {
  //   return XB_CODES.find((dire) => dire.value === directCode);
  // }

  return (
    <div>
      <NavBar className="bg-white" onBack={back}>
        测量详情
      </NavBar>
      <div className="main-page-content ">
        <div className="relative h-0 p-0 pb-[70%] border-y border-[#dedede]">
          <div className="absolute left-0 right-0 top-0 bottom-0 bg-title">
            <MeasurementCanvas
              width={window.innerWidth}
              height={window.innerWidth * 0.7}
              logicalExtent={{ minX: -45, maxX: 45, minY: -18, maxY: 52 }}
              gridStep={3}
              origin={{ x: 0, y: 20 }}
              pixelPerMm={window.innerWidth / 90}
              maxZoom={5}
              showGrid={true}
              showBenchmark={true}
              showAnalysis={false}
              showScale={false}
              scaleInterval={1}
              showCoordinates={false}
              ref={canvasRef}
            />
          </div>
        </div>
        <section>
          <h1 className="h-10 px-4 text-base font-medium leading-10">详细信息</h1>
          {measure && (
            <div
              className="overflow-x-hidden overflow-y-auto"
              style={{
                height: 'calc(100vh - var(--navBarHeight) - (100vw * 0.7) - 50px)',
              }}
            >
              <div className="grid grid-cols-[auto_1fr] bg-white px-5 py-3 gap-x-5 gap-y-4 text-sm ">
                <p className="text-[#818181]">创建时间</p>
                <span className="text-text">{measure.createTime}</span>

                <p className="text-[#818181]">测量名称</p>
                <span className="text-text">{measure.name}</span>

                <p className="text-[#818181]">批次</p>
                <span className="text-text">{measure.batch}</span>

                <p className="text-[#818181]">数据来源</p>
                <span className="text-text">{measure.extraDescObj?.dataSource}</span>

                <p className="text-[#818181]">线路分类</p>
                <span className="text-text">{measure.extraDescObj?.lineClassify}</span>

                <p className="text-[#818181]">轨型</p>
                <span className="text-text">{measure.extraDescObj?.railSize}</span>

                <p className="text-[#818181]">铁路局名称</p>
                <span className="text-text">{measure.extraDescObj?.tljCode}</span>

                <p className="text-[#818181]">路段名称</p>
                <span className="text-text">{measure.extraDescObj?.gwdCode}</span>

                <p className="text-[#818181]">线路名称</p>
                <span className="text-text">{measure.extraDescObj?.xmCode}</span>

                <p className="text-[#818181]">车站</p>
                <span className="text-text">{measure.extraDescObj?.stationCode}</span>

                <p className="text-[#818181]">方向</p>
                <span className="text-text">{measure.extraDescObj?.xbCode}</span>

                <p className="text-[#818181]">股别</p>
                <span className="text-text">{measure.extraDescObj?.unitType}</span>

                <p className="text-[#818181]">里程</p>
                <span className="text-text">{`${measure.extraDescObj?.mile}公里+${measure.extraDescObj?.meter}米`}</span>
              </div>
            </div>
          )}
        </section>
      </div>
    </div>
  );
}
