import React, { useCallback, useState } from 'react';
import { Form, Input, Drawer, Button, AutoTableContainer, Pagination, Table, } from 'kts-xui';
import { Space, Row } from 'kts-components-antd-x4';
import GoodsAdd from './GoodsAdd';
import ImportGoodsSource from './ImportGoodsSource';
import GoodImportExcel from './GoodsImportExcel';
interface Item {
    key: string;
    name: string;
    model: string;
}
const originData: Item[] = [];
for (let i = 0; i < 10; i++) {
    originData.push({
        key: i.toString(),
        name: `Edrward ${i}`,
        model: `London Park no. ${i}`,
    });
}
interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
    editing: boolean;
    dataIndex: string;
    title: any;
    record: Item;
    index: number;
    children: React.ReactNode;
   
}
interface IProps {
    onClose: () => void;
    type:number;
}
const EditableCell: React.FC<EditableCellProps> = ({
    editing,
    dataIndex,
    title,
    record,
    index,
    children,
    ...restProps
}) => {
    return (
        <td {...restProps}>
            {editing ? (
                <Form.Item
                    name={dataIndex}
                    style={{ margin: 0 }}
                    rules={[
                        {
                            required: true,
                            message: `请输入${title}!`,
                        },
                    ]}
                >
                    <Input />
                </Form.Item>
            ) : (
                children
            )}
        </td>
    );
};
const EditGoods = (props: IProps) => {
    const [form] = Form.useForm();
    const [data, setData] = useState(originData);
    const [editingKey, setEditingKey] = useState('');
    const [childType, setChildType] = useState('');
    const [pageMeta, setPageMeta] = useState<{ pageNum: number, pageSize: number, pages: number, total: number }>({
        pageNum: 1,
        pageSize: 10,
        pages: 5,
        total: 50,
    });
    const isEditing = (record: Item) => record.key === editingKey;
    const columns = [
        {
            title: '商品名称',
            dataIndex: 'name',
            width: '50%',
            editable: true,
        },
        {
            title: '规格型号',
            dataIndex: 'model',
            width: '30%',
            editable: true,
            render: (text) => {
                return <span style={{ whiteSpace: 'pre-wrap' }}>{text}</span>
            }
        },
        {
            title: '操作',
            dataIndex: 'operation',
            render: (_: any, record: Item) => {
                const editable = isEditing(record);
                return editable ? (
                    <Space>
                        <a href="javascript:;" onClick={() => save(record)}>
                            保存
                        </a>
                        <a onClick={cancel}>取消</a>
                    </Space>
                ) : (
                    <Space>
                        <a onClick={() => edit(record)}>
                            编辑
                        </a>
                        <a onClick={() => remove(record)}>移除</a>
                    </Space>
                );
            },
        },
    ];
    const remove = (record: Item) => {

    }
    const save = (record: Item) => {
        setEditingKey('');
    }
    const edit = (record: Item) => {
        form.setFieldsValue({ ...record });
        setEditingKey(record.key);
    }
    const cancel = () => {
        setEditingKey('');
    }
    const onPageChange = (pageNum: any, pageSize: any) => {
        setPageMeta({
            ...pageMeta,
            pageNum,
            pageSize
        });
        cancel();
    }
    const mergedColumns = columns.map(col => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record: Item) => ({
                record,
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });
    const showchildren = (type: string) => {
        setChildType(type);
    }
    const hideChild = () => {
        setChildType('');
    }
    const getData = () => {
        hideChild();
    }
    const childComponent = useCallback(() => {
        if (childType === 'add') {
            return <GoodsAdd onClose={hideChild} onSuccess={getData} type={props.type}/>
        } else if (childType === 'source') {
            return <ImportGoodsSource onClose={hideChild} onSuccess={getData} type={props.type}/>
        } else if (childType === 'excel') {
            const excelConfig = { downloadurl: '/download/excel', url: '/upload/excel' }
            return <GoodImportExcel onClose={hideChild} onSuccess={getData} data={excelConfig} type={props.type}/>
        } else {
            return null;
        }
    }, [childType])
    return (
        <Drawer
            title="商品管理"
            visible={true}
            onClose={props.onClose}
            width={700}
            footer={
                [<Button onClick={props.onClose}>取消</Button>]
            }
        >
            {childComponent()}
            <Space direction="vertical" style={{ width: '100%' }}>
                <Row justify='end'>
                    <Space align='end'>
                        <Button onClick={() => { showchildren('source') }}>从商品管理导入</Button>
                        <Button onClick={() => { showchildren('excel') }}>Excel上传</Button>
                        <Button onClick={() => { showchildren('add') }}>添加一行</Button>
                    </Space>
                </Row>
                <Form form={form} component={false}>
                    <div style={{ height: 'calc(100vh - 107px )' }}>
                        <AutoTableContainer style={{ flex: 1, }} >
                            <Table
                                components={{
                                    body: {
                                        cell: EditableCell,
                                    },
                                }}
                                bordered
                                dataSource={data}
                                columns={mergedColumns}
                                rowClassName="editable-row"
                                pagination={false}
                            />
                        </AutoTableContainer>
                        <Pagination onChange={onPageChange} showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条,  共有 ${total} 条`} style={{ padding: '16px 0', flex: 'none', background: 'white', textAlign: 'center' }} total={pageMeta.total} pageSize={pageMeta.pageSize} current={pageMeta.pageNum} />
                    </div>
                </Form>
            </Space>
        </Drawer>
    )
}

export default EditGoods;