import { useState, useEffect } from 'react'

import { DrillParamsService } from '../../services/api'
import LoaderPortal from '../../components/LoaderPortal'
import { invokeWebApiWrapperAsync } from '../../components/factory'
import { EditableTable, SelectFromDictionary } from '../../components/Table'
import { makeActionHandler, makeColumn, makeNumericAvgRange } from '../../components/Table'

import { dictionarySectionType, getByKeyOrReturnKey } from './dictionary'

export const columns = [
    makeColumn('Конструкция секции','idWellSectionType', {
        editable: true,
        input: <SelectFromDictionary dictionary={dictionarySectionType}/>,
        width: 160,
        render: (_, record) => getByKeyOrReturnKey(dictionarySectionType, record.idWellSectionType)
    }),
    makeNumericAvgRange('Нагрузка, т', 'axialLoad', 1),
    makeNumericAvgRange('Давление, атм', 'pressure', 1),
    makeNumericAvgRange('Момент на ВСП, кН·м', 'rotorTorque', 1),
    makeNumericAvgRange('Обороты на ВСП, об/мин', 'rotorSpeed', 1),
    makeNumericAvgRange('Расход, л/с', 'flow', 1)
]

export const WellDrillParams = ({ idWell }) => {
    const [params, setParams] = useState([])
    const [showLoader, setShowLoader] = useState(false)

    const updateParams = () => invokeWebApiWrapperAsync(
        async () => {
            const params = await DrillParamsService.getAll(idWell)
            setParams(Array.isArray(params) ? params : [])
        },
        setShowLoader,
        'Не удалось загрузить список режимов бурения скважины'
    )

    useEffect(updateParams, [idWell])

    const handlerProps = {
        service: DrillParamsService,
        setLoader: setShowLoader,
        errorMsg: `Не удалось выполнить операцию`,
        onComplete: updateParams,
        idWell
    }

    const recordParser = (record) => ({ ...record, idWell })

    return (
        <LoaderPortal show={showLoader}>
            <EditableTable
                size={'small'}
                bordered
                columns={columns}
                dataSource={params}
                onRowAdd={makeActionHandler('insert', handlerProps, recordParser)}
                onRowEdit={makeActionHandler('update', handlerProps, recordParser)}
                onRowDelete={makeActionHandler('delete', handlerProps, recordParser)}
                pagination={false}
            />
        </LoaderPortal>
    )
}
