import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import {Table, Icon, Row, Col, Button, Form, Input, Cascader, Select} from 'antd';
import {Link} from 'react-router';
import {serialize, formatDateTime, tradeStatusToString} from '../../utils';
import Layout from '../../components/Layout/Layout';
import MainHeader from '../../components/MainHeader/MainHeader';
import HeaderOperation from '../../components/HeaderOperation/HeaderOperation';

const columns = [
    {
        title: '订单ID',
        dataIndex: 'id',
        key: 'id',
        width: 70,
        // fixed:'left'
    }, {
        title: '产品',
        dataIndex: 'shortTitle',
        key: 'shortTitle',
        width:200,
        render: (shortTitle, record)=>(<span title={shortTitle}>{(shortTitle + '').substring(0, 15)}</span>)
    }, {
        title: '预约时间',
        dataIndex: 'reservationTime',
        key: 'reservationTime',
        width: 150,
        className: 'tac',
        render: (reservationTime, record)=>(
            <span>
                {reservationTime && formatDateTime(reservationTime)}
            </span>
        )
    }, {
        title: '投资人',
        dataIndex: 'buyerName',
        key: 'buyerName',
        width: 80,
        className: 'tac',
    }, {
        title: '预约额度',
        dataIndex: 'reservationAmount',
        key: 'reservationAmount',
        width: 100,
        className: 'tac',
    }, {
        title: '实际打款',
        dataIndex: 'remittanceAmount',
        key: 'remittanceAmount',
        width: 100,
        className: 'tac',
    }, {
        title: '进度',
        dataIndex: 'status',
        key: 'status',
        width: 160,
        className: 'tac',
        render: (status, record)=>(<span data-status={status}>{tradeStatusToString(status)}</span>)
    }, {
        title: '操作',
        key: 'operation',
        width: 140,
        // fixed:'right',
        className: 'tac',
        render: (text, record)=>(
            <span>
                <Link to={'/trades/contract/'+ record.id+'?title='+ record.shortTitle} onClick={e=>e.stopPropagation()}>合同</Link>
                {
                    (record.status == 11 || record.status == 21) && (! record.commissionId) &&
                    <span>
                        <span className="ant-divider"></span>
                        <Link to={'/trades/commission/'+ record.id} onClick={e=>e.stopPropagation()}>佣金</Link>
                    </span>
                }
            </span>
        )
    }
];

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

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

    componentWillMount() {
        this.fetchList(this.props.location.query);
    };

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

    handleRowClick({id}) {
        this.props.history.push('/trades/' + 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,
            items,
            loading,
            history:{replace},
            form:{getFieldProps},
            location:{pathname, query}
        } = this.props;

        const pagination = {
            total: total,
            pageSize: parseInt(query.s, 10) || 30,
            current: parseInt(query.p, 10) || 1,
            showSizeChanger: true,
            showTotal: total => `共 ${total} 条`,
            pageSizeOptions:['10', '30', '50', '100'],
            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 = (
            <HeaderOperation history={this.props.history} buttons={[{
                key:'filter',
            }]}/>
        );

        const header = (
            <MainHeader breadcrumb={['订单管理', '订单列表']}
                        operation={operation}
                        title="订单列表">
                {
                    this.state.filterVisible &&
                    <Form className="filterForm" inline onSubmit={this.handleFilterSubmit.bind(this)}>
                        <Form.Item label="ID">
                            <Input placeholder="请输入搜索ID" {...searchStyle} {...getFieldProps('id')}/>
                        </Form.Item>
                        <Form.Item label="类目">
                            {
                                cates &&
                                <Cascader options={cates} placeholder="请选产品类目" {...searchStyle}
                                    {...getFieldProps('categoryId')}
                                />
                            }
                        </Form.Item>
                        <Form.Item label="标题">
                            <Input placeholder="请输入搜索标题" {...searchStyle} {...getFieldProps('title')}/>
                        </Form.Item>
                        <Form.Item label="状态">
                            <Select placeholder="请选择状态"  {...searchStyle} {...getFieldProps('status')}>
                                <Select.Option key="status-option-default"
                                               value={null}>请选择</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>
        );
    }
}



