Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
5.4 kB
1
Indexable
Never
import { useCallback, useEffect, useState } from 'react';

import { type IApiRequest } from '@/api/api.interface';
import { useGet } from '@/api/api.middleware';
import { type IColumnConfigTableSelection } from '@/core2/table/tableSelection';
import UpAndDownComponent from '@/features/forLeasing/create/steps/StepTwoDetailedInformation/upDownComponent';
import { Helper } from '@/utils/Helper';
import { LoggerService } from '@/utils/Logger';

import { type IDetailedInformationListData } from '../../interface';
import { type IComponentProps } from '../interface';
import DetailedInformationView from './view';

interface IDetailedInformationComponentProps extends IComponentProps {
  apiAddNewFloor: IApiRequest;
}
interface IDetailedInformationResponseListRacks {
  height: number;
  length: number;
  name: string;
  racksTemplateId: string;
  width: number;
}
interface IDetailedInformationComponentState {
  templateRacks: Record<string, number>;
  gridColumns: IColumnConfigTableSelection[];
  dataList: IDetailedInformationListData[];
}
const initState: IDetailedInformationComponentState = { templateRacks: {}, gridColumns: [], dataList: [] };
function DetailedInformationComponent({
  apiAddNewFloor,
  onChangePayload,
  ...others
}: IDetailedInformationComponentProps) {
  const [state, setState] = useState<IDetailedInformationComponentState>(initState);
  const [shouldRenderDefault, setShouldRenderDefault] = useState(true);

  const handleListSpaceForLeasingParse = (item: IDetailedInformationListData) => {
    const listSpaceForLeasing: Array<{ racksTemplateId: string }> = [];
    for (const key of Object.keys(item)) {
      if (key !== 'id' && key !== 'floor') {
        for (let i = 0; i < item[key]; i++) {
          listSpaceForLeasing.push({ racksTemplateId: key });
        }
      }
    }
    return listSpaceForLeasing;
  };

  useEffect(() => {
    if (state.gridColumns.slice(1).length > 0 && shouldRenderDefault) {
      const convertFloors = others.detail.floorStoreList.map(floor => {
        return {
          floor: floor.name,
          id: floor.floorStoreId,
          isSelected: true,
          ...state.gridColumns.slice(1).reduce((total, column) => {
            return {
              ...total,
              [column.field]: 0,
            };
          }, {}),
          ...floor.displayRacksForLeasing.reduce((total, rack) => {
            return {
              ...total,
              [rack.rackTemplateId]: 1,
            };
          }, {}),
        };
      });
      setState(prev => ({ ...prev, dataList: convertFloors }));
      setShouldRenderDefault(false);
    }
  }, [state.gridColumns]);

  useEffect(() => {
    const displayRacksForLeasing =
      state.dataList.length > 0
        ? state.dataList.map((item, id) => ({
            isDisabled: item.isSelected ? 0 : 1,
            floor: id,
            listSpaceForLeasing: handleListSpaceForLeasingParse(item),
          }))
        : [];
    onChangePayload && onChangePayload({ displayRacksForLeasing });
  }, [state.dataList]);

  const handleAddFloor = () => {
    const { dataList, templateRacks } = state;
    const floorName = dataList.length === 0 ? 'Ground floor' : `Floor ${dataList.length}`;
    const newDataList: IDetailedInformationListData[] = [
      ...dataList,
      { floor: floorName, id: Helper.randomKey(), ...templateRacks },
    ];
    setState(prev => ({ ...prev, dataList: newDataList }));
  };

  const handleChangeSelect = (data: any) => {
    setState(prev => ({ ...prev, dataList: data }));
  };

  const handleChangeValueRack = (data: { floor: string; id: string } & Record<string, any>) => {
    console.log('handleChangeValueRack', data);
    const { dataList } = state;
    const index = dataList.findIndex(item => item.id === data.id);
    dataList[index] = data;
    setState(prev => ({ ...prev, dataList }));
  };
  const addNewFloorResponseFunc = {
    handleRequestSuccess: (data: IDetailedInformationResponseListRacks[]) => {
      try {
        if (data.length > 0) {
          const gridColumns: IColumnConfigTableSelection[] = data.map(item => ({
            field: item.racksTemplateId,
            title: (
              <div>
                <p className='m-0'>{item.name}</p>
                <span className='text-neutral-70'>{`L ${item.length} W ${item.width} H ${item.height}`}</span>
              </div>
            ),
            cell: dataItem => (
              <UpAndDownComponent
                field={item.racksTemplateId}
                data={dataItem}
                onChange={handleChangeValueRack}
              />
            ),
          }));
          gridColumns.unshift({ field: 'floor', title: 'Floor' });
          const templateRacks: Record<string, number> = {};
          for (const item of data) {
            templateRacks[item.racksTemplateId] = 0;
          }
          setState(prev => ({ ...prev, gridColumns, templateRacks }));
        }
      } catch (error: any) {
        LoggerService.error('addNewFloorResponseFunc excuted handleRequestSuccess received error', error);
      }
    },
  };
  useGet(apiAddNewFloor, addNewFloorResponseFunc);

  return (
    <DetailedInformationView
      handleAddFloor={handleAddFloor}
      gridColumns={state.gridColumns}
      dataList={state.dataList}
      handleChangeSelect={handleChangeSelect}
      {...others}
    />
  );
}

export default DetailedInformationComponent;
Leave a Comment