/* eslint-disable array-callback-return */
import { Button, Form, Input, message, Select, InputNumber } from "antd";
import { useEffect, useState } from "react";
import { useNavigate } from "react-router";
import { saveMeasurement_new } from "../../../services/measure/analysis";
import { useAppSelector } from "../../../utils/hooks";
import {
  getOrgListService,
  dictionaryListService,
  queryStationData
} from "../../../services/ktj/org";
import { useAppDispatch } from "../../../utils/hooks";
import { setOrgData } from "../../../store/ktj/orgState";
import type {
  OrgItem,
  GwdDicItem,
  KTJ_BASE_TYPE,
  options,
  dataSourceOptions,
  unitTypesOptions,
  unitType,
  extraDescType
} from "../../../services/ktjTypes";
import { RAIN_TYPES, XB_CODES, DATA_SOURCE } from "../../../constant/index";
import "./MeasureAction.scss";
export default function MeasureConfig() {
  const { Option } = Select;
  const navigate = useNavigate();
  const systemState = useAppSelector((store) => store.systemState);
  const [messageApi, contextHolder] = message.useMessage();
  const dispatch = useAppDispatch();
  const measureState = useAppSelector((store) => store.measureState);
  const [extraDesc, setExtraDesc] = useState<extraDescType>()
  const onFinish = (values: any) => {
    let mtValue = values["meters"]
    //百米小于100时， 补齐3位。 比如 1 ："001", 10: "010"
    if (mtValue < 100) {
      mtValue = String(mtValue).padStart(3, '0');
    }
    const params = {
      operator: values["operator"],//操作员
      name: values["name"],//测量名称
      location: values["location"],//位置
      direction: values["direction"],//方向
      tljCode: values["tljCode"],//铁路局
      gwdCode: values["gwdCode"],//铁路段
      xmCode: values["xmCode"],//铁路线
      lineClassify: values["lineClassify"],//线路分类
      dataType: values["dataType"],//采集方式
      dataSource: values["dataSource"],//数据来源
      railSize: values["railSize"],//轨型
      xbCode: values["xbCode"],//行别
      unitType: values["unitType"],//股别
      mileage: `${values['kilometre']}+${mtValue}`,//里程
      stationCode: values['stationCode'],//车站
      batch: values['batch'],//批次
      radius: values["radius"],//半径
      turnoutNum: values["turnoutNum"],//道岔号
      sleeperNum: values["sleeperNum"],//枕木号
      extraDesc:JSON.stringify(extraDesc),
      alignPoints:[]
    };

    const orgItem = {
      tljCode: values["tljCode"],//铁路局
      gwdCode: values["gwdCode"],//铁路段
      xmCode: values["xmCode"],//铁路线
    }
    localStorage.setItem('orgInfo', JSON.stringify(orgItem));
    params.extraDesc = JSON.stringify(extraDesc)
    let measureData = measureState.measureData;
    if(measureData && measureData.length){
      params.alignPoints = measureData
    }
    localStorage.setItem('measureForm', JSON.stringify(params))
    saveMeasurement_new(params)
      .then((res) => {
        if (res.success) {
          messageApi.error(res.data.info);
        } else {
          message.success("保存成功");
          navigate("../action");
        }
      })
      .catch((e) => {
        navigate("../action");
      });
  };
  let user = localStorage.getItem("user") || "";
  let userInfo = (user && JSON.parse(user)) || {};
  const [form] = Form.useForm();
  useEffect(() => {
    queryKTJOrgList();
    queryDictionaryList();
    resetDataSource()
    resetRailTypes()
  }, []);

  useEffect(()=>{
  }, [measureState.measureData])

  //给股别分类
  const [unitTypeList, setUnitTypeList] = useState<unitTypesOptions[]>([])
  const resetRailTypes = () => {
    let zxOptions:unitTypesOptions = {
      label:'直线',
      options:[]
    }
    let qxOptions:unitTypesOptions = {
      label:'曲线',
      options:[]
    }
    let zxList:unitType[] = []
    let qxList:unitType[] = []
    RAIN_TYPES.map(item => {
      if(item.type === 1){
        zxList.push({
          label: item.name,
          value: item.code,
        })
      }else{
        qxList.push({
          label: item.name,
          value: item.code,
        })
      }
    })
    zxOptions.options = zxList
    qxOptions.options = qxList
    setUnitTypeList([zxOptions, qxOptions])
  }

  const [xbCodeOptions, setXbCodeOptions] = useState<dataSourceOptions[]>()
  const resetDataSource = () => {
    let options:dataSourceOptions[] = []
    DATA_SOURCE.map(item => {
      let optionMap:any = {
        label: item.name,
        value: item.code,
        options:[]
      }
      let childOptions:options[] = []
      item.child.map(ele => {
        childOptions.push({
          label: ele.name,
          value: ele.code
        })
        optionMap.options = childOptions
      })
      options.push(optionMap)
    })
    setXbCodeOptions(options)
  }

  //初始化科天健机构数据
  let [SJLY_List, setSJLYList] = useState<KTJ_BASE_TYPE[]>([]);
  let [WRPS_CJFS_List, setWRPSCJFSList] = useState<KTJ_BASE_TYPE[]>([]);
  let [WRPS_GGGX_List, setWRPSGGGXList] = useState<KTJ_BASE_TYPE[]>([]);
  let [XLFL_List, setXLFLList] = useState<KTJ_BASE_TYPE[]>([]);
  const queryDictionaryList = () => {
    dictionaryListService().then((res) => {
      if (res && res.data) {
        const { WRPS_CJFS, WRPS_GGGX, XLFL } = res.data;
				const SJLY:KTJ_BASE_TYPE[] = res.data.SJLY
				if(SJLY && SJLY.length){
					let sjlylist = SJLY.filter(item => item.key === 'XLDC' || item.key === 'DCDC')
					setSJLYList(sjlylist);
				}
        if(WRPS_CJFS && WRPS_CJFS.length){
          setWRPSCJFSList(WRPS_CJFS);
        }
        if(WRPS_GGGX && WRPS_GGGX.length){
          setWRPSGGGXList(WRPS_GGGX);
        }
        if(XLFL && XLFL.length){
          setXLFLList(XLFL);
        }
      }
    });
  };

  //获取机构数据
  const [KTJOrgList, setKTJOrgList] = useState<OrgItem[]>([]);
  const queryKTJOrgList = () => {
    getOrgListService()
      .then((res) => {
        let list: options[] = [];
        if (res && res.data) {
          let resData: OrgItem[] = res.data;
          setKTJOrgList(resData);
          dispatch(setOrgData(resData));
          resData.map((item) => {
            list.push({
              value: item.key,
              label: item.value,
            });
          });
        }
      })
      .catch((e) => {});
  };


  //选择机构时change
  const [gwdDicList, setGwdDicList] = useState<GwdDicItem[]>([]);
  const [gwdCodeValue, setGwdCodeValue] = useState<string>();
  const [xmCodeValue, setXmCodeValue] = useState<string>();
  const [gwdDicOptions, setGwdDicOptions] = useState<options[]>([]);
  const [railDicOptions, setRailDicOptions] = useState<options[]>([]);
  const [orgGwdDicList, setOrgGwdDicList] = useState<GwdDicItem[]>([])

  const onOrgChange = (value: string, option:any) => {
    let list = KTJOrgList.filter((item) => item.key === value);
    form.resetFields(["gwdCode", "xmCode"]);
    if (list && list.length) {
      let orgItem: OrgItem = list[0];
      setExtraDesc({...extraDesc,orgName:option.label})
      if (orgItem && orgItem.gwdDicList) {
        let listOptoins: options[] = [];
        setGwdDicList(orgItem.gwdDicList);
        setOrgGwdDicList(orgItem.gwdDicList)
        orgItem.gwdDicList.map((item) => {
          listOptoins.push({
            value: item.key,
            label: item.value,
          });
        });
        setGwdDicOptions(listOptoins);
        setGwdCodeValue(listOptoins[0].value);
      }
    }
  };

  const onGwdChange = (value: string, option:any) => {
    let cloneGwdDicList = [...orgGwdDicList];
    form.resetFields(["xmCode"]);
    let list = cloneGwdDicList.filter((item) => item.key === value);
    if (list && list.length) {
      let gwdDicItem: GwdDicItem = list[0];
      setExtraDesc({...extraDesc,gwdName:option.label})
      if (gwdDicItem && gwdDicItem.railDicList) {
        let railOptions: options[] = [];
        gwdDicItem.railDicList.map((item) => {
          railOptions.push({
            value: item.key,
            label: item.value,
          });
        });
        if(railOptions && railOptions.length){
          setRailDicOptions(railOptions);
          setXmCodeValue(railOptions[0].value);
        }
      }
    }
  };

  //车站数据
  const [stationList, setStationList] = useState<KTJ_BASE_TYPE[]>([])
  const queryStation = (value:string, option:any) => {
    form.resetFields(["stationCode"]);
    let tljCode =  form.getFieldValue("tljCode")
    let gwdCode =  form.getFieldValue("gwdCode")
    let xmCode =  form.getFieldValue("xmCode")
    const params = {
      tljCode,
      gwdCode,
      xmCode
    }
    setExtraDesc({...extraDesc,xmName:option.label})
    queryStationData(params).then(res => {
      if(res && res.data){
        setStationList(res.data)
      }else{
        setStationList([])
      }
      const measureForm = localStorage.getItem('measureForm')
      if (measureForm) {
        form.setFieldsValue({
          ...JSON.parse(measureForm)
        });
      }
    })
  }

  
  useEffect(()=>{
    if(systemState.orgInfo){
      const cloneOrgItem = systemState.orgInfo
      if(cloneOrgItem.value){
        const org = JSON.parse(cloneOrgItem.value)
        onOrgChange(org[0].value, org[0])
        onGwdChange(org[1].value, org[1])
        form.setFieldsValue({
          tljCode:org[0].value,
          gwdCode: org[1].value,
          xmCode: org[2].value
        });
        queryStation(org[2].value, org[2])
      }
    }
  },[KTJOrgList, xmCodeValue, gwdCodeValue, systemState.orgInfo])


  useEffect(()=>{
    if(systemState.accountInfo){
      const cloneAccountItem = systemState.accountInfo
      if(cloneAccountItem.value){
        form.setFieldsValue({
          operator:cloneAccountItem.value
        })
      }
    }
  },[systemState.accountInfo])
  

  const onRailTypeChange = (value:string, option:any) => {
    setExtraDesc({...extraDesc,railSizeName:option.label})
  }

  //数据来源change
  const [dataSource, setDataSource] = useState('')
  const onDataSourceChange = (value:string, option:any) => {
    setExtraDesc({...extraDesc,dataSourceName:option.label})
    form.resetFields(["xbCode"]);
    setDataSource(value)
  }

  //车站
  const onSatioinChange = (value:string, option:any) => {
    setExtraDesc({...extraDesc,stationName:option.label})
  }

  //股别change
  const [unitType, setUnitType] = useState<number>()
  const onUnitTypeChange = (value:string) => {
    RAIN_TYPES.map(item => {
      if(item.code === value){
        setUnitType(item.type)
      }
    })
  }

  useEffect(() => {
    const initData = {
      operator: "klj_test",
      direction: "左",
    }
    form.setFieldsValue(initData);
  }, [userInfo.nickname, form]);

  return (
    <>
      {contextHolder}
      <div>
        <Form
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          size="large"
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <div className="layout">
            <Form.Item
              label="操作员"
              name="operator"
              rules={[{ required: true, message: "请输入操作员姓名" }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="测量名称"
              name="name"
              rules={[{ required: true, message: "请输入测量名称" }]}
            >
              <Input placeholder="请输入测量名称" />
            </Form.Item>
						<Form.Item
							label="铁路局"
							name="tljCode"
							rules={[{ required: true, message: "请选择铁路局" }]}
						>
							<Select
								onChange={onOrgChange}
								placeholder="请选择铁路段"
							>
								{KTJOrgList.map((item) => (
									<Option key={item.key} value={item.key}>{item.value}</Option>
								))}
							</Select>
						</Form.Item>


						<Form.Item
							label="铁路段"
							name="gwdCode"
							rules={[{ required: true, message: "请选择铁路段" }]}
						>
							<Select
								onChange={onGwdChange}
								placeholder="请选择铁路段"
								value={gwdCodeValue}
								options={gwdDicOptions.map((item) => ({ label: item.label, value: item.value }))}
							>
							</Select>
						</Form.Item>

						<Form.Item
							label="铁路线"
							name="xmCode"
							rules={[{ required: true, message: "请选择铁路线" }]}
						>
							<Select
									placeholder="请选择铁路线"
									value={xmCodeValue}
                  onChange={queryStation}
									options={railDicOptions.map((item) => ({ label: item.label, value: item.value }))}
							>
							</Select>
						</Form.Item>
            <Form.Item
              label="轨型"
              name="railSize"
              rules={[{ required: true, message: "请选择轨型" }]}
            >
              <Select
                placeholder="请选择轨型"
                onChange={onRailTypeChange}
                options={WRPS_GGGX_List.map((item) => ({
                  label: item.value,
                  value: item.key,
                }))}
              ></Select>
            </Form.Item>

            <Form.Item
              label="数据来源"
              name="dataSource"
              rules={[{ required: true, message: "请选择数据来源" }]}
            >
              <Select
                placeholder="请选择数据来源"
                onChange={onDataSourceChange}
                options={SJLY_List.map((item) => ({
                  label: item.value,
                  value: item.key,
                }))}
              ></Select>
            </Form.Item>            

            <Form.Item
							label="车站"
							name="stationCode"
							rules={[{ required: true, message: "请选择车站" }]}
						>
							<Select
								placeholder="请选择车站"
                onChange={onSatioinChange}
							>
								{stationList.map((item) => (
									<Option key={item.key} value={item.key}>{item.value}</Option>
								))}
							</Select>
						</Form.Item>

            <Form.Item
              label="线路分类"
              name="lineClassify"
              rules={[{ required: true, message: "请选择线路分类" }]}
            >
              <Select
                placeholder="请选择线路分类"
                options={XLFL_List.map((item) => ({
                  label: item.value,
                  value: item.key,
                }))}
              ></Select>
            </Form.Item>

            <Form.Item
              label="采集方式"
              name="dataType"
              rules={[{ required: true, message: "请选择采集方式" }]}
            >
              <Select
                placeholder="请选择采集方式"
                options={WRPS_CJFS_List.map((item) => ({
                  label: item.value,
                  value: item.key,
                }))}
              ></Select>
            </Form.Item>

            <Form.Item
              label="批次"
              name="batch"
              rules={[{ required: true, message: "请输入批次" }]}
            >
              <Input placeholder="请输入批次" />
            </Form.Item>

            {/* <Form.Item
              label="位置"
              name="location"
              rules={[{ required: false, message: "请输入位置" }]}
            >
              <Input placeholder="请输入位置" />
            </Form.Item>

            <Form.Item
              label="方向"
              name="direction"
              rules={[{ required: false, message: "请输入方向" }]}
            >
              <Select
                className="w-[5rem]"
                options={[
                  { value: "左", label: "左侧" },
                  { value: "右", label: "右侧" },
                ]}
              />
            </Form.Item> */}
            {dataSource === 'DCDC' ? (
              <>
                <Form.Item
                  label="道岔号"
                  name="turnoutNum"
                  rules={[{ required: true, message: "请输入道岔号" }]}
                >
                  <InputNumber className="w-[18vw]" placeholder="请输入道岔号" />
                </Form.Item>

                <Form.Item
                  label="枕木号"
                  name="sleeperNum"
                  rules={[{ required: true, message: "请输入枕木号" }]}
                >
                  <InputNumber className="w-[18vw]"  placeholder="请输入枕木号" />
                </Form.Item>
              
                <Form.Item
                label="行别"
                name="xbCode"
                rules={[{ required: true, message: "请选择行别" }]}
                
              >
                <Select placeholder="请选择行别" options={xbCodeOptions}>
                </Select>
              </Form.Item>
              </>
            ) : (
              <Form.Item
              label="行别"
              name="xbCode"
              rules={[{ required: true, message: "请选择行别" }]}
            >
              <Select  placeholder="请选择行别">
                {XB_CODES.map((item) => (
                  <Option key={item.code} value={item.code}>
                    {item.name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            )}
            
            {dataSource === "XLDC" &&
              <div style={{display:"flex"}}>
                <Form.Item
                  label="里程"
                  style={{marginLeft:"5vw"}}
                  name="kilometre"
                  rules={[{ required: true, message: "请输入" }]}
                >
                  <InputNumber className="w-[7vw]" placeholder="公里" />
                </Form.Item>
                <Form.Item
                >
                  +
                </Form.Item>
                <Form.Item
                  name="meters"
                  style={{marginLeft:"10px"}}
                  rules={[{ required: true, message: "请输入" }]}
                >
                  <InputNumber className="w-[6vw]" placeholder="百米" />
                </Form.Item>
              </div>
            }

            <Form.Item
              label="股别"
              name="unitType"
              rules={[{ required: true, message: "请选择股别" }]}
            >
              <Select placeholder="请选择股别" onChange={onUnitTypeChange} options={unitTypeList}>
              </Select>
            </Form.Item>
            {unitType === 2 && 
              <Form.Item
                label="半径"
                name="radius"
                rules={[{ required: true, message: "请输入半径" }]}
              >
                <InputNumber className="w-[18vw]" placeholder="请输入半径" />
              </Form.Item>
            }
            
          </div>
          <div className="flex justify-center w-[60vw] mt-[15vh]">
            <Form.Item label={null} >
              <Button style={{ width: 150 }} onClick={() => navigate("../action", { replace: true })}>
                返回
              </Button>
            </Form.Item>
            <Form.Item label={null}>
              <Button
                type="primary"
                size="large"
                style={{ width: 150, marginLeft:"20px" }}
                htmlType="submit"
              >
                保存测量
              </Button>
            </Form.Item>
          </div>
        </Form>
      </div>
    </>
  );
}
