components/SpeedLimitFiller.tsx

src/ui/components/widgets/SpeedLimitSection/components/SpeedLimitFiller.tsx
mail@pastecode.io avatar
unknown
typescript
18 days ago
12 kB
1
Indexable
Never
import { useSearchParams } from '@Hooks'
import { CButton, CLabel, CRow, CSelect } from '@coreui/react'
import { useLocation } from 'react-router-dom'
import { ActionTypes, actionCreatorsProps, speedLimitStates } from '../types'
import { useCallback, useEffect, useLayoutEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import {
  fetchTSOSpeedLimitsByRouteId,
  fetchZoneSpeedLimitsByRouteId
} from '@Redux/slices/portalDataSlice'
import { useSpeedLimitStore } from '@Contexts'
import { Icons } from '@Assets/icons/Icons'
import CustomDropDown from './DropDown/CustomDropDown'
import { PORTAL_ROLE } from '@Constants'

interface SpeedLimitFillerType {
  state: speedLimitStates
  actions: actionCreatorsProps
}

const SpeedLimitFiller = ({ state, actions }: SpeedLimitFillerType) => {
  const searchParams = useSearchParams<
    'route-id' | 'direction' | 'type' | 'page'
  >()
  const dispatch = useDispatch()
  const location = useLocation()
  const { data: userInfoData } = useSelector((state: any) => state.userInfo)
  const isAdmin =
    userInfoData.roles.includes(PORTAL_ROLE.RAILVISION_ADMIN) ||
    userInfoData.roles.includes(PORTAL_ROLE.PORTAL_ADMIN)
  const {
    data: { railroadId }
  } = useSelector((state: any) => state.userInfo)

  const {
    zoneSpeedLimitsByRouteId: {
      data: zoneSpeedLimitsData,
      loading: zoneSpeedLimitsLoading,
      error: zoneSpeedLimitsError
    }
  } = useSelector((state: any) => state.portalData)

  const {
    TSOSpeedLimitsByRouteId: {
      data: TSOSpeedLimitsData,
      loading: TSOSpeedLimitsLoading,
      error: TSOSpeedLimitsError
    }
  } = useSelector((state: any) => state.portalData)

  const speedLimitStore = useSpeedLimitStore

  const { actionType, directionList, direction, routeId, routes, type } = state
  // console.log('🚀 ~ SpeedLimitFiller ~ directionList:', directionList)
  // const [isDisable, setIsDisable] = useState<boolean>()
  const speedLimitData = useSpeedLimitStore.use.speedLimits()
  const removeFirstSpeedLimit = useSpeedLimitStore.use.removeFirstSpeedLimit()

  const handleSelectionTypeChange = useCallback(
    (selected: string[]) => {
      const type = selected.join(',')
      if (type !== '') {
        searchParams.setSearchParam({ k: 'type', v: type })
      } else {
        searchParams.delSearchParam('type')
      }
      setTimeout(() => {
        actions.onChangePage('')
        actions.onChangeType(type)
      }, 50)
    },
    [actions, searchParams]
  )

  useEffect(() => {
    const routeIdParam = searchParams.getSearchParam('route-id')
    const directionParam = searchParams.getSearchParam('direction')
    const endDestinationId = routeIdParam
      ?.split('_')
      .filter(item => item !== directionParam)
    if (routeIdParam) {
      dispatch(
        fetchZoneSpeedLimitsByRouteId({
          routeId: routeIdParam,
          railroadId: railroadId,
          startDestinationId: directionParam,
          endDestinationId: endDestinationId![0]
        })
      )
      dispatch(
        fetchTSOSpeedLimitsByRouteId({
          routeId: routeIdParam,
          railroadId: railroadId,
          startDestinationId: directionParam,
          endDestinationId: endDestinationId![0]
        })
      )
    }
  }, [])

  // useEffect(() => {
  //   const routeIdParam = searchParams.getSearchParam('route-id')
  //   routeIdParam && actions.onChangeRouteId(routeIdParam)
  // }, [route])

  useEffect(() => {
    const routeIdParam = searchParams.getSearchParam('route-id')
    if (!routeIdParam) {
      const routeId = routes?.[0]?.route_id
      const routeName = routes?.[0]?.route_name
      const direction = routeId?.split('_')
      searchParams.setSearchParam({ k: 'route-id', v: routeId })
      searchParams.setSearchParam({ k: 'direction', v: direction?.[0] })
      searchParams.setSearchParam({ k: 'type', v: 'TSO' })
      const payload = {
        routeId: routeId,
        routeName: routeName,
        type: 'TSO'
      }
      if (routeId) {
        actions.onInitStates(payload)
        dispatch(
          fetchZoneSpeedLimitsByRouteId({
            routeId: routeId,
            railroadId: railroadId,
            startDestinationId: direction?.[0],
            endDestinationId: direction?.[1]
          })
        )
        dispatch(
          fetchTSOSpeedLimitsByRouteId({
            routeId: routeId,
            railroadId: railroadId,
            startDestinationId: direction?.[0],
            endDestinationId: direction?.[1]
          })
        )
      }
    } else {
      actions.onChangeRouteId(routeIdParam)
    }
  }, [routes])

  useEffect(() => {
    const routeIdParam = searchParams.getSearchParam('route-id')
    const directionParam = searchParams.getSearchParam('direction')
    const typeParam = searchParams.getSearchParam('type')

    routeIdParam && actions.onChangeRouteId(routeIdParam)

    directionParam && actions.onChangeDirection(directionParam)

    typeParam && actions.onChangeType(typeParam)
  }, [])

  useEffect(() => {
    state.page !== ''
      ? searchParams.setSearchParam({ k: 'page', v: state.page })
      : searchParams.delSearchParam('page')
  }, [state.page])

  // useEffect(() => {
  //   routeId ? setIsDisable(false) : setIsDisable(true)
  // }, [routeId])

  return (
    <CRow className="justify-between mx-0 mb-4 py-8 ">
      <div className="flex w-[70%] flex-wrap gap-8">
        <div className="w-[25%]">
          <CLabel
            key="routeId"
            className="flex justify-center w-full font-semibold"
          >
            Route
          </CLabel>
          <CSelect
            className=" text-center text-align-last-center w-full"
            value={routeId}
            onChange={(e: any) => {
              const v = e.target.value
              const direction = v.split('_')

              if (v) {
                searchParams.setSearchParam({ k: 'route-id', v })
                searchParams.setSearchParam({ k: 'direction', v: direction[0] })
              }

              actions.onChangeRouteId(v)
              actions.onChangeDirection(direction?.[0])

              if (v) {
                dispatch(
                  fetchZoneSpeedLimitsByRouteId({
                    routeId: v,
                    railroadId: railroadId,
                    startDestinationId: direction[0],
                    endDestinationId: direction[1]
                  })
                )
                dispatch(
                  fetchTSOSpeedLimitsByRouteId({
                    routeId: v,
                    railroadId: railroadId,
                    startDestinationId: direction[0],
                    endDestinationId: direction[1]
                  })
                )
              }
            }}
          >
            {routes?.map((item, index) => (
              <option className="text-left" value={item?.route_id} key={index}>
                {item?.route_name}
              </option>
            ))}
          </CSelect>
        </div>

        <div className="w-[25%]">
          <CLabel key="direction" className="flex justify-center w-full">
            Direction
          </CLabel>
          <CSelect
            className="text-center text-align-last-center w-full"
            value={direction}
            onChange={(e: any) => {
              const v = e.target.value
              const endDestinationId = directionList.filter(
                item => item?.value !== v
              )

              v !== ''
                ? searchParams.setSearchParam({ k: 'direction', v: v })
                : searchParams.delSearchParam('direction')

              dispatch(
                fetchZoneSpeedLimitsByRouteId({
                  routeId: routeId,
                  railroadId: railroadId,
                  startDestinationId: v,
                  endDestinationId: endDestinationId[0]?.value
                })
              )
              dispatch(
                fetchTSOSpeedLimitsByRouteId({
                  routeId: routeId,
                  railroadId: railroadId,
                  startDestinationId: v,
                  endDestinationId: endDestinationId[0]?.value
                })
              )
              actions.onChangeDirection(v)
            }}
          >
            {directionList?.length > 1 &&
              directionList?.map(item => {
                return (
                  <option
                    className="text-left"
                    key={item?.value}
                    value={item?.value}
                  >
                    To {item?.text}
                  </option>
                )
              })}
          </CSelect>
        </div>
        <div className="w-[25%]">
          <CLabel key="type" className="flex justify-center w-full">
            Type
          </CLabel>
          <CustomDropDown
            type={type}
            options={[
              { value: 'Zone', label: 'Zone' },
              { value: 'TSO', label: 'TSO' }
            ]}
            search={false}
            placeholder="Select Type"
            onChange={handleSelectionTypeChange}
          />
          {/* <CSelect
            className="w-full text-center text-align-last-center"
            value={type}
            onChange={e => {
              const v = (e.target as HTMLInputElement).value
              v !== ''
                ? searchParams.setSearchParam({ k: 'type', v: v })
                : searchParams.delSearchParam('type')
              setTimeout(() => {
                actions.onChangePage('')
              }, 50)
              actions.onChangeType(v)
            }}
          >
            <option className="text-left" value="">
              Any
            </option>
            <option className="text-left" value="Zone">
              Zone
            </option>
            <option className="text-left" value="TSO">
              TSO
            </option>
          </CSelect> */}
        </div>
      </div>

      {isAdmin && (
        <div className="flex w-[30%] gap-4 items-end justify-end">
          <CButton
            onClick={() => {
              actions.onChangeActionType(ActionTypes.Add)
            }}
            // disabled={isDisable}
            className="bg-slate-500 text-white w-max "
          >
            <div className="flex justify-center items-center gap-2">
              <Icons.AddIcon className="w-[14px] h-[14px]" />
              <span>Add Speed Limit</span>
            </div>
          </CButton>

          {actionType === ActionTypes.Edit ||
          actionType === ActionTypes.EditItem ? (
            <CButton
              onClick={() => {
                actions.onChangeActionType(ActionTypes.View)
                actions.onSelectedItem({
                  selectedIndex: -1,
                  selectedItemData: null
                })
              }}
              className="bg-red-400 stroke-[#D9DBE0] text-white w-24"
            >
              <div className="flex justify-center items-center gap-1">
                <Icons.EditIcon className="stroke-red-400" />
                <span>Cancel</span>
              </div>
            </CButton>
          ) : (
            <CButton
              onClick={() => {
                Object.keys(speedLimitData?.[0]!).length === 0 &&
                  speedLimitData?.[0].constructor === Object &&
                  removeFirstSpeedLimit()
                actions.onChangeActionType(ActionTypes.Edit)
                actions.onSelectedItem({
                  selectedIndex: -1,
                  selectedItemData: null
                })
              }}
              disabled={
                zoneSpeedLimitsData?.length === 0 &&
                TSOSpeedLimitsData?.length === 0
              }
              className="bg-[#DDDDDD] stroke-[#D9DBE0] text-[#3F4B62]"
            >
              <div className="flex justify-center items-center gap-1">
                <Icons.EditIcon />
                <span>Edit</span>
              </div>
            </CButton>
          )}
        </div>
      )}
    </CRow>
  )
}

export default SpeedLimitFiller
Leave a Comment