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

import Layout from '../../components/Layout/Layout';
import MainHeader from '../../components/MainHeader/MainHeader';
import HeaderOperation, {DetailOperations} from '../../components/HeaderOperation/HeaderOperation';
import FooterOperation from  '../../components/FooterOperation/FooterOperation';

import {UUID, NULL, imgProps, formItemLayout, footerFormSubmitLayout, FILE_UPLOAD, handleUpload} from '../../utils';


const TYPE_ENUM = ['请选择','产品ID', 'URL', '图片'];

@connect(state=>({
    user: state.user,
    loading: state.banner.loading,
    item: state.banner.item,
    isEdit: state.banner.isEdit
}))
@Form.create()
export default class Item extends Component {
    static propsType = {
        item: PropTypes.object,
        user: PropTypes.object,
        dispatch: PropTypes.func
    };

    constructor(props, content) {
        super(props, content);
        this.state = {
            weight: 1,
            type: undefined,
            fileList: []
        };
    }

    componentWillMount() {
        this.props.dispatch({
            type: 'CLEAR_BANNER_ITEM'
        });
    }

    componentDidMount() {
        const {params:{id}} = this.props;
        if (id) {
            this.fetchItem(id);
        }
    }

    componentWillReceiveProps(nextProps) {
        const {params:{id}, history} = this.props;
        const {item, isEdit} = nextProps;
        if (!id && item && item.id) {
            history.replace('/banners/' + item.id);
            return;
        }
        if(!this.props.isEdit && isEdit && item){
            this.setState({
                fileList: [{
                    uid: UUID(),
                    status: 'done',
                    url: item.pic,
                    thumbUrl: item.pic + '!t'
                }],
                type: item.type,
                weight: item.weight
            });
        }
    }

    fetchItem(id) {
        this.props.dispatch({
            type: 'FETCH_BANNER',
            data:{id}
        });
    }


    handleSubmit(e) {
        e.preventDefault();

        const {form, dispatch, params:{id}} = this.props;
        const data = form.getFieldsValue();
        data.weight = this.state.weight;
        data.pic = this.state.fileList[0] ? this.state.fileList[0].url : undefined;
        data.type = this.state.type;
        data.status = data.status ? 1 : 0;
        if (id) {
            data.id = id;
        }
        console.log(data, id, id ?  'EDIT_BANNER_SUBMIT':'CREATE_BANNER' );
        dispatch({
            type: id ? 'EDIT_BANNER_SUBMIT' : 'CREATE_BANNER',
            data
        });
    }

    render = ()=> {

        let {item, loading, form:{getFieldProps}, location:{query}, isEdit, params, dispatch, user} = this.props;

        const isCreate = !params.id;

        if (!params.id) {
            item = {};
            isEdit = true;
        }

        const breadcrumb = isCreate ? ['Banner管理', '新增Banner'] : ['Banner管理', 'Banner详情'];

        const title = isCreate ? '添加Banner' : ('Banner详情' + (isEdit ? ' - 编辑' : ''));

        const operation = (
            <HeaderOperation history={this.props.history}
                             buttons={DetailOperations('BANNER', params.id, isEdit, dispatch)}/>
        );

        const header = (
            <MainHeader breadcrumb={breadcrumb} title={title}
                        operation={operation}
            />
        );


        const redirectNamePlaceholder = {0: '无需填写', 1: '请输入一个产品ID', 2: '请输入消息跳转指定的URL地址'};



        return (
            <Layout header={header}>
                <Spin spinning={loading}>
                    {
                        item &&
                        <Form className="main-form" horizontal onSubmit={this.handleSubmit.bind(this)}>
                            <Form.Item label="Banner标题" {...formItemLayout}>
                                {
                                    isEdit ?
                                        <Input placeholder="Banner标题"
                                               {...getFieldProps('title', {
                                                   initialValue:item.title
                                               })}  />
                                        :
                                        item.title || NULL
                                }

                            </Form.Item>
                            <Form.Item label="Banner图片" {...formItemLayout}>
                                {
                                    isEdit ?
                                        <Upload {...FILE_UPLOAD} listType="picture-card"
                                                multiple={false}
                                                headers={{
                                                    authorization: user && user.token,
                                                }}
                                                onChange={info=>this.setState({fileList: handleUpload(info, 1)})}
                                                onPreview={file => {
                                                    this.setState({
                                                        priviewImage: file.url,
                                                        priviewVisible: true
                                                    });
                                                }}
                                                fileList={this.state.fileList}>
                                            <Icon type="upload"/>
                                            <div className="ant-upload-text">上传Banner</div>
                                        </Upload>
                                        :
                                        <img {...imgProps(this, item.pic)} style={{display:'block'}} />
                                }
                                <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.Item>
                            <Form.Item label="Banner跳转" {...formItemLayout}>
                                {
                                    isEdit ?
                                        <Row>
                                            <Col span="6">
                                                <Select placeholder="请选择"
                                                        value={this.state.type}
                                                        onChange={value=>this.setState({type: value})}>
                                                    {
                                                        TYPE_ENUM.map((type, index)=>
                                                            <Select.Option key={'type-'+index} value={index}>{type}</Select.Option>
                                                        )
                                                    }
                                                </Select>
                                            </Col>
                                            <Col span="18" style={{paddingLeft: '.5em'}}>
                                                <Input placeholder={redirectNamePlaceholder[this.state.redirectName]}
                                                       {...getFieldProps('redirect', {
                                                           initialValue: item.redirect
                                                       })} />
                                            </Col>
                                        </Row>
                                        :
                                        TYPE_ENUM[item.type]+': '+ item.redirect
                                }
                            </Form.Item>
                            <Form.Item label="权重配置" {...formItemLayout}>
                                {
                                    isEdit ?
                                        <Slider min={1} max={100} value={this.state.weight}
                                                onChange={value=>this.setState({weight: value})}/>
                                        :
                                        item.weight
                                }
                            </Form.Item>
                            <Form.Item label="是否展示" {...formItemLayout}>
                                <Switch checkedChildren="是" unCheckedChildren="关"
                                        {...getFieldProps('status', {
                                            initialValue: !!item.status,
                                            valuePropName: 'checked'
                                        })}
                                        disabled={!isEdit}

                                />
                            </Form.Item>
                            <FooterOperation {...this.props} isEdit={isEdit} command="BANNER"
                                             hasCancel={!isCreate}/>

                        </Form>
                    }
                </Spin>
            </Layout>
        );
    }
}
