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: '',
            sort:'',
            summary:'',
            name:'',
            pictureVideoUrl: '',
            pictureImgUrl: '',
            content: '',
            commodityContent: '',
            amount: '',
            projectList: [],
            host: 0,
            commodityType: '',
        }
        this.getOrgCodeUrl = this.getOrgCodeUrl.bind(this);
        this.getVideoOrgCodeUrl = this.getVideoOrgCodeUrl.bind(this);
        this.onOk = this.onOk.bind(this);
        this.getProjectList = this.getProjectList.bind(this);
    }

    componentDidMount() {
        this.getProjectList();
    }

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

    getVideoOrgCodeUrl(e) {
        if(e.length === 0){
            this.setState({
                pictureVideoUrl: '',
                commodityType: '',
            });
        }else{
            let str = e[0].type;
            let index = str.indexOf("/");
            let type =str.substring(0,index);
            this.setState({
                pictureVideoUrl: e,
                commodityType: type === 'video' ? 1 : type === 'audio' ? 2 : 0,
            });
        }

    }

    onOk(releaseStatus = 0){
        if(!this.state.name){
            message.warning('请输入产品名称');
            return false;
        }
        if(isNaN(parseInt(this.state.projectType))){
            message.warning('请输入产品分类');
            return false;
        }
        if(isNaN(parseInt(this.state.amount))){
            message.warning('请输入正确的金额');
            return false;
        }
        // if(this.state.pictureVideoUrl.length === 0){
        //     message.warning('请上传视频/音频');
        //     return false;
        // }
        if(this.state.pictureImgUrl.length === 0){
            message.warning('请上传略缩图');
            return false;
        }
        if(!this.state.commodityContent){
            message.warning('请输入未购买简介');
            return false;
        }
        if(!this.state.content){
            message.warning('请输入已购买简介');
            return false;
        }
        this.setState({
            loading: true
        });
        let url = this.props.id ? "/api/admin/project/update" : "/api/admin/project/add"
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + url,
            data: {
                name: this.state.name || undefined,
                sort:this.state.sort || undefined,
                summary:this.state.summary || undefined,
                content: this.state.content || undefined,
                commodityContent: this.state.commodityContent || undefined,
                id: this.props.id || undefined,
                type: this.state.projectType,
                amount: !isNaN(parseInt(this.state.amount)) ? this.state.amount : undefined,
                commodityUrl: this.state.pictureVideoUrl ? this.state.pictureVideoUrl[0].response.data : '',
                commodityType: this.state.commodityType,
                thumbnailUrl: this.state.pictureImgUrl[0].response.data || undefined,
                host: this.state.host,
                releaseStatus,
            },
            success: function(data) {
                if (data.error && data.error.length) {
                    message.warning(data.error[0].message);
                } else {
                    message.success(this.state.id ? '修改成功' : '添加成功');
                    this.props.onOk();
                }
            }.bind(this)
        }).always(
            function() {
                this.setState({
                    loading: false
                });
            }.bind(this)
        );
    }

    getProjectList() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/open/projectTypeList",
            data: {}
        }).done((data1) => {
            if (data1.error.length !== 0) {
                message.warning(data1.error[0].message);
            } else {
                this.setState({
                    projectList: data1.data,
                },()=>{
                    if(this.props.infor){
                        this.setState({
                            name: this.props.infor.name,
                            sort:this.props.infor.sort,
                            summary:this.props.infor.summary,
                            content: this.props.infor.content,
                            commodityContent: this.props.infor.commodityContent,
                            projectType: this.props.infor.type,
                            amount: this.props.infor.amount,
                            pictureVideoUrl: this.props.infor.commodityUrl ? splitUrl(this.props.infor.commodityUrl, ',', globalConfig.avatarHost + '/upload') : '',
                            pictureImgUrl: this.props.infor.thumbnailUrl ? splitUrl(this.props.infor.thumbnailUrl, ',', globalConfig.avatarHost + '/upload') : [],
                            host: this.props.infor.host,
                            commodityType:this.props.infor.commodityType
                        })
                    }
                });
            }
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this))
    }

    render() {
        return (
            <Modal
                className="customeDetails"
                title={this.props.id ? "修改产品" : "添加产品"}
                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>
                            <FormItem
                                className="half-item"
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 12 }}
                                label="产品分类"
                            >
                                <Select
                                    value={this.state.projectType}
                                    placeholder="请选择产品分类"
                                    onChange={e => {
                                        this.setState({
                                            projectType: e
                                        });
                                    }}
                                >
                                    {
                                        this.state.projectList.map((v,k)=>(
                                            <Option key={k} value={v.id}>{v.name}</Option>
                                        ))
                                    }
                                </Select>
                            </FormItem>
                            <FormItem
                                className="half-item"
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 12 }}
                                label="产品金额"
                            >
                                <Input
                                    type={'number'}
                                    placeholder="请输入产品金额"
                                    value={this.state.amount}
                                    onChange={(e) => {
                                        this.setState({ amount: e.target.value });
                                    }}
                                />
                            </FormItem>
                            <FormItem
                                className="half-item"
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 12 }}
                                label="是否发布到首页"
                            >
                                <Select
                                    value={this.state.host}
                                    placeholder="是否发布到首页"
                                    onChange={e => {
                                        this.setState({
                                            host: e
                                        });
                                    }}
                                >
                                    <Option value={0}>否</Option>
                                    <Option value={1}>是</Option>
                                </Select>
                            </FormItem>
                            <FormItem
                                className="half-item"
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 12 }}
                                label="排序"
                            >
                                <Input
                                    placeholder="请输入排序"
                                    value={this.state.sort}
                                    onChange={e => {
                                        this.setState({
                                            sort: e.target.value
                                        });
                                    }}
                                />
                                <p>数字越大,排序越前</p>
                            </FormItem>
                            <FormItem
                                className="half-item"
                                labelCol={{ span: 8 }}
                                wrapperCol={{ span: 12 }}
                                label="摘要"
                            >
                                <Input
                                    placeholder="请输入摘要"
                                    value={this.state.summary}
                                    onChange={e => {
                                        this.setState({
                                            summary: e.target.value
                                        });
                                    }}
                                />
                            </FormItem>
                            <div className="clearfix">
                                <FormItem
                                    className="half-item"
                                    labelCol={{ span: 8 }}
                                    wrapperCol={{ span: 12 }}
                                    label="缩略图"
                                >
                                    <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="视频/音频"
                                >
                                    <PicturesWall
                                        type={this.state.commodityType}
                                        fileList={this.getVideoOrgCodeUrl}
                                        pictureUrl={this.state.pictureVideoUrl}
                                    />
                                    <p>支持<span style={{color:'#F00'}}>MP3/MP4/RMVB/MKV/AVI</span></p>
                                </FormItem>
                            </div>
                            <div className="clearfix">
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 18 }}
                                    label="未购买简介"
                                >
                                    <Editors
                                        id={0}
                                        textContent={this.state.content}
                                        uploadUrl={"/api/admin/news/uploadFile"}
                                        globalConfig={globalConfig.uploadPath}
                                        placeholder="内容(编辑器,支持图文音频等)"
                                        handleRichText={value => {
                                            this.setState({ content: value });
                                        }}
                                    />
                                </FormItem>
                            </div>
                            <div className="clearfix">
                                <FormItem
                                    labelCol={{ span: 4 }}
                                    wrapperCol={{ span: 18 }}
                                    label="已购买简介"
                                >
                                    <Editors
                                        id={1}
                                        textContent={this.state.commodityContent}
                                        uploadUrl={"/api/admin/news/uploadFile"}
                                        globalConfig={globalConfig.uploadPath}
                                        placeholder="内容(编辑器,支持图文音频等)"
                                        handleRichText={value => {
                                            this.setState({ commodityContent: value });
                                        }}
                                    />
                                </FormItem>
                            </div>
                        </div>
                        <div style={{display:'flex',justifyContent: 'center'}}>
                            <Button
                                type="primary"
                                onClick={()=>{
                                    this.onOk();
                                }}>
                                保存
                            </Button>
                            <Button
                                type="primary"
                                style={{marginLeft:'30px'}}
                                onClick={()=>{
                                    this.onOk(1);
                                }}>
                                保存并发布
                            </Button>
                        </div>
                    </SpinContainer>
                </Form>
            </Modal>
        )
    }
}

export default Add;
