import React from 'react';
import {
	Icon,
	Modal,
	message,
	Spin,
	Upload,
	Input,
	Button,
	Radio,
	Form
} from 'antd';
import {  splitUrl} from '@/tools.js';

const PicturesWall = React.createClass({
	getInitialState() {
		return {
			previewVisible: false,
			previewImage: '',
			fileList: [],
			tags: []
		};
	},
	handleCancel() {
		this.setState({ previewVisible: false });
	},
	handlePreview(file) {
		this.setState({
			previewImage: file.url || file.thumbUrl,
			previewVisible: true
		});
	},
	handleChange(info) {
		let fileList = info.fileList;
		this.setState({ fileList });
		this.props.fileList(fileList);
    },
	componentWillReceiveProps(nextProps) {
        this.state.fileList = nextProps.pictureUrl;
	},
	render() {
		const { previewVisible, previewImage, fileList } = this.state;
		const uploadButton = (
			<div>
				<Icon type="plus" />
				<div className="ant-upload-text">点击上传</div>
			</div>
		);
		return (
			<div className="clearfix">
				<Upload
					action={globalConfig.context + '/api/admin/banners/uploadPicture'}
					data={{ sign: 'banners'}}
					listType="picture-card"
					fileList={fileList}
					onPreview={this.handlePreview}
					onChange={this.handleChange}
				>
					{fileList.length >= 1 ? null : uploadButton}
				</Upload>
				<Modal maskClosable={false} visible={previewVisible} footer={null} onCancel={this.handleCancel}>
					<img alt="example" style={{ width: '100%' }} src={previewImage} />
				</Modal>
			</div>
		);
	}
});

class BannerForm extends React.Component {
	constructor(props) {
        super(props);
		this.state = {
			loading: false,
            imgUrl: [],
            visible:false
		};
	}
	cancelFun(){
		this.props.closeDesc();
	}
    loadData(id) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context +  '/api/admin/banners/details' ,
            data: {
                id: id
            },
            success: function (data) {
                let thisData = data.data;
                if (!thisData) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                    thisData = {};
                };
                this.setState({
                    id: thisData.id, //品类ID
                    data:thisData,
                    imgUrl: thisData.imgUrl ? splitUrl(thisData.imgUrl, ',', globalConfig.avatarHost + '/upload') : [],
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    }
	
    handleSubmit(e){
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            //url转化
            let thePictureUrl = [];
            if (this.state.imgUrl.length) {
                let picArr = [];
                this.state.imgUrl.map(function (item) {
                    if ( item.response && item.response.data && item.response.data.length ){
                        picArr.push(item.response.data);
                    }
                });
                thePictureUrl = picArr.join(",");
            }else{
                message.warning('请上传图片!');
                return false;
            };
            if (!err) {
                this.setState({
                    loading: true
                });
                $.ajax({
                    method: "post",
					dataType: "json",
					async:true,
                    url: this.props.data.id ? globalConfig.context + '/api/admin/banners/update' : globalConfig.context + '/api/admin/banners/save',
                    data: {
                        id:this.props.data.id,
                        text:values.text,
                        forwardUrl:values.forwardUrl,
                        apiUrl:values.apiUrl,
                        imgUrl:thePictureUrl.length?thePictureUrl:'',
                        deleteSign:false,
                        client:values.client
                    }
                }).done(function (data) {
                    this.setState({
                        loading: false
					});
                    if (!data.error.length) {
                        message.success('操作成功！');
                        this.setState({
                            visible: false
                        });
                        this.props.handOk();
                    } else {
                        message.warning(data.error[0].message);
                    }
                }.bind(this));
            }
        })
    }
    componentWillMount() {
        if (this.props.data&&this.props.data.id) {
            this.loadData(this.props.data.id);
        } else {
			this.state.data = {};
			this.state.imgUrl = [];
        };
    }
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible) {
            this.state.textFileList = [];
            this.state.videoFileList = [];
            if (nextProps.data.id) {
                this.loadData(nextProps.data.id);
            } else {
				this.state.data = {};
				this.state.imgUrl = [];
            };
			this.props.form.resetFields();
        };
    }
	render() {
        const { getFieldDecorator } = this.props.form;
        const FormItem = Form.Item;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 12 },
		};
        let theData = this.state.data||{};
		return (
			<div className="patent-desc">
                <Form layout="horizontal" onSubmit={this.handleSubmit.bind(this)} id="demand-form">
                    <Spin spinning={this.state.loading}>
                        <div className="clearfix">
                            <FormItem  {...formItemLayout} label="轮播图描述">
                                {getFieldDecorator('text', {
                                    rules: [ { required: true, message: '此项为必填项!' } ],
                                    initialValue: theData.text
                                })(<Input placeholder="请输入轮播图名称"/>)}
                            </FormItem>
                        </div>
                        <div className="clearfix">
                            <FormItem {...formItemLayout} label="跳转地址">
                                {getFieldDecorator('forwardUrl', {
                                    initialValue: theData.forwardUrl
                                })(<Input placeholder="请输入跳转地址"/>)}
                            </FormItem>
                        </div>
                        <div className="clearfix">
                            <FormItem  {...formItemLayout} label="api">
                                {getFieldDecorator('apiUrl', {
                                    rules: [ { required: true, message: '此项为必填项!' } ],
                                    initialValue: theData.apiUrl
                                })(<Input placeholder="请输入api"/>)}
                            </FormItem>
                        </div>
                        <div className="clearfix">
                            {/*<FormItem  {...formItemLayout} label="位置">
                                {getFieldDecorator('client', {
                                    rules: [ { required: true, message: '此项为必填项!' } ],
                                    initialValue: theData.client 
                                })(
                                    <Radio.Group>
                                        <Radio value={0}>网站</Radio>
                                        <Radio value={1}>App</Radio>
                                    </Radio.Group>
                                    )
                                }
                            </FormItem>*/}
                        </div>
                        <div className="clearfix">
                            <FormItem labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} label={<span><strong style={{color:"#f00"}}> * </strong>轮播图</span>}>
                                <PicturesWall
                                    fileList={(e)=>{this.setState({imgUrl:e})}}
                                    pictureUrl={this.state.imgUrl}
                                    visible={this.props.visible}
                                />
                            </FormItem>
                        </div>
                        <div className="clearfix">
                            <FormItem wrapperCol={{ span: 12, offset: 6 }}>
                                <Button className="set-submit" type="primary" htmlType="submit">
                                    保存
                                </Button>
                                <Button className="set-submit" type="ghost" onClick={this.cancelFun.bind(this)}>
                                    取消
                                </Button>
                            </FormItem>
                        </div>
                    </Spin>
                </Form>    
			</div>
		);
	}
}

export default Form.create()(BannerForm);
