import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import {Table, Icon, message} from 'antd';
import {Link} from 'react-router';
import {serialize, formatDateTime, remittanceAuditStatusToString} from '../../utils';
import Layout from '../../components/Layout/Layout';
import MainHeader from '../../components/MainHeader/MainHeader';
import HeaderOperation from '../../components/HeaderOperation/HeaderOperation';


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

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

    }

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

    fetchList(data) {
        this.props.dispatch({
            type: 'FETCH_REMITTANCE_LIST',
            data
        });
    }

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

    render() {
        const {total, items, loading, history:{replace}, location:{pathname, query}} = this.props;
        const {selectedRowKeys} = this.state;

        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',
            }, {
                key: 'download',
                title: '打包下载照片',
                icon: 'cloud-download-o',
                children: '下载照片',
                onClick: (e)=> {
                    if (selectedRowKeys.length) {
                        let name = selectedRowKeys[0];
                        if (selectedRowKeys.length > 1) {
                            name += '--' + selectedRowKeys[selectedRowKeys.length - 1];
                        }
                        const iframe = document.createElement('iframe');
                        const ids = selectedRowKeys.join(',');
                        iframe.src = '/zip/' + name + '.zip?id=' + ids;
                        document.body.appendChild(iframe);
                        setTimeout(()=> {
                            document.body.removeChild(iframe);
                        }, 10000);
                    }
                }
            }]}/>
        );


        const header = (<MainHeader breadcrumb={['审核管理', '报单审核']}
                                    title="报单审核列表"
                                    operation={operation}
        />);

        const columns = [
            {
                title: 'ID',
                dataIndex: 'id',
                key: 'id',
                width: 70
            }, {
                title: '产品',
                dataIndex: 'itemShortTitle',
                key: 'itemShortTitle',
                width: 200,
                render: (shortTitle, record)=>(<span title={shortTitle}>{(shortTitle + '').substring(0, 20)}</span>)
            }, {
                title: '投资人',
                dataIndex: 'buyerName',
                key: 'buyerName',
                width: 100,
                className: 'tac',
            }, {
                title: '预约额度',
                dataIndex: 'reservationAmount',
                key: 'reservationAmount',
                width: 80,
                className: 'tac',
            }, {
                title: '报单时间',
                dataIndex: 'submitReceiptTime',
                key: 'submitReceiptTime',
                width: 150,
                className: 'tac',
                render: (submitReceiptTime, record)=>(
                    <span>
                {submitReceiptTime && formatDateTime(submitReceiptTime)}
            </span>
                )
            }, {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                width: 120,
                className: 'tac',
                render: (status, record)=>(<span data-status={status}>{remittanceAuditStatusToString(status)}</span>)
            }, {
                title: '操作',
                key: 'operation',
                width: 60,
                className: 'tac',
                render: (text, record)=>(
                    <div>
                        {
                            record.status == 1 &&
                            <Link to={'/remittance/audits/' + record.id} onClick={e=>e.stopPropagation()}>审核</Link>
                        }
                        {
                            record.status == 9 &&
                            <a href="javascript:void('下载');" onClick={e=> {
                                e.stopPropagation();
                                const iframe = document.createElement('iframe');
                                iframe.src = '/zip/' + record.id + '.zip?id=' + record.id;
                                document.body.appendChild(iframe);
                                setTimeout(()=> {
                                    document.body.removeChild(iframe);
                                }, 10000);
                            }}>下载</a>
                        }
                    </div>
                )
            }
        ];


        const rowSelection = {
            selectedRowKeys,
            onChange: (selectedRowKeys)=> {
                this.setState({selectedRowKeys})
            },
            getCheckboxProps: record=>({
                disabled: record.status !== 9
            })
        };


        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)}
                       rowSelection={rowSelection}
                       rowKey="id"
                />
            </Layout>
        );
    }
}



