/* eslint-disable array-callback-return */
import { Button, Form, Input, message, Select, InputNumber, Cascader, Row, Col, Spin } from "antd";
import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router";
import { getDetailList, saveMeasurement_new } from "../../../services/measure/analysis";
import { useAppSelector } from "../../../utils/hooks";
import {
  getOrgListService,
  dictionaryListService,
  queryStationData
} from "../../../services/ktj/org";
import type { InputRef } from 'antd/es/input'; 
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";
import { GwdItem, orgCascaderType, OrgOptions, systemItem } from "../../system/types";
  

export default function MeasureConfig() {
  const navigate = useNavigate();
  const [KTJOrgList, setKTJOrgList] = useState<orgCascaderType[]>([]);
  const [extraDesc, setExtraDesc] = useState<extraDescType>()
  const measureState = useAppSelector((store) => store.measureState);
  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm();
  const [orgValues, setOrgValues] = useState<string[]>([])
  const [WRPS_GGGX_List, setWRPSGGGXList] = useState<KTJ_BASE_TYPE[]>([]);
  const [dataSource, setDataSource] = useState('')
  const [SJLY_List, setSJLYList] = useState<KTJ_BASE_TYPE[]>([]);
  const [stationList, setStationList] = useState<KTJ_BASE_TYPE[]>([])
  const [XLFL_List, setXLFLList] = useState<KTJ_BASE_TYPE[]>([]);
  const [WRPS_CJFS_List, setWRPSCJFSList] = useState<KTJ_BASE_TYPE[]>([]);
  const [xbCodeOptions, setXbCodeOptions] = useState<dataSourceOptions[]>()
  const [unitTypeList, setUnitTypeList] = useState<unitTypesOptions[]>([])
  const [unitType, setUnitType] = useState<number>()
  const inputRef = useRef<InputRef>(null);	
  const systemState = useAppSelector((store) => store.systemState);
  const [kilMet, setKilMet] = useState<Record<string, any>>({})
  const [loading, setLoading] = useState(false)
  useEffect(()=>{
    showLastForm()
    queryDictionaryList()
    resetRailTypes()
    resetDataSource()
    // queryRailData()
    console.log('systemState.orgInfo---', systemState.orgInfo)
    setTimeout(() => {
      if(inputRef.current){
        inputRef.current.focus()
      }
    }, 100)
  }, [])


  //获取铁路局数据
  // function queryRailData(){
  //   getOrgListService().then((res) => {
  //     if (res && res.data) {
  //       let resData: OrgItem[] = res.data;
  //       let data = convertToCascaderData(resData)
  //       setKTJOrgList(data)
  //       // 使用上次保存时的参数。
        
  //     }
  //   }).catch((e) => {});
  // }

  function showLastForm () {
    let mfInfo: any = {}
      // 获取记录中的第一条数据
    const params = {
      pageSize: 5,
      pageNum: 1,
    }
    setLoading(true)
    getDetailList(params).then(res => {
      if(res.success){
        const list = res.data.list
        if(list && list.length){
          mfInfo = list[0]
          setForm(mfInfo)
        }else{
          setForm({})
        }
      }
      setLoading(false)
    }).catch( ()=> {
      setLoading(false)
    })
  }

  const getDate = () => {
    const currentDate = new Date(); // 获取当前时间
    const year = currentDate.getFullYear(); // 获取完整的年份
    let month: string | number = currentDate.getMonth() + 1; // 获取月份（0-11），需要加1
    let day: string | number = currentDate.getDate(); // 获取日
    month = month < 10 ? "0" + month : month
    day = day < 10 ? "0" + day : day
    const currentTime = `${year}-${month}-${day}`
    let now = `${year}${month}${day}`
    return  {
      now,
      nowfm: currentTime,
    }; // 格式化日期为YYYY-MM-DD格式
  }

  const setForm = (mfInfo: any) => {
    console.log('mfInfo---', mfInfo)
    let kilometre = 0
    let meters = 0
    if(mfInfo.mileage){
      kilometre = mfInfo.mileage.split('+')[0]
      meters = mfInfo.mileage.split('+')[1]
    }
    const ymd = getDate();
    const createTime = mfInfo.createTime
    let todayNumber = mfInfo.todayNumber || 0
    if(createTime && createTime.indexOf(ymd.nowfm) === -1 ){
      todayNumber = 0
    }
    let orgInfo = systemState.orgInfo;
    let labels: string[] = []
    let orgCode: string[] = []
    if(orgInfo && orgInfo.value){
      const orgValue = JSON.parse(orgInfo.value)
      orgValue && orgValue.forEach((org: OrgOptions) => {
        labels.push(org.label)
        orgCode.push(org.value)
      })
    }
    let stationCode = null
    if(orgCode && orgCode[2] === mfInfo.xmCode){
      stationCode = mfInfo.stationCode
    }
    let label = labels.join('-')
    // let name = `${label}-${ymd.now}${(Number(todayNumber) + 1).toString().padStart(4, '0') }`
    let name = mfInfo?.name
    setKilMet({
      kilometre,
      meters
    })
    const user = localStorage.getItem("user");
    let userData = JSON.parse(user || "");
    form.setFieldsValue({
      ...mfInfo,
      orgValues: orgCode,
      kilometre,
      meters,
      name,
      operator: userData.nickname || userData.account,
      stationCode,
    });
    const railList = orgCode
    setOrgValues(railList)
    getStationData(railList)
    setDataSource(mfInfo.dataSource)
    onUnitTypeChange(mfInfo.unitType)
  }

  function convertToCascaderData(data:OrgItem[]) {
    return data.map(item => {
      const newItem:orgCascaderType = {
        value: item.key,
        label: item.value,
      };
      if (item.gwdDicList && item.gwdDicList.length > 0) {
        newItem.children = item.gwdDicList.map(gwdItem => {
          const newGwdItem:GwdItem = {
            value: gwdItem.key,
            label: gwdItem.value,
          };
          if (gwdItem.railDicList && gwdItem.railDicList.length > 0) {
            newGwdItem.children = gwdItem.railDicList.map(railItem => ({
              value: railItem.key,
              label: railItem.value || railItem.input
            }));
          }
          return newGwdItem;
        });
      }
      return newItem;
    });
  }

  function onOrgChange(value:string[], selectedOptions: orgCascaderType[]){
    if(value.length){
      form.setFieldsValue({tljCode: value[0]})
      form.setFieldsValue({gwdCode: value[1]})
      form.setFieldsValue({xmCode: value[2]})
      getStationData(value)
      form.resetFields(["stationCode"]);
    }
  }

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

  //数据来源change
  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})
  }

    //车站数据
  const getStationData = (railData: string[]) => {
    let orgInfo = systemState.orgInfo;
    let orgCode: string[] = []
    if(orgInfo && orgInfo.value){
      const orgValue = JSON.parse(orgInfo.value)
      orgValue && orgValue.forEach((org: OrgOptions) => {
        orgCode.push(org.value)
      })
    }
    let tljCode =  orgCode[0]
    let gwdCode =  orgCode[1]
    let xmCode =  orgCode[2]
    const params = {
      tljCode,
      gwdCode,
      xmCode
    }
    queryStationData(params).then(res => {
      if(res && res.data?.length){
        setStationList(res.data)
      }else{
        setStationList([])
      }
    })
  }

  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 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)
  }

  const onUnitTypeChange = (value:string) => {
    RAIN_TYPES.map(item => {
      if(item.code === value){
        setUnitType(item.type)
      }
    })
  }

  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 onFinish = (values: any) => {
    let mtValue = values["meters"]
    //百米小于100时， 补齐3位。 比如 1 ："001", 10: "010"
    if (mtValue < 100) {
      mtValue = String(mtValue).padStart(3, '0');
    }
    console.log('values--11-', values)
    
   let orgInfo = systemState.orgInfo;
    let orgCode: string[] = []
    if(orgInfo && orgInfo.value){
      const orgValue = JSON.parse(orgInfo.value)
      orgValue && orgValue.forEach((org: OrgOptions) => {
        orgCode.push(org.value)
      })
    }
    const params = {
      operator: values["operator"],//操作员
      name: values["name"],//测量名称
      location: values["location"],//位置
      direction: values["direction"],//方向
      tljCode: orgCode[0],//values["tljCode"],//铁路局
      gwdCode: orgCode[1],//values["gwdCode"],//铁路段
      xmCode: orgCode[2],//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:[]
    };

    
    if(values.orgValues && values.orgValues.length){
      const orgItem = {
        tljCode: values.orgValues[0],
        gwdCode: values.orgValues[1],
        xmCode: values.orgValues[2]
      }
      localStorage.setItem('orgInfo', JSON.stringify(orgItem));
      params.tljCode = values.orgValues[0]
      params.gwdCode = values.orgValues[1]
      params.xmCode = values.orgValues[2]
    }
    
    params.extraDesc = JSON.stringify(extraDesc)
    let measureData = measureState.measureData;
    if(measureData && measureData.length){
      params.alignPoints = measureData
    }
    localStorage.setItem('measureForm', JSON.stringify(params))
    console.log('params---', params)
    saveMeasurement_new(params)
      .then((res) => {
        if (res.success) {
          messageApi.error(res.data.info);
        } else {
          message.success("保存成功");
          navigate("../action");
        }
      })
      .catch((e) => {
        navigate("../action");
      });
  };

  const resetLabel = (labelName: string) => {
    return <label style={{ fontSize: '20px' }}>{ labelName }</label>
  }

  return (
    <Spin spinning={loading}>
      <div >
        <Form
          form={form}
          size="large"
          labelCol={{span: 6}}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <div style={{marginTop: '1rem', display:'grid', gridTemplateColumns: '1fr 1fr 1fr'}}>
            <Form.Item
              labelCol={{span: 3}}
              style={{marginLeft:'-1rem'}}
              label={resetLabel('测量名称')} 
              name="name"
              rules={[{ required: true, message: "请输入测量名称" }]}
            >
              <Input ref={inputRef}  style={{width: '71vw'}} className="label-vh" placeholder="请输入测量名称" />
            </Form.Item>
          </div>

          <div className="layout">
            <Form.Item
              label={resetLabel('操作员')} 
              name="operator"
              rules={[{ required: true, message: "请输入操作员姓名" }]}
            >
              <Input className="label-vh  w-[18vw]"/>
            </Form.Item>
						{/* <Form.Item
              label={resetLabel('铁路局')} 
							name="orgValues"
							rules={[{ required: true, message: "请选择铁路局" }]}
						>
							<Cascader className='label-vh w-[600px]' key={orgValues.length} defaultValue={orgValues} options={KTJOrgList} onChange={onOrgChange} placeholder="请选择局段线" />
						</Form.Item> */}
            <Form.Item
              label={resetLabel('轨型')}
              name="railSize"
              rules={[{ required: true, message: "请选择轨型" }]}
            >
              <Select
                className="label-vh select-w200"
                placeholder="请选择轨型"
                onChange={onRailTypeChange}
                options={WRPS_GGGX_List.map((item) => ({
                  label: item.value,
                  value: item.key,
                }))}
              ></Select>
            </Form.Item>

            <Form.Item
              label={resetLabel('数据来源')}
              name="dataSource"
              rules={[{ required: true, message: "请选择数据来源" }]}
            >
              <Select
                className="label-vh"
                placeholder="请选择数据来源"
                onChange={onDataSourceChange}
                options={SJLY_List.map((item) => ({
                  label: item.value,
                  value: item.key,
                }))}
              ></Select>
            </Form.Item>            
            {dataSource === "DCDC" &&
            <Form.Item
              label={resetLabel('车站')}
							name="stationCode"
							rules={[{ required: true, message: "请选择车站" }]}
						>
							<Select
                className="label-vh"
                style={{width: '18vw'}}
								placeholder="请选择车站"
                onChange={onSatioinChange}
                options={stationList.map((item) => ({
                  label: item.value,
                  value: item.key,
                }))}
							>
							</Select>
						</Form.Item>}
            

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

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

            <Form.Item
              label={resetLabel('批次')}
              name="batch"
              rules={[{ required: true, message: "请输入批次" }]}
            >
              <InputNumber className="label-vh w-[18vw]" placeholder="请输入批次" />
            </Form.Item>
            {dataSource === 'DCDC' ? (
              <>
                <Form.Item
                  label={resetLabel('道岔号')}
                  name="turnoutNum"
                  rules={[{ required: true, message: "请输入道岔号" }]}
                >
                  <InputNumber className="abel-vh w-[18vw]" placeholder="请输入道岔号" />
                </Form.Item>

                <Form.Item
                  label={resetLabel('枕木号')}
                  name="sleeperNum"
                  rules={[{ required: true, message: "请输入枕木号" }]}
                >
                  <InputNumber className="abel-vh w-[18vw]"  placeholder="请输入枕木号" />
                </Form.Item>
              
                <Form.Item
                label={resetLabel('行别')}
                name="xbCode"
                rules={[{ required: true, message: "请选择行别" }]}
                
              >
                <Select className="label-vh" placeholder="请选择行别" options={xbCodeOptions}>
                </Select>
              </Form.Item>
              </>
            ) : (
              <Form.Item
              label={resetLabel('行别')}
              name="xbCode"
              rules={[{ required: true, message: "请选择行别" }]}
            >
              <Select  placeholder="请选择行别"
              className="label-vh"
              options={XB_CODES.map((item) => ({
                label: item.name,
                value: item.code,
              }))}
              >
              </Select>
            </Form.Item>
            )}
            
            {dataSource === "XLDC" &&
              <>
                  <Form.Item
                    label={resetLabel('里程')}
                    name="kilometre"
                    rules={[{ required: true, message: "请输入" }]}
                  >
                    <div style={{display:"flex",alignItems:"center"}}>
                      <InputNumber className="label-vh  w-[16vw]" defaultValue={kilMet.kilometre === 'undefined' ? '' : kilMet.kilometre} placeholder="公里" />千米
                    </div>
                  </Form.Item>
                  <Form.Item
                    label={resetLabel('百米')}
                    name="meters"
                    rules={[{ required: true, message: "请输入" }]}
                  >
                    <div style={{display:"flex",alignItems:"center"}}>
                      <InputNumber className="label-vh  w-[18vw]" defaultValue={kilMet.meters === 'undefined' ? '' : kilMet.meters}  placeholder="百米" />米
                    </div>
                  </Form.Item>
              </>
            }

            <Form.Item
              label={resetLabel('股别')}
              name="unitType"
              rules={[{ required: true, message: "请选择股别" }]}
            >
              <Select className="label-vh" placeholder="请选择股别" onChange={onUnitTypeChange} options={unitTypeList}>
              </Select>
            </Form.Item>
            {unitType === 2 && 
              <Form.Item
                label={resetLabel('半径')}
                name="radius"
                rules={[{ required: true, message: "请输入半径" }]}
              >
                <InputNumber className="label-vh 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>
    </Spin>
  );
}
