import React, { useEffect, useState } from 'react';
import { FormComponentProps } from 'antd/lib/form';
import Form from 'antd/es/form';
import {
    Avatar,
    Button,
    Card,
    Drawer,
    List,
    Input
} from 'antd';
import { DeviceProduct } from '../data';
import apis from '@/services';
import cardStyles from '@/pages/device/product/index.less';
import productImg from '@/pages/device/product/img/product.png';
import AutoHide from '@/pages/device/location/info/autoHide';
import SearchForm from '@/components/SearchForm';
import encodeQueryParam from '@/utils/encodeParam';

const { Search } = Input


interface Props extends FormComponentProps {
    data: Partial<DeviceProduct>;
    close: Function;
    save: (data: Partial<DeviceProduct>) => void;
}

interface State {
    listLoading: boolean;
    result: any;
    searchParam: any;
    selectItem: any;
}

const Save: React.FC<Props> = props => {
    const initState: State = {
        listLoading: true,
        result: [],
        searchParam: {
            terms: { name$LIKE: '' },
            pageSize: 8,
            sorts: { field: 'id', order: 'desc' },
        },
        selectItem: {}
    };


    const [result, setResult] = useState<any[]>(initState.result);
    const [searchParam, setSearchParam] = useState(initState.searchParam);
    const [listLoading, setListLoading] = useState(initState.listLoading);
    const [selectItem, setSelectItem] = useState(initState.selectItem);

    useEffect(() => {
        handleSearch(searchParam)
    }, []);

    const handleSearch = (params?: any) => {
        setSearchParam(params);
        setListLoading(true)
        apis.deviceProdcutCommon.list(encodeQueryParam(params)).then(
            e => {
                if (e.status === 200) {
                    setResult(e.result);
                }
                setListLoading(false)
            }
        )
    };

    const saveData = () => {
        props.save({
            id: selectItem.id
        });
    };

    const onChange = (page: number, pageSize: number) => {
        handleSearch({
            pageIndex: page - 1,
            pageSize,
            terms: searchParam.terms,
            sorts: searchParam.sorts,
        });
    };

    const onShowSizeChange = (current: number, size: number) => {
        handleSearch({
            pageIndex: current - 1,
            pageSize: size,
            terms: searchParam.terms,
            sorts: searchParam.sorts,
        });
    };

    const changeValue = (value: any) => {
        handleSearch({
            pageSize: searchParam.pageSize,
            terms: { name$LIKE: value },
            sorts: searchParam.sorts
        })
    };

    const cardInfoTitle = {
        fontSize: 14,
        color: 'rgba(0, 0, 0, 0.85)',
    };
    return (
        <Drawer
            visible
            title={`${props.data?.id ? '编辑' : '新增'}产品`}
            width={700}
            onClose={() => props.close()}
            closable
        >
            <div className={cardStyles.filterCardList} style={{
                height: 'calc(100vh - 150px)',
                overflow: 'auto'
            }}>
                <div style={{
                    position: 'absolute',
                    top: '12px',
                    right: '70px'
                }}>
                    <Search
                        placeholder="请输入产品名称"
                        onSearch={value => changeValue(value)}
                        style={{ width: 200 }}
                    />
                </div>
                {result.data && (
                    <List<any>
                        rowKey="id"
                        loading={listLoading}
                        grid={{ gutter: 24, xl: 2, lg: 2, md: 2, sm: 2, xs: 1 }}
                        dataSource={(result || {}).data}
                        pagination={{
                            current: result?.pageIndex + 1,
                            total: result?.total,
                            pageSize: result?.pageSize,
                            showQuickJumper: true,
                            showSizeChanger: true,
                            hideOnSinglePage: true,
                            pageSizeOptions: ['8', '16', '40', '80'],
                            style: { marginTop: -20 },
                            showTotal: (total: number) =>
                                `共 ${total} 条记录 第  ${result.pageIndex + 1}/${Math.ceil(
                                    result.total / result.pageSize,
                                )}页`,
                            onChange,
                            onShowSizeChange,
                        }}
                        renderItem={item => {
                            if (item && item.id) {
                                return (
                                    <List.Item key={item.id} onClick={() => {
                                        setSelectItem(item)
                                    }}>
                                        <Card
                                            hoverable
                                            bodyStyle={{ paddingBottom: 20 }}
                                            style={{ border: selectItem.id == item.id ? '1px solid #1890FF' : '1px solid #e8e8e8' }}
                                        >
                                            <Card.Meta
                                                avatar={<Avatar size={40} src={item.photoUrl || productImg} />}
                                                title={
                                                    <AutoHide title={item.name} style={{ width: '95%', fontWeight: 600 }} />
                                                }
                                                description={<AutoHide title={item.id} style={{ width: '95%' }} />}
                                            />
                                            <div className={cardStyles.cardItemContent}>
                                                <div className={cardStyles.cardInfo}>
                                                    <div style={{ width: '100%' }}>
                                                        <p style={cardInfoTitle}>产品类型</p>
                                                        <AutoHide
                                                            title={item.deviceType?.text}
                                                            style={{ fontSize: 14, fontWeight: 600, width: '95%' }}
                                                        />
                                                    </div>
                                                </div>
                                            </div>
                                        </Card>
                                    </List.Item>
                                );
                            }
                            return '';
                        }}
                    />
                )}
            </div>

            <div
                style={{
                    position: 'absolute',
                    right: 0,
                    bottom: 0,
                    width: '100%',
                    borderTop: '1px solid #e9e9e9',
                    padding: '10px 16px',
                    background: '#fff',
                    textAlign: 'right',
                }}
            >
                <Button
                    onClick={() => {
                        props.close();
                    }}
                    style={{ marginRight: 8 }}
                >
                    关闭
                </Button>
                <Button
                    onClick={() => {
                        saveData();
                    }}
                    type="primary"
                >
                    保存
                </Button>
            </div>
        </Drawer>
    );
};

export default Form.create<Props>()(Save);
