import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import {
    Form,
    Input,
    Button,
    Checkbox,
    message,
    Tabs,
    DatePicker,
    Upload,
    Icon,
    Modal,
    Breadcrumb,
    Row,
    Col,
    Spin
} from 'antd';

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

import {
    formatDateTime,
    formItemLayout,
    smallFormItemLayout,
    footerFormSubmitLayout,
    handleUpload
} from '../../utils';

@connect(state=>({
    loading: state.trade.loading,
    user: state.user,
    item: state.trade.item
}))
@Form.create()
export default class AddItem extends Component {

    constructor() {
        super(...arguments);
        this.state = {
            priviewVisible: false,
            priviewImage: '',
            identityCardList: [],
            bankCardList: [],
            receiptList: [],
            signaturePages: []

        };
    }

    componentDidMount(){
        const {item} = this.props;
        if (item && item.id) {
            this.props.dispatch({
                type: 'INIT_TRADE'
            });
        }
    }

    componentWillReceiveProps(nextProps) {
        const {item} = nextProps;
        if (item && item.id) {
            this.props.history.push('/trades/' + item.id);
            this.props.dispatch({
                type: 'INIT_TRADE'
            });
        }
    }


    handleSubmit(e) {
        e.preventDefault();
        const data = this.props.form.getFieldsValue();
        data.itemId = this.props.location.query.itemId;

        if(!data.itemId){
            message.warning('未知的产品ID');
            return;
        }

        if (data.remittance.remittanceTime) {
            data.remittance.remittanceTime = formatDateTime(data.remittance.remittanceTime);
        }

        const {identityCardList, bankCardList, receiptList, signaturePages} = this.state;

        if(Array.isArray(identityCardList) && identityCardList.length){
            data.remittance.identityCardFront = identityCardList[0] && identityCardList[0].url;
            data.remittance.identityCardBack = identityCardList[1] && identityCardList[1].url;
        }
        if(Array.isArray(bankCardList) && bankCardList.length){
            data.remittance.bankCardPic = bankCardList[0] && bankCardList[0].url;
        }
        if(Array.isArray(receiptList) && receiptList.length){
            data.remittance.remittanceReceipt = receiptList[0] && receiptList[0].url;
        }
        if(Array.isArray(signaturePages) && signaturePages.length){
            let tmp = [];
            signaturePages.forEach(file=>{
                tmp.push(file.url);
            })
            data.remittance.signaturePages = JSON.stringify(tmp);
        }

        console.log(data);

        this.props.dispatch({
            type: 'CREATE_TRADE_ITEM',
            data,
            push: this.props.history.push,
        });
    }

    render() {

        const {loading, form:{getFieldProps}, location:{query}, user} = this.props;

        const header = (<MainHeader breadcrumb={['订单管理', '创建订单']}
                                    title={(query.title ? query.title + ' - ' : '') + '报单'}/>);

        return (
            <Layout header={header}>
                <Spin spinning={loading}>
                    <Form className="main-form" horizontal onSubmit={this.handleSubmit.bind(this)}>
                        <Form.Item {...smallFormItemLayout} label="理财师手机号" help="请准确核对理财师手机号码">
                            <Input {...getFieldProps('user.mobile')} />
                        </Form.Item>
                        <Form.Item {...smallFormItemLayout} label="投资人姓名" help="请如实填写投资人姓名">
                            <Input {...getFieldProps('buyer.name')} />
                        </Form.Item>
                        <Form.Item {...smallFormItemLayout} label="投资人身份证号码" help="请如实填写投资人18位身份证号码">
                            <Input placeholder="" {...getFieldProps('buyer.identityCardNumber')} />
                        </Form.Item>
                        <Form.Item {...formItemLayout} label="投资人身份证照片" help="投资人身份证正反面照片">
                            <Upload action="/api/fileUpload/upload" listType="picture-card"
                                    multiple={true}
                                    headers={{
                                            authorization: user && user.token,
                                        }}
                                    onChange={info=>this.setState({identityCardList: handleUpload(info, 2)})}
                                    onPreview={file => {
                                        this.setState({
                                            priviewImage: file.url,
                                            priviewVisible: true
                                        });
                                    }}
                                    fileList={this.state.identityCardList}>
                                <Icon type="upload"/>
                                <div className="ant-upload-text">上传照片</div>
                            </Upload>
                        </Form.Item>
                        <Form.Item {...smallFormItemLayout} label="投资人实际打款金额" help="请如实填写投资人实际打款金额">
                            <Input placeholder="520万" {...getFieldProps('remittance.remittanceAmount')} />
                        </Form.Item>
                        <Form.Item {...formItemLayout} label="投资人实际打款时间">
                            <DatePicker showTime
                                        format="yyyy-MM-dd HH:mm:ss"
                                        placeholder="请选择时间"
                                {...getFieldProps('remittance.remittanceTime')}
                            />
                        </Form.Item>
                        <Form.Item {...smallFormItemLayout} label="投资人银行卡开户行">
                            <Input placeholder="中国工商银行杭州文一西路支行" {...getFieldProps('remittance.bankBranch')} />
                        </Form.Item>
                        <Form.Item {...formItemLayout} label="投资人银行卡照片">
                            <Upload action="/api/fileUpload/upload" listType="picture-card"
                                    headers={{
                                            authorization: user && user.token,
                                        }}
                                    onChange={info=>this.setState({bankCardList: handleUpload(info, 1)})}
                                    onPreview={file => {
                                        this.setState({
                                            priviewImage: file.url,
                                            priviewVisible: true
                                        });
                                    }}
                                    fileList={this.state.bankCardList}>
                                <Icon type="upload"/>
                                <div className="ant-upload-text">上传照片</div>
                            </Upload>
                        </Form.Item>
                        <Form.Item {...formItemLayout} label="投资人打款凭条照片">
                            <Upload action="/api/fileUpload/upload" listType="picture-card"
                                    multiple={true}
                                    headers={{
                                            authorization: user && user.token,
                                        }}
                                    onChange={info=>this.setState({receiptList: handleUpload(info)})}
                                    onPreview={file => {
                                        this.setState({
                                            priviewImage: file.url,
                                            priviewVisible: true
                                        });
                                    }}
                                    fileList={this.state.receiptList}>
                                <Icon type="upload"/>
                                <div className="ant-upload-text">上传照片</div>
                            </Upload>
                        </Form.Item>
                        <Form.Item {...formItemLayout} className="clearfix" label="投资人合同签字页照片">
                            <Upload action="/api/fileUpload/upload" listType="picture-card"
                                    multiple={true}
                                    headers={{
                                            authorization: user && user.token,
                                        }}
                                    onChange={info=>this.setState({signaturePages: handleUpload(info)})}
                                    onPreview={file => {
                                        this.setState({
                                            priviewImage: file.url,
                                            priviewVisible: true
                                        });
                                    }}
                                    fileList={this.state.signaturePages}>
                                <Icon type="upload"/>
                                <div className="ant-upload-text">上传照片</div>
                            </Upload>
                        </Form.Item>
                        <Form.Item {...footerFormSubmitLayout} style={{marginTop:30}}>
                            <Button type="primary" htmlType="submit" loading={loading}><Icon type="save"/>创建订单</Button>
                            <Button onClick={e=>{e.preventDefault(); this.props.history.goBack();}}
                                    style={{marginLeft:'1em'}}>
                                <Icon type="rollback"/>返回
                            </Button>
                        </Form.Item>
                        <Modal footer={null}
                               width="100vw"
                               visible={this.state.priviewVisible}
                               className="img-priview-dialog"
                               style={{height:'100vh', background:'transparent'}}
                               onCancel={()=>this.setState({ priviewVisible: false })}>
                            <img src={this.state.priviewImage} style={{maxWidth:'100%'}}/>
                        </Modal>
                    </Form>
                </Spin>
            </Layout>
        );
    }
}
