import React, { useEffect, useState } from 'react';
import { Checkbox, message, Popover } from 'antd';
import classNames from 'classnames';
import _ from 'lodash';
import { config } from './base/config';
import { getEditComponent } from './base';
import s from './Cell.less';
import { CellProps, CellDataProps } from './interface';
import FormHelper from '../utils/formHelper';
import firstIcon from '../assets/first.png';
import secondIcon from '../assets/second.png';
import thirdIcon from '../assets/third.png';
import expandIcon from '../assets/extend.png';
import { transferAttr } from './base/_utils/transferAttr';

const Cell = (props: CellProps) => {
    const {
        columnConfig,
        cellClassName,
        cellStyle,
        record,
        columnData,
        value: cellData,
        emitChangeCell,
        columnIndex,
        rowIndex,
        paginationConfig,
        showIndex,
        emptyPlaceholder,
        cellEditable,
        rowSelection,
        columns,
        contentMenu,
        selectedCell,
        cellKey,
        changeSelectedCell,
        position = 'center',
    } = props;
    const {
        columnType,
        columnName,
        requiredFlag,
        renderDetailCell,
        renderEditCell,
        cellRenderProps,
        readOnlyFlag,
        showExpand,
    } = columnConfig;
    const [status, setStatus] = useState('detail');

    useEffect(() => {
        setStatus('detail');
    }, [cellData]);

    const changeCellData = (changedValue: any) => {};
    const emitChangeCellData = (changedValue: any, optionValue: any) => {
        const temp: CellDataProps[] = [];
        cellData.map((item: CellDataProps) => {
            temp.push({ text: item.text, value: item.value });
        });
        if (_.isEqual(temp, changedValue)) {
            setStatus('detail');
            return;
        }
        changeValue(changedValue, optionValue);
    };

    const changeValue = async (changedValue: any, optionValue: any) => {
        // 校验必填项
        if (requiredFlag) {
            if (!changedValue || changedValue.length === 0) {
                message.error('该字段为必填项');
                return;
            }
            if (changedValue.length === 1) {
                const data = changedValue[0];
                if (!data.value && !data.text) {
                    message.error('该字段为必填项');
                    return;
                }
            }
        }
        const extraData = FormHelper.changeTableData({
            item: columnConfig,
            changedKey: columnName,
            changedValue,
            originValue: optionValue,
        });
        extraData.push({
            columnCode: columnName,
            cellValueList: changedValue,
        });
        if (typeof emitChangeCell === 'function') {
            emitChangeCell({
                rowId: record.id,
                value: extraData,
            });
        }
        setStatus('detail');
    };

    const selfRenderDetailCell = () => {
        let empty =
            !cellData || cellData.length === 0 || (cellData.length === 1 && !cellData[0].text && !cellData[0].value);
        let detailConfig;
        if (typeof renderDetailCell === 'function') {
            detailConfig = renderDetailCell({ cellData, rowData: record, columnConfig });
            empty = false;
        } else {
            detailConfig = config[String(columnType)] || config['1'];
        }
        const DetailComp: any = detailConfig.detailComp;

        const newProps = {
            ...(detailConfig.componentAttr || {}),
            ...(columnConfig.columnAttrObj || {}),
        };
        const transferColumn = transferAttr(columnType, newProps);

        const style: any = {};
        const { current = 1, pageSize = 20 } = paginationConfig || {};

        const getIndex = () => {
            // if (current === 1) {
            //     let src = '';
            //     switch (rowIndex) {
            //         case 0:
            //             src = firstIcon;
            //             break;
            //         case 1:
            //             src = secondIcon;
            //             break;
            //         case 2:
            //             src = thirdIcon;
            //             break;
            //         default:
            //             return rowIndex + 1;
            //     }
            //     return <img className={s.icon} alt="" src={src} />;
            // }
            return (current - 1) * pageSize + rowIndex + 1;
        };
        const getCheckbox = () => {
            const { selectedRows, onChange } = rowSelection;
            const index = selectedRows.findIndex((item: any) => {
                return item.id === record.id;
            });
            const checked = index > -1;
            const onToggle = () => {
                if (typeof onChange === 'function') {
                    const data = _.cloneDeep(selectedRows);
                    if (checked) {
                        data.splice(index, 1);
                    } else {
                        data.push(record);
                    }
                    onChange(data);
                }
            };
            return <Checkbox checked={checked} onClick={onToggle} />;
        };

        const { dynamicCellConfigDTO } = columnData;

        const detail = (
            <div
                className={
                    selectedCell === `${position}_${cellKey}` ? classNames(s.detailCell, s.selected) : s.detailCell
                }
                onClick={() => {
                    // 不可编辑状态
                    if (!cellEditable || readOnlyFlag || (dynamicCellConfigDTO && dynamicCellConfigDTO.readonlyFlag)) {
                        return false;
                    }
                    if (selectedCell === `${position}_${cellKey}`) {
                        setStatus('edit');
                    } else {
                        changeSelectedCell && changeSelectedCell(`${position}_${cellKey}`);
                    }
                }}
                // onDoubleClick={() => {
                //     cellEditable && !readOnlyFlag && setStatus('edit');
                // }}
                style={style}
            >
                {rowSelection && columnIndex === 0 && <div className={s.checkbox}>{getCheckbox()}</div>}
                {showIndex && columnIndex === 0 && <div className={s.num}>{getIndex()}</div>}
                {showExpand && columnIndex === 0 && (
                    <div className={s.expand}>
                        <img
                            onClick={showExpand.bind(null, { rowId: record.id })}
                            className={s.expandIcon}
                            alt=""
                            src={expandIcon}
                        />
                    </div>
                )}
                {empty ? (
                    emptyPlaceholder || '-'
                ) : (
                    <div className={s.content}>
                        <DetailComp
                            value={cellData}
                            columns={columns}
                            rowData={record}
                            columnConfig={columnConfig}
                            componentAttr={transferColumn}
                            formatter={detailConfig.getFormatter}
                            cellRenderProps={cellRenderProps}
                        />
                    </div>
                )}
            </div>
        );

        return contentMenu ? (
            <Popover
                overlayClassName={s.menuPop}
                trigger="contextMenu"
                placement="rightTop"
                content={
                    <div role="presentation" className={style.menuContainer}>
                        {contentMenu.map((item: any, i: number) => {
                            return (
                                <div
                                    key={i}
                                    role="presentation"
                                    className={style.menu}
                                    onClick={item.onClick.bind(null, record)}
                                >
                                    {item.label}
                                </div>
                            );
                        })}
                    </div>
                }
            >
                {detail}
            </Popover>
        ) : (
            detail
        );
    };

    const selfRenderEditCell = () => {
        let editConfig;
        if (typeof renderEditCell === 'function') {
            editConfig = renderEditCell({ cellData, rowData: record, columnConfig });
        } else {
            editConfig = config[String(columnType)] || config['1'];
        }

        const EditComp: any = getEditComponent(editConfig, true);

        return (
            <div className={s.editCell}>
                <EditComp
                    value={cellData}
                    columnConfig={columnConfig}
                    onChange={changeCellData}
                    onEmitChange={emitChangeCellData}
                    style={{
                        minHeight: cellStyle.height,
                        borderRadius: 0,
                    }}
                />
            </div>
        );
    };

    return (
        <div className={cellClassName} style={cellStyle}>
            {status === 'detail' && selfRenderDetailCell()}
            {status === 'edit' && selfRenderEditCell()}
        </div>
    );
};

export default Cell;
