import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import {Table, Icon, Row, Col, Button, Form, Input, Cascader, Select} from 'antd';
import {
    serialize,
    formatDateTime,
    productStatusToString,
    productEnableCreateTrade,
    UUID,
    formItemLayout,
    smallFormItemLayout,
    footerFormSubmitLayout,
    handleUpload,
    filterFormItemLayout,
    PRODUCT_STATUS,
    filterFormItemStyle
} from '../../utils';
import {Link} from 'react-router';

import Layout from '../../components/Layout/Layout';
import MainHeader from '../../components/MainHeader/MainHeader';

const ProductStatus = Object.keys(PRODUCT_STATUS).filter(key=>key != -9);


const columns = [
    {
        title: 'ID',
        dataIndex: 'id',
        key: 'id',
        width: 60
    }, {
        title: '类目',
        dataIndex: 'cateId',
        key: 'cateId',
        width: 80,
        className: 'tac',
        render: (cateId, record)=>(<span data-cate-id={cateId}>{record.cateName}</span>)
    }, {
        title: '标题',
        dataIndex: 'shortTitle',
        key: 'shortTitle',
        render: (shortTitle, record)=>(<span title={shortTitle}>{(shortTitle + '').substring(0, 15)}</span>)
    }, {
        title: '募集比率',
        dataIndex: 'rate',
        key: 'rate',
        width: 120,
        className: 'tac',
    }, {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 80,
        className: 'tac',
        render: (status, record)=>(<span data-status={status}>{productStatusToString(status)}</span>)
    }, {
        title: '创建时间',
        dataIndex: 'dateCreated',
        key: 'dateCreated',
        width: 150,
        className: 'tac',
        render: (dateCreated, record)=>(
            <span>
                {dateCreated && formatDateTime(dateCreated)}
            </span>
        )
    }, {
        title: '操作',
        key: 'operation',
        width: 120,
        className: 'tac',
        render: (text, product)=>(
            <span>
                <Link to={'/announcement?itemId='+product.id+'&title='+product.shortTitle}
                      onClick={e=>e.stopPropagation()}>公告</Link>
                {
                    productEnableCreateTrade(product.status) &&
                    <span>
                        <span className="ant-divider"></span>
                        <Link to={'/trades/create?itemId='+product.id+'&title='+product.shortTitle}
                              onClick={e=>e.stopPropagation()}>报单</Link>
                    </span>
                }

            </span>
        )
    }
];

@connect(state=>({
    cates: state.product.cates,
    items: state.product.items,
    loading: state.product.loading,
    total: state.product.total
}))
@Form.create()
export default class List extends Component {

    constructor(props, context) {
        super(props, context);
        this.state = {
            filterVisible: false
        }
    }

    componentDidMount() {
        this.fetchList(this.props.location.query);
        const {cates} = this.props;
        if (!cates || !cates.length) {
            this.fetchCates();
        }
    };

    fetchList(query) {
        this.props.dispatch({
            type: 'FETCH_PRODUCT_LIST',
            query
        });
    };

    fetchCates() {
        this.props.dispatch({
            type: 'FETCH_PRODUCT_CATES'
        });
    };

    handleRowClick({id}) {
        this.props.history.push('/products/' + id);
    }

    handleFilterVisible() {
        this.setState({
            filterVisible: !this.state.filterVisible
        });

    }

    handleFilterSubmit(e) {
        e.preventDefault();
        const formData = this.props.form.getFieldsValue();
        if (formData.categoryId && formData.categoryId[1]) {
            formData.categoryId = formData.categoryId[1];
        }
        const searchQuery = {...this.props.location.query, ...formData};
        console.log(searchQuery);
        this.props.history.replace(this.props.location.pathname + '?' + serialize(searchQuery));
        this.fetchList(searchQuery);
    }

    handleResetFilterForm(e) {
        e.preventDefault();
        this.props.form.setFieldsValue({
            id: undefined,
            status: undefined,
            categoryId: undefined,
            title: undefined
        });
    }

    render() {

        const {
            total, cates, items, loading,
            form:{getFieldProps},
            history:{replace},
            location:{pathname, query}
        } = this.props;


        const pagination = {
            total: total,
            pageSize: parseInt(query.s, 10) || 10,
            current: parseInt(query.p, 10) || 1,
            showSizeChanger: true,
            onShowSizeChange: (current, pageSize)=> {
                console.log('Current: ', current, '; PageSize: ', pageSize);
                query.p = current;
                query.s = pageSize;
                replace(pathname + '?' + serialize(query));
                this.fetchList(query);
            },
            onChange: (current)=> {
                console.log('Current: ', current);
                query.p = current;
                replace(pathname + '?' + serialize(query));
                this.fetchList(query);
            }
        };

        const operation = (
            <div style={{textAlign:'right'}}>
                <Button.Group>
                    <Button type="ghost" onClick={this.handleFilterVisible.bind(this)}>
                        <Icon type="filter"/>
                    </Button>
                </Button.Group>
            </div>
        );



        const header = (
            <MainHeader breadcrumb={['产品管理', '产品列表']}
                        title="产品列表"
                        operation={operation}
            >
                {
                    this.state.filterVisible &&
                    <Form className="filterForm" inline onSubmit={this.handleFilterSubmit.bind(this)}>
                        <Form.Item label="ID">
                            <Input placeholder="请输入搜索ID" {...filterFormItemStyle} {...getFieldProps('id')}/>
                        </Form.Item>
                        <Form.Item label="类目">
                            {
                                cates &&
                                <Cascader options={cates} placeholder="请选产品类目" {...filterFormItemStyle}
                                    {...getFieldProps('categoryId')}
                                />
                            }
                        </Form.Item>
                        <Form.Item label="标题">
                            <Input placeholder="请输入搜索标题" {...filterFormItemStyle} {...getFieldProps('title')}/>
                        </Form.Item>
                        <Form.Item label="状态">
                            <Select placeholder="请选择状态"  {...filterFormItemStyle} {...getFieldProps('status')}>
                                <Select.Option key="status-option-default"
                                               value={null}>请选择</Select.Option>
                                {
                                    ProductStatus.map((status, index)=>
                                        <Select.Option key={status} data-value={status}
                                                       value={status}>{PRODUCT_STATUS[status]}</Select.Option>
                                    )
                                }
                            </Select>
                        </Form.Item>
                        <Form.Item>
                            <Button.Group size="default">
                                <Button type="primary" size="default" htmlType="submit" loading={loading}><Icon
                                    type="search"/>筛选</Button>
                                <Button type="ghost" size="default" htmlType="reset"
                                        onClick={this.handleResetFilterForm.bind(this)}><Icon
                                    type="cross-circle-o"/>清空</Button>
                            </Button.Group>
                        </Form.Item>
                    </Form>
                }
            </MainHeader>
        );

        return (
            <Layout header={header}>
                <Table className="list-table" columns={columns}
                       dataSource={Array.isArray(items)?items:[]}
                       loading={loading}
                       pagination={pagination}
                       scroll={{ y: window.innerHeight-(this.state.filterVisible? 203 :150) }}
                       onRowClick={this.handleRowClick.bind(this)}
                />
            </Layout>
        );
    }
}



