import { useState, useEffect } from 'react'

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


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

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

    useEffect(updateParams, [idWell])

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

    const onAdd = async (param) => {
        param.idWell = idWell
        await DrillParamsService.save(idWell, param)
        updateParams()
    }

    const onEdit = async (param) => {
        if (!param.id) return
        param.idWell = idWell
        await DrillParamsService.edit(idWell, param)
        updateParams()
    }

    const onDelete = async (param) => {
        if (!param.id) return
        await DrillParamsService.delete(idWell, param.id)
        updateParams()
    }

    return (
        <LoaderPortal show={showLoader}>
            <EditableTable
                size={'small'}
                bordered
                columns={columns}
                dataSource={params}
                onRowAdd={onAdd}
                onRowEdit={onEdit}
                onRowDelete={onDelete}
            />
        </LoaderPortal>
    )
}
