import React from 'react';
import { EditCellProps, EditCellState } from './interface';
import FormHelper from '../utils/formHelper';

const formatData = (columns: [], rowData: [], noEdit?: boolean) => {
    const temp: any[] = [];
    columns.forEach((item: any) => {
        const value: any = rowData.find((itemData: any) => {
            return itemData.colName === item.key;
        });
        temp.push({
            ...item,
            value: (value && value.cellValueList) || [{ text: '', value: '' }],
            type: item.columnType,
            readonlyFlag: noEdit ? true : item.readonlyFlag,
        });
    });
    return temp;
};
const formHelp = (columns: [], record: any, item: any) => {
    const list = formatData(columns, record.rowData);
    const itemsConfig = FormHelper.getFormData({ list, rowLocked: record.isLocked });
    return itemsConfig.find((temp: any) => {
        return temp.columnName === item.columnName;
    });
};
export default class EditCell extends React.Component {
    static getDerivedStateFromProps(nextProps: EditCellProps, prevState: EditCellState) {
        const { prevProps } = prevState;
        let columnConfig = formHelp(nextProps.columns, nextProps.rowData, nextProps.columnConfig);

        let nextState: EditCellState = {
            ...prevState,
            prevProps: nextProps,
            columnConfig,
        };
        if (
            JSON.stringify(prevProps.columnConfig) !== JSON.stringify(nextProps.columnConfig) ||
            JSON.stringify(prevProps.rowData) !== JSON.stringify(nextProps.rowData)
        ) {
            let columnConfig = formHelp(nextProps.columns, nextProps.rowData, nextProps.columnConfig);
            if (JSON.stringify(prevState.columnConfig) !== JSON.stringify(columnConfig)) {
                nextState.columnConfig = columnConfig;
            }
        }
        return nextState;
    }
    constructor(props: EditCellProps) {
        super(props);
        this.state = {
            prevProps: props,
            columnConfig: {},
        };
    }

    handleChange = (newValue: any, originValue: any, emitFlag: boolean) => {
        const { onChange } = this.props;
        if (typeof onChange === 'function') {
            onChange(newValue, originValue, emitFlag);
        }
    };

    render() {
        const { columnConfig } = this.state;
        const { component, value, tableId, cellData, rowId } = this.props;
        const Component = component;
        return (
            <Component
                value={value}
                changeParams={this.handleChange}
                columnConfig={columnConfig}
                autoFocus={true}
                style={{ width: '100%' }}
                tableId={tableId}
                cellData={cellData}
                rowId={rowId}
            />
        );
    }
}
