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.audits,
    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(query) {
        this.props.dispatch({
            type: 'FETCH_REMITTANCE_LIST',
            query
        });
    }

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

    // packImages(id) {
    //     const {dispatch} = this.props;
    //     (new Promise((resolve)=> {
    //         require.ensure(['socket.io-client'], function (require) {
    //
    //             const io = require('socket.io-client');
    //
    //             const socket = io();
    //
    //             socket.on('zip-start', function () {
    //                 message.info('开始打包');
    //             });
    //
    //             socket.on('zip-success', function (data) {
    //                 console.log('zip-success', data);
    //                 dispatch({
    //                     type: 'ZIP_SUCCESS',
    //                     data
    //                 });
    //             });
    //
    //             socket.on('zip-failed', function (err) {
    //                 console.error('zip-failed', err);
    //                 message.error(err && err.message || '未知错误!');
    //
    //             });
    //
    //             socket.on('zip-completed', function (data) {
    //                 console.log('zip-completed', data);
    //                 socket.close();
    //                 if (data && data.length) {
    //                     message.success('打包完成');
    //                 }
    //                 resolve();
    //             });
    //
    //             socket.emit('zip', id);
    //
    //         }, 'socket.io');
    //     })).then(()=> {
    //
    //     });
    // }

    render() {

        console.log('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 + '?id=' + ids;
                        document.body.appendChild(iframe);
                        setTimeout(()=> {
                            document.body.removeChild(iframe);
                        }, 1000);
                    }
                }
            }]}/>
        );


        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 + '?id=' + record.id;
                                document.body.appendChild(iframe);
                                setTimeout(()=> {
                                    document.body.removeChild(iframe);
                                }, 1000);
                            }}>下载</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>
        );
    }
}



