import { defineComponent, PropType } from '@vue/composition-api';
import { CellValue, EditingData, IndexColumn } from '@/lib/types';
import { TextCell } from '@/lib/components/body/cell/text-cell';
import { useOperator, useStoreInject } from '@/lib/store';
import { useWatchRowData } from '@/lib/composables/watch-row-data';
import { Operator } from '@/lib/operator';
import { EditOperator } from '@/lib/operator/EditOperator';

export const CalculateCell = defineComponent({
    name: 'CalculateCell',
    props: {
        rowId: {
            required: true,
            type: String,
        },
        columnId: {
            required: true,
            type: String,
        },
        calculator: {
            required: false,
            type: Array as unknown as PropType<IndexColumn['calculator']>,
        },
        formatter: {
            required: false,
            type: Function as PropType<IndexColumn['formatter']>,
        },
        renderer: {
            required: false,
            type: Function as PropType<IndexColumn['renderer']>,
        },
        data: {
            require: true,
            type: Object as PropType<EditingData>,
        },
    },
    setup(props) {
        const { rowId, columnId, calculator, data } = props;
        const editOperator = useOperator<EditOperator>(Operator.edit);
        const { state } = useStoreInject();
        const calculateValue = (value: string) =>
            editOperator.calculateCell(rowId, columnId, value);
        const theValue = useWatchRowData<CellValue>(
            rowId,
            state,
            data.value,
            calculator,
            calculateValue,
            false,
        );
        return {
            theValue,
        };
    },
    render(h) {
        const { theValue, formatter, renderer } = this;
        if (renderer) return renderer(theValue);
        const text = formatter ? formatter(theValue.value) : `${theValue.value || ''}`;
        return h(TextCell, {
            props: {
                text,
            },
        });
    },
});
