import {Mask, NavBar, Picker, SpinLoading, Toast} from 'antd-mobile';
import { useNavigate } from 'react-router';
import icon_arr_r from '../assets/icon_arr_s_r.svg';
import {ChangeEvent, useCallback, useEffect, useState} from 'react';
import { useAppDispatch, useAppSelector } from '../utils/hooks';
import { DATA_SOURCE, LINE_CLASSIFY, UNIT_TYPES, XB_CODES } from '../utils/constant';
import { ExtraDesc, MeasurementDTO } from '../services/apiTypes';
import Bridge from '../utils/bridge';
import { resetState } from '../store/features/measureSlice';
import { selectOrgTextArr } from '../store';

export default function MeasureSave() {
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const back = () => navigate(-1);

  const contextState = useAppSelector((state) => state.context);
  const baseState = useAppSelector((state) => state.baseData);
  const measureState = useAppSelector((state) => state.measure);
  const orgTextArr = useAppSelector(selectOrgTextArr);


  const loadData = useCallback(() => {
    Bridge.getRecordList({ pageNum: 1, size: 1 }).then((res) => {
      if (res.success && res.data.list.length) {
        const data = res.data.list[0]?.records?.[0]
        console.log(data)
        setName(data?.name)
        setBatch(data?.batch)
        setMile(data?.mileage?.split('+')?.[0])
        setMeter(data?.mileage?.split('+')?.[1])
        setLineClassCode([data?.lineClassify])
        setDataSourceCode([data?.dataSource])
        setDirectionCode([data?.xbCode])
        setUnitType([data?.unitType])
        setTurnoutNum(Number(data?.turnoutNum || 1))
        setSleeperNum(Number(data?.sleeperNum || 1))
        setStationCode([data?.stationCode])
        document.getElementById('name-id')?.focus()
      }
    });
  }, []);
  useEffect(() => {
    loadData();
  }, [loadData]);


  const [name, setName] = useState('');
  const [batch, setBatch] = useState('');
  const [mile, setMile] = useState('10');
  const [meter, setMeter] = useState('10');
  const [turnoutNum, setTurnoutNum] = useState(1);
  const [sleeperNum, setSleeperNum] = useState(1);
  const [railPickerVisible, setRailPickerVisible] = useState(false);
  const [dataSourcePickerVisible, setDataSourcePickerVisible] = useState(false);
  const [lineClassPickerVisible, setLineClassPickerVisible] = useState(false);
  const [unitTypePickerVisible, setUnitTypePickerVisible] = useState(false);
  const [stationPickerVisible, setStationPickerVisible] = useState(false);

  const [directionCode, setDirectionCode] = useState<string[]>([XB_CODES[0].value]);
  const [dataSourceCode, setDataSourceCode] = useState<string[]>([DATA_SOURCE[0].value]);
  const [lineClassCode, setLineClassCode] = useState<string[]>([LINE_CLASSIFY[0].value]);
  const [stationCode, setStationCode] = useState<string[]>(
    contextState.stationList.length > 0 ? [contextState.stationList[0].value] : []
  );
  const [unitType, setUnitType] = useState<string[]>([UNIT_TYPES[0].value]);

  const onInputChange = (evt: ChangeEvent<HTMLInputElement>) => {
    if (evt.target.name === 'name') {
      if (evt.target.value.length <= 50) {
        setName(evt.target.value);
      }else {
        Toast.show('名称长度不能超过50个字符');
      }
    } else if (evt.target.name === 'batch') {
      if (evt.target.value.length <= 10) {
        setBatch(evt.target.value);
      }
      else {
        Toast.show('批次长度不能超过10个字符');
      }
    } else if (evt.target.name === 'mile') {
      const val = evt.target.value.replace(/^0+/, '')
      if (/^\d*$/.test(val)) {
        setMile(val || '');
      }
    } else if (evt.target.name === 'meter') {
      const val = evt.target.value.replace(/^0+/, '')
      if (/^\d*$/.test(val)) {
        setMeter(val || '');
      }
    } else if (evt.target.name === 'turnoutNum') {
      if (/^\d*$/.test(evt.target.value)) {
        setTurnoutNum(+evt.target.value);
      }
    } else if (evt.target.name === 'sleeperNum') {
      if (/^\d*$/.test(evt.target.value)) {
        setSleeperNum(+evt.target.value);
      }
    }
  };
  const [measureData, setMeasureData] = useState(measureState.measureData)
  useEffect(()=>{
    setMeasureData(measureState.measureData)
  },[measureState.measureData])

  const [loading, setLoading] = useState(false);
  const onSaveBtnClick = () => {
    if (!name) {
      return Toast.show('请输入测量名称');
    }
    if (!batch) {
      return Toast.show('请输入批次号');
    }
    setLoading(true)
    const railType = baseState.railTypes.find((r) => r.id === contextState.currRailTypeId);
    const [tlj, gwd, xm] = orgTextArr;
    const desc: ExtraDesc = {
      railSize: railType!.name,
      tljCode: tlj,
      gwdCode: gwd,
      xmCode: xm,
      xbCode: XB_CODES.find((x) => x.value === directionCode[0])!.label,
      stationCode:
        stationCode.length > 0
          ? contextState.stationList.find((s) => s.value === stationCode[0])!.label
          : '',
      lineClassify: LINE_CLASSIFY.find((l) => l.value === lineClassCode[0])!.label,
      dataSource: DATA_SOURCE.find((d) => d.value === dataSourceCode[0])!.label,
      unitType: UNIT_TYPES.find((u) => u.value === unitType[0])!.label,
      mile: +mile,
      meter: +meter,
    };
    const dto: MeasurementDTO = {
      operator: 'klj_test',
      dataType: 'MINIPROF',
      name,
      batch,
      railSize: railType!.code,
      tljCode: contextState.currOrgCode,
      gwdCode: contextState.currGWDCode,
      xmCode: contextState.currXMCode,
      xbCode: directionCode[0],
      stationCode: stationCode.length > 0 ? stationCode[0] : '',
      lineClassify: lineClassCode[0],
      dataSource: dataSourceCode[0],
      turnoutNum: turnoutNum?.toFixed(),
      sleeperNum: sleeperNum?.toFixed(),
      unitType: unitType[0],
      mileage: `${mile}+${meter.padStart(3, '0')}`,
      radius: '',
      extraDesc: JSON.stringify(desc),
      alignPoints:[]
    };
    if(measureData && measureData.length){
      dto.alignPoints = measureData
    }
    Bridge.saveMeasure(dto).then((res) => {
      if (res.success) {
        Toast.show('保存成功');
        setTimeout(() => {
          navigate('/home/measure');
          dispatch(resetState());
        }, 300);
      } else {
        Toast.show(res.message);
      }
    }).catch(e=>{
      Toast.show({
        content: '操作失败',
      });
    }).finally(() => {
      setLoading(false)
    });
  };

  return (
    <>
      <div>
        {loading && (
            <Mask opacity='thick' className="h-[100vh] flex justify-center items-center">
              <div style={{ margin: '45%',  display: 'flex', flexDirection: 'column',  alignItems: 'center', justifyContent: 'center' }}>
                <SpinLoading color="#5c92b4" />
                <span className="whitespace-nowrap mt-5 text-[#5c92b4]" style={{fontSize: '16px'}}>请稍候...</span>
              </div>
            </Mask>
        )}
        <NavBar className="bg-white" onBack={back}>
          测量参数
        </NavBar>
        <div className="main-page-content overflow-x-hidden overflow-y-auto">
          <div className="bg-white px-5 text-sm text-text mt-2">
            <div className="h-12 flex items-center border-b border-[#eee]">
              <span>测量名称</span>
              <input
                  id='name-id'
                type="text"
                name="name"
                value={name}
                placeholder="请填写测量名称"
                className="border-0 outline-none self-stretch text-right flex-1 ml-4"
                onChange={onInputChange}
              />
            </div>
            <div className="h-12 flex items-center border-b border-[#eee]">
              <span>批次</span>
              <input
                type="text"
                name="batch"
                value={batch}
                placeholder="请填写批次"
                className="border-0 outline-none self-stretch text-right flex-1 ml-4"
                onChange={onInputChange}
              />
            </div>
            <div
              className="h-12 flex items-center border-b border-[#eee]"
              onClick={() => setDataSourcePickerVisible(true)}
            >
              <span>数据来源</span>
              <span className="ml-auto mr-4">
                {DATA_SOURCE.find((r) => r.value === dataSourceCode[0])?.label || ''}
              </span>
              <img src={icon_arr_r} alt="arr" />
            </div>

            {dataSourceCode[0] === 'DCDC' ? (
              <>
                <div className="h-12 flex items-center border-b border-[#eee]">
                  <span>道岔号</span>
                  <input
                    type="number"
                    name="turnoutNum"
                    value={turnoutNum}
                    className="border-0 outline-none self-stretch text-right flex-1 ml-4"
                    onChange={onInputChange}
                  />
                </div>
                <div className="h-12 flex items-center border-b border-[#eee]">
                  <span>枕木号</span>
                  <input
                    type="number"
                    name="sleeperNum"
                    value={sleeperNum}
                    className="border-0 outline-none self-stretch text-right flex-1 ml-4"
                    onChange={onInputChange}
                  />
                </div>
                <div
                  className="h-12 flex items-center border-b border-[#eee]"
                  onClick={() => {
                    if (contextState.stationList.length > 0) {
                      setStationPickerVisible(true);
                    }
                  }}
                >
                  <span>车站</span>
                  <span className="ml-auto mr-4">
                    {contextState.stationList.find((r) => r.value === stationCode[0])?.label || ''}
                  </span>
                  <img src={icon_arr_r} alt="arr" />
                </div>
              </>
            ) : (
              <div className="h-12 flex items-center border-b border-[#eee]">
                <span>里程</span>
                <input
                  type="number"
                  name="mile"
                  value={mile}
                  className="w-14 h-8 mx-1 border border-[#eee] rounded outline-none text-center ml-auto"
                  onChange={onInputChange}
                />
                <span>公里+</span>
                <input
                  type="number"
                  name="meter"
                  value={meter}
                  className="w-14 h-8 mx-1 border border-[#eee] rounded outline-none text-center"
                  onChange={onInputChange}
                />
                <span>米</span>
              </div>
            )}

            <div
              className="h-12 flex items-center border-b border-[#eee]"
              onClick={() => setLineClassPickerVisible(true)}
            >
              <span>线路分类</span>
              <span className="ml-auto mr-4">
                {LINE_CLASSIFY.find((r) => r.value === lineClassCode[0])?.label || ''}
              </span>
              <img src={icon_arr_r} alt="arr" />
            </div>

            <div
              className="h-12 flex items-center border-b border-[#eee]"
              onClick={() => setRailPickerVisible(true)}
            >
              <span>行别</span>
              <span className="ml-auto mr-4">
                {XB_CODES.find((r) => r.value === directionCode[0])?.label || ''}
              </span>
              <img src={icon_arr_r} alt="arr" />
            </div>
            <div className="h-12 flex items-center " onClick={() => setUnitTypePickerVisible(true)}>
              <span>股别</span>
              <span className="ml-auto mr-4">
                {UNIT_TYPES.find((r) => r.value === unitType[0])?.label || ''}
              </span>
              <img src={icon_arr_r} alt="arr" />
            </div>
          </div>
          <div
            className="btn-contained rounded-md h-12 mx-9 my-8 text-base font-medium"
            onClick={onSaveBtnClick}
          >
            确定
          </div>
        </div>
      </div>
      <Picker
        columns={[XB_CODES]}
        visible={railPickerVisible}
        onClose={() => {
          setRailPickerVisible(false);
        }}
        value={directionCode}
        onConfirm={(v) => {
          setDirectionCode(v as string[]);
        }}
      />
      <Picker
        columns={[DATA_SOURCE]}
        visible={dataSourcePickerVisible}
        onClose={() => {
          setDataSourcePickerVisible(false);
        }}
        value={dataSourceCode}
        onConfirm={(v) => {
          setDataSourceCode(v as string[]);
        }}
      />
      <Picker
        columns={[LINE_CLASSIFY]}
        visible={lineClassPickerVisible}
        onClose={() => {
          setLineClassPickerVisible(false);
        }}
        value={dataSourceCode}
        onConfirm={(v) => {
          setLineClassCode(v as string[]);
        }}
      />
      <Picker
        columns={[UNIT_TYPES]}
        visible={unitTypePickerVisible}
        onClose={() => {
          setUnitTypePickerVisible(false);
        }}
        value={unitType}
        onConfirm={(v) => {
          setUnitType(v as string[]);
        }}
      />
      <Picker
        columns={[contextState.stationList]}
        visible={stationPickerVisible}
        onClose={() => {
          setStationPickerVisible(false);
        }}
        value={stationCode}
        onConfirm={(v) => {
          setStationCode(v as string[]);
        }}
      />
    </>
  );
}
