import React,{Component} from 'react';
import {Form, Input, Modal, Spin, Radio, Button, Icon, Upload, message, Checkbox} from "antd";
import TextArea from "antd/es/input/TextArea";
import {
    splitUrl,
    beforeUploadFile,
} from "@/tools.js";
import $ from "jquery/src/ajax";
import {companyList, getCompanyValueArray} from "../../../../common/configure";

const FormItem = Form.Item;
const RadioGroup = Radio.Group;

// 上传文件
const PicturesWall = React.createClass({
    getInitialState() {
        return {
            previewVisible: false,
            previewImage: "",
            fileList: this.props.pictureUrl
        };
    },
    getDefaultProps() {
        return {
            changeClick: this.modifyChange
        };
    },
    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 style={{ display: "inline-block" }}>
                <Upload
                    beforeUpload={beforeUploadFile}
                    action={globalConfig.context + "/api/admin/activity/upload"}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange}
                >
                    {fileList && fileList.length >= 1 ? null : uploadButton}
                </Upload>
                <Modal
                    maskClosable={false}
                    visible={previewVisible}
                    footer={null}
                    onCancel={e => {
                        this.setState({ previewVisible: false });
                    }}
                >
                    <img alt="" style={{ width: "100%" }} src={previewImage} />
                </Modal>
            </div>
        );
    }
});

class ActivityOperation extends Component{
    constructor(props) {
        super(props);
        this.state={
            loading: false,
            pictureUrl: [],
            details: {},
            locations: [],
        }
        this.submit = this.submit.bind(this);
        this.getOrgCodeUrl = this.getOrgCodeUrl.bind(this);
    }

    submit(e){
        e.preventDefault();
        let _this = this;
        this.props.form.validateFields((err, values) => {
            if(values.title.length > 6){
                message.warning('标题最多六个字');
                return;
            }
            if(this.state.locations.length === 0){
                message.warning('请选择城市');
                return;
            }
            if (!err) {
                this.setState({
                    loading: true
                })
                values.pictureUrl = values.pictureUrl ? values.pictureUrl[0].response.data : undefined;
                let url = this.props.id ? "/api/admin/activity/update" : "/api/admin/activity/add";
                if(this.props.id){
                    values.id = this.props.id;
                }
                values.locations = this.state.locations.join(',')
                $.ajax({
                    method: "post",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + url,
                    data: values,
                    success: function(data) {
                        if (data.error && data.error.length) {
                            message.warning(data.error[0].message);
                        } else {
                            message.success('添加成功')
                            _this.props.onCancel();
                        }
                    }.bind(this)
                }).always(
                    function() {
                        this.setState({
                            loading: false
                        });
                    }.bind(this)
                );
            }
        });
    }

    getOrgCodeUrl(e) {
        this.setState({ pictureUrl: e });
        this.props.form.setFieldsValue({
            pictureUrl: e
        })
    }

    getSelect(){
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/activity/select",
            data: {
                id:this.props.id,
            },
            success: function(data) {
                if (data.error.length) {
                    message.warning(data.error[0].message);
                } else {
                    this.props.form.setFieldsValue({
                        title:data.data.title,
                        publisher:data.data.publisher,
                        sort:data.data.sort,
                        releaseStatus:data.data.releaseStatus,
                        content:data.data.content,
                        pictureUrl:data.data.pictureUrl
                            ? splitUrl(
                                data.data.pictureUrl,
                                ",",
                                globalConfig.avatarUploadHost
                            )
                            : []
                    });
                    this.setState({
                        locations:data.data.locations,
                        checked:data.data.locations.length === companyList.length,
                        indeterminate: data.data.locations.length < companyList.length,
                        pictureUrl:data.data.pictureUrl
                            ? splitUrl(
                                data.data.pictureUrl,
                                ",",
                                globalConfig.avatarUploadHost
                            )
                            : []
                    })
                }
            }.bind(this)
        }).always(
            function() {
                this.setState({
                    loading: false
                });
            }.bind(this)
        );
    }

    componentDidMount() {
        if(this.props.id){
            this.getSelect();
        }
    }

    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <Modal
                className="customeDetails"
                title={this.props.id?"修改活动":"新增活动"}
                width="700px"
                onCancel={this.props.onCancel}
                visible={this.props.visible}
                footer={false}
            >
                <Form
                    layout="horizontal"
                    onSubmit={this.submit}
                    id="demand-form"
                >
                    <Spin spinning={this.state.loading}>
                        <FormItem
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 8 }}
                            label="活动标题"
                        >
                            {getFieldDecorator('title', {
                                rules: [{ required: true, message: '请输入活动标题!' }],
                            })(
                                <Input placeholder="请输入活动标题" />
                            )}
                        </FormItem>
                        <FormItem
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 8 }}
                            label="发布人"
                        >
                            {getFieldDecorator('publisher', {
                                rules: [{ required: true, message: '请输入发布人名称!' }],
                            })(
                                <Input placeholder="请输入发布人名称" />
                            )}
                        </FormItem>
                        <FormItem
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 8 }}
                            label="排序"
                        >
                            {getFieldDecorator('sort', {
                                rules: [{ required: true, message: '请输入排序!' }],
                            })(
                                <Input placeholder="请输入排序" type={'number'}/>
                            )}
                        </FormItem>
                        <FormItem
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 8 }}
                            label="是否发布"
                        >
                            {getFieldDecorator('releaseStatus',{
                                rules: [{ required: true, message: '请选择是否显示!' }],
                            })(
                                <RadioGroup>
                                    <Radio value={0}>否</Radio>
                                    <Radio value={1}>是</Radio>
                                </RadioGroup>
                            )}
                        </FormItem>
                        <FormItem
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 12 }}
                            label="公司"
                        >
                            <Checkbox indeterminate={this.state.indeterminate} checked={this.state.checked} onChange={(e)=>{
                                this.setState({
                                    locations: e.target.checked ? getCompanyValueArray():[],
                                    indeterminate: false,
                                    checked:e.target.checked
                                })
                            }}>全选</Checkbox>
                            <Checkbox.Group
                                options={companyList}
                                value={this.state.locations}
                                onChange={(e) => {
                                    this.setState({
                                        locations: e,
                                        indeterminate: companyList.length > e.length,
                                        checked: companyList.length === e.length
                                    });
                                }}
                            />
                        </FormItem>
                        <FormItem
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 8 }}
                            label="活动简介"
                        >
                            {getFieldDecorator('content', {
                                rules: [{ required: true, message: '请输入活动简介!' }],
                            })(
                                <TextArea placeholder="请输入活动简介" type={'number'}/>
                            )}
                        </FormItem>
                        <FormItem
                            labelCol={{ span: 8 }}
                            wrapperCol={{ span: 8 }}
                            label="活动大图"
                            extra="图片尺寸:1240X440"
                        >
                            {getFieldDecorator('pictureUrl', {
                                rules: [{ required: true, message: '请选择活动大图!' }],
                            })(
                                <PicturesWall
                                    fileList={this.getOrgCodeUrl}
                                    pictureUrl={this.state.pictureUrl}
                                />
                            )}
                        </FormItem>
                        <FormItem
                           style={{
                               display: 'flex',
                               justifyContent: 'center',
                           }}
                        >
                            <Button
                                loading={this.state.loading}
                                type="primary"
                                htmlType="submit"
                            >
                                {this.props.id ? '保存':'添加' }
                            </Button>
                        </FormItem>
                    </Spin>
                </Form>
            </Modal>
        );
    }
}
const ActivityOperationForm = Form.create()(ActivityOperation);

export default ActivityOperationForm;
