import { useState, useEffect } from 'react'

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

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

export const DrillProcessFlow = ({idWell}) => {
    const [flows, setFlows] = useState([])
    const [showLoader, setShowLoader] = useState(false)

    const updateFlows = () => invokeWebApiWrapperAsync(
        async () => {
            const flows = await DrillFlowChartService.get(idWell)
            setFlows(Array.isArray(flows) ? flows : [])
        },
        setShowLoader,
        'Не удалось загрузить режимно-технологическую карту скважины'
    )

    useEffect(updateFlows, [idWell])

    const onAdd = async (param) => {
        param.idWell = idWell
        await DrillFlowChartService.insert(idWell, param)
        updateFlows()
    }

    const onEdit = async (param) => {
        if (!param.id) return
        param.idWell = idWell
        await DrillFlowChartService.update(idWell, param.id, param)
        updateFlows()
    }

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

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