import React,{Component} from 'react';
import SpinContainer from "../../../SpinContainer";
import {Button, Form, Icon, Input, message, Modal, Select, Upload} from "antd";
import {beforeUploadFile,splitUrl} from "@/tools.js";
import Editors from "@/richTextEditors";
import $ from "jquery/src/ajax";

const FormItem = Form.Item;

//上传图片组件
const PicturesWall = React.createClass({
    getInitialState() {
        return {
            previewVisible: false,
            previewImage: "",
            fileList: this.props.pictureUrl,
            type:''
        };
    },
    getDefaultProps() {
        return {
            changeClick: this.modifyChange
        };
    },
    handleCancel() {
        this.setState({ previewVisible: false });
    },
    handlePreview(file) {
        let type = '';

        if(file.type){
            let str = file.type;
            let index = str.indexOf("/");
            type =str.substring(0,index) === 'video' ? 1 : str.substring(0,index) === 'audio' ? 2 : 0;
        }else{
            // let str = file.url || file.thumbUrl;
            // let index = str.lastIndexOf(".");
            // type = str.substring(index+1);
            type = this.props.type;
        }
        this.setState({
            type,
            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
                    accept={
                        this.props.type === 0 ? "image/*" :
                            this.props.type === 1 ?
                                'video/mp4,video/rmvb,video/mkv,video/avi' :
                                this.props.type === 2 ?
                                "audio/mp3" : '*'}
                    beforeUpload={beforeUploadFile}
                    action={globalConfig.context + "/api/admin/project/uploadFile"}
                    data={{ sign: "purchase_picture" }}
                    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={this.handleCancel}
                >
                    {
                        this.state.type=== 0 ?
                            <img alt="" style={{ width: "100%" }} src={previewImage} /> :
                            this.state.type=== 1 ?
                                <video style={{width:'100%'}} controls="controls" autoPlay="" name="media">
                                    <source src={previewImage} type="video/mp4"/>
                                </video>:
                                this.state.type=== 2 ?
                                    <audio src={previewImage} controls="controls">Your browser does not support the audio element.</audio>: ''
                    }
                </Modal>
            </div>
        );
    }
});

class Add extends Component{
    constructor(props) {
        super(props);
        this.state={
            loading: false,
            projectType: props.shareType || '',
            name:'',
            pictureImgUrl: '',
            shareImgUrl:'',
            shareId:'',
        }
        this.getOrgCodeUrl = this.getOrgCodeUrl.bind(this);
        this.getShareOrgCodeUrl = this.getShareOrgCodeUrl.bind(this);
        this.onOk = this.onOk.bind(this);
        this.getWeChatShareDetals = this.getWeChatShareDetals.bind(this);
    }

    componentDidMount() {
        if(this.props.id || this.props.shareId){
            this.getWeChatShareDetals();
        }
    }

    getOrgCodeUrl(e) {
        this.setState({ pictureImgUrl: e });
    }

    getShareOrgCodeUrl(e) {
        this.setState({ shareImgUrl: e });
    }

    onOk(){
        if(!this.state.name){
            message.warning('请输入分享标题');
            return false;
        }
        if(isNaN(parseInt(this.state.projectType))){
            message.warning('请选择分享位置');
            return false;
        }
        if(this.state.pictureImgUrl.length === 0){
            message.warning('请上传朋友分享图');
            return false;
        }
        if(this.state.shareImgUrl.length === 0){
            message.warning('请上传朋友圈分享图');
            return false;
        }
        this.setState({
            loading: true
        });
        let url = this.state.shareId ? "/api/admin/weChatShare/update" : "/api/admin/weChatShare/add"
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + url,
            data: {
                pid: this.props.id || undefined,       //项目编号
                id: this.state.shareId || undefined,
                title: this.state.name || undefined,
                shareUrl: this.state.pictureImgUrl[0].response.data || undefined,
                momentsUrl: this.state.shareImgUrl[0].response.data || undefined,
                type: this.state.projectType,
            },
            success: function(data) {
                if (data.error && data.error.length) {
                    message.warning(data.error[0].message);
                } else {
                    message.success(this.state.shareId ? '修改成功' : '添加成功');
                    this.props.onOk();
                }
            }.bind(this)
        }).always(
            function() {
                this.setState({
                    loading: false
                });
            }.bind(this)
        );
    }

    getWeChatShareDetals() {
        this.setState({
            loading: true
        });
        let data = {};
        if(this.props.id){
            data.pid = this.props.id
        }else if(this.props.shareId){
            data.id = this.props.shareId
        }
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/weChatShare/details",
            data: data
        }).done((data1) => {
            if (data1.error.length !== 0) {
                message.warning(data1.error[0].message);
            } else {
                if(data1.data){
                    this.setState({
                        name: data1.data.title,
                        projectType: data1.data.type,
                        pictureImgUrl: data1.data.shareUrl ? splitUrl(data1.data.shareUrl, ',', globalConfig.avatarHost + '/upload') : [],
                        shareImgUrl: data1.data.momentsUrl ? splitUrl(data1.data.momentsUrl, ',', globalConfig.avatarHost + '/upload') : [],
                        shareId:data1.data.id,
                    })
                }
            }
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this))
    }

    render() {
        return (
            <Modal
                className="customeDetails"
                title={this.state.shareId ? "修改分享" : "添加分享"}
                okText={"保存"}
                width="1050"
                visible={this.props.visible}
                onCancel={this.props.onCancel}
                footer={false}
            >
                <Form
                    layout="horizontal"
                    id="demand-form"
                >
                    <SpinContainer spinning={this.state.loading}>
                        <div className="clearfix">
                            <FormItem
                                className="half-item"
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 12 }}
                                label="转发标题"
                            >
                                <Input
                                    placeholder="请输入转发标题"
                                    value={this.state.name}
                                    onChange={(e) => {
                                        this.setState({ name: e.target.value });
                                    }}
                                />
                            </FormItem>
                            {!this.props.shareType ? <FormItem
                                className="half-item"
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 12 }}
                                label="分享位置"
                            >
                                <Select
                                    value={this.state.projectType}
                                    placeholder="请选择分享位置"
                                    onChange={e => {
                                        this.setState({
                                            projectType: e
                                        });
                                    }}
                                >
                                    <Option value={1}>首页</Option>
                                </Select>
                            </FormItem> : null}
                            <div className="clearfix">
                                <FormItem
                                    className="half-item"
                                    labelCol={{ span: 8 }}
                                    wrapperCol={{ span: 12 }}
                                    label="朋友分享图"
                                    extra='图片长宽比是 5:4,建议尺寸660*528'
                                >
                                    <PicturesWall
                                        type={0}
                                        fileList={this.getOrgCodeUrl}
                                        pictureUrl={this.state.pictureImgUrl}
                                    />
                                </FormItem>
                            </div>
                            <div className="clearfix">
                                <FormItem
                                    className="half-item"
                                    labelCol={{ span: 8 }}
                                    wrapperCol={{ span: 12 }}
                                    label="朋友圈分享图"
                                    extra='图片长宽比是 1:1,会自动收缩,尺寸大小影响不大'
                                >
                                    <PicturesWall
                                        type={0}
                                        fileList={this.getShareOrgCodeUrl}
                                        pictureUrl={this.state.shareImgUrl}
                                    />
                                </FormItem>
                            </div>
                        </div>
                        <div style={{display:'flex',justifyContent: 'center'}}>
                            <Button
                                type="primary"
                                onClick={()=>{
                                    this.onOk();
                                }}>
                                保存
                            </Button>
                        </div>
                    </SpinContainer>
                </Form>
            </Modal>
        )
    }
}

export default Add;
