import { NavBar, Picker, Toast } from 'antd-mobile';
import { useNavigate } from 'react-router';
import icon_arr_r from '../assets/icon_arr_s_r.svg';
import { ChangeEvent, 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 orgTextArr = useAppSelector(selectOrgTextArr);

  const [name, setName] = useState('');
  const [batch, setBatch] = useState('');
  const [mile, setMile] = useState(10);
  const [meter, setMeter] = useState(10);
  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[0].value]);
  const [unitType, setUnitType] = useState<string[]>([UNIT_TYPES[0].value]);

  const onInputChange = (evt: ChangeEvent<HTMLInputElement>) => {
    if (evt.target.name === 'name') {
      setName(evt.target.value);
    } else if (evt.target.name === 'batch') {
      setBatch(evt.target.value);
    } else if (evt.target.name === 'mile') {
      if (/^\d*$/.test(evt.target.value)) {
        setMile(+evt.target.value);
      }
    } else if (evt.target.name === 'meter') {
      if (/^\d*$/.test(evt.target.value)) {
        setMeter(+evt.target.value);
      }
    }
  };
  const onSaveBtnClick = () => {
    if (!name) {
      return Toast.show('请输入测量名称');
    }
    if (!batch) {
      return Toast.show('请输入批次号');
    }
    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: 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,
      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[0],
      lineClassify: lineClassCode[0],
      dataSource: dataSourceCode[0],
      unitType: unitType[0],
      mileage: `${mile}+${meter.toString().padStart(3, '0')}`,
      radius: '',
      extraDesc: JSON.stringify(desc),
    };
    Bridge.saveMeasure(dto).then((res) => {
      if (res.success) {
        Toast.show('保存成功');
        setTimeout(() => {
          navigate(-1);
          dispatch(resetState());
        }, 300);
      } else {
        Toast.show(res.message);
      }
    });
  };

  return (
    <>
      <div>
        <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
                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]">
              <span>里程</span>
              <input
                type="text"
                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="text"
                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={() => 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>
            <div
              className="h-12 flex items-center border-b border-[#eee]"
              onClick={() => 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]"
              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[]);
        }}
      />
    </>
  );
}
