import React from 'react';
import { Icon, Tooltip, Modal, message, Spin, Upload, Input, InputNumber, Select, DatePicker, Button, Radio, Form, Cascader, Tag } from 'antd';
import moment from 'moment';
import './techDemand.less';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import { IndustryObject } from '../../DicIndustryList.js';
import { beforeUploadFile, splitUrl, companySearch } from '../../tools.js';

const KeyWordTagGroup = React.createClass({
    getInitialState() {
        return {
            tags: [],
            inputVisible: false,
            inputValue: ''
        };
    },
    handleClose(removedTag) {
        const tags = this.state.tags.filter(tag => tag !== removedTag);
        this.props.tagsArr(tags);
        this.setState({ tags });
    },
    showInput() {
        this.setState({ inputVisible: true }, () => this.input.focus());
    },
    handleInputChange(e) {
        this.setState({ inputValue: e.target.value });
    },
    handleInputConfirm() {
        const state = this.state;
        const inputValue = state.inputValue;
        let tags = state.tags;
        if (inputValue && tags.indexOf(inputValue) === -1) {
            tags = [...tags, inputValue];
        }
        this.props.tagsArr(tags);
        this.setState({
            tags,
            inputVisible: false,
            inputValue: '',
        });
    },
    componentWillMount() {
        this.state.tags = this.props.keyWordArr;
    },
    componentWillReceiveProps(nextProps) {
        if (this.props.keyWordArr != nextProps.keyWordArr) {
            this.state.tags = nextProps.keyWordArr;
        };
    },
    render() {
        const { tags, inputVisible, inputValue } = this.state;
        return (
            <div className="keyWord-tips">
                {tags.map((tag, index) => {
                    const isLongTag = tag.length > 10;
                    const tagElem = (
                        <Tag key={tag} closable={index !== -1} afterClose={() => this.handleClose(tag)}>
                            {isLongTag ? `${tag.slice(0, 10)}...` : tag}
                        </Tag>
                    );
                    return isLongTag ? <Tooltip title={tag}>{tagElem}</Tooltip> : tagElem;
                })}
                {inputVisible && (
                    <Input
                        ref={input => this.input = input}
                        type="text"
                        style={{ width: 78 }}
                        value={inputValue}
                        onChange={this.handleInputChange}
                        onBlur={this.handleInputConfirm}
                        onPressEnter={this.handleInputConfirm}
                    />
                )}
                {!inputVisible && <Button className="addtips" type="dashed" disabled={tags.length > 9 ? true : false} onClick={this.showInput}>+ 新关键词</Button>}
            </div>
        );
    }
});

const PicturesWall = React.createClass({
    getInitialState() {
        return {
            previewVisible: false,
            previewImage: '',
            fileList: [],
        }
    },
    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/demand/uploadPicture"}
                    data={{ 'sign': 'demand_picture', 'uid': this.props.uid }}
                    listType="picture-card"
                    fileList={fileList}
                    onPreview={this.handlePreview}
                    onChange={this.handleChange} >
                    {fileList.length >= 5 ? null : uploadButton}
                </Upload>
                <Modal maskClosable={false} visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        );
    }
});

const DemandDetailForm = Form.create()(React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false,
            textFileList: [],
            videoFileList: [],
            pictureUrl: [],
            tags: []
        };
    },
    loadData(id, detailApiUrl) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + detailApiUrl,
            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 = {};
                };
                let d = new Date()
                if (thisData && thisData.dateOfBirthMonth && thisData.dateOfBirthYear) {
                    d.setMonth(thisData.dateOfBirthMonth - 1);
                    d.setYear(parseInt(thisData.dateOfBirthYear));
                };
                this.setState({
                    data: thisData,
                    tags: thisData.keyword ? thisData.keyword.split(",") : [],
                    pictureUrl: thisData.pictureUrl ? splitUrl(thisData.pictureUrl, ',', globalConfig.avatarHost + '/upload') : []
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getSalesmanList() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/salesman",
            success: function (data) {
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    }
                    return;
                };
                let _me = this, theArr = [];
                for (var item in data.data) {
                    theArr.push(
                        <Select.Option value={item} key={item}>{data.data[item]}</Select.Option>
                    )
                };
                this.setState({
                    salesmanOption: theArr
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getContactsList(theUid) {
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/getContacts",
            data: {
                uid: theUid
            },
            success: function (data) {
                let theOption = [];
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                        return;
                    };
                };
                for (let item in data.data) {
                    let theData = data.data[item];
                    theOption.push(
                        <Select.Option value={item} key={theData}>{theData}</Select.Option>
                    );
                };
                this.setState({
                    contactsOption: theOption
                });
            }.bind(this),
        });
    },
    getTagsArr(e) {
        this.setState({ tags: e });
    },
    getPictureUrl(e) {
        this.setState({ pictureUrl: e });
    },
    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            //keyword长度判断
            if (this.state.tags.length < 3) {
                message.warning('关键词数量不能小于3个！');
            };
            //url转化
            let thePictureUrl = [];
            if (this.state.pictureUrl.length) {
                let picArr = [];
                this.state.pictureUrl.map(function (item) {
                    picArr.push(item.response.data);
                });
                thePictureUrl = picArr.join(",");
            };
            if (!err) {
                this.setState({
                    loading: true
                });
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: this.props.data.id ? globalConfig.context + '/api/admin/demand/update' : globalConfig.context + '/api/admin/demand/apply',
                    data: {
                        id: this.props.data.id,
                        dataCategory: this.props.detailApiUrl.indexOf('org') >= 0 ? 1 : 0,
                        serialNumber: this.props.data.serialNumber,
                        name: values.name,
                        keyword: this.state.tags ? this.state.tags.join(",") : [],
                        infoSources: values.infoSources,
                        industryCategoryA: values.industryCategory ? values.industryCategory[0] : undefined,
                        industryCategoryB: values.industryCategory ? values.industryCategory[1] : undefined,
                        demandType: values.demandType,
                        problemDes: values.problemDes,
                        technicalRequirements: values.technicalRequirements,
                        pictureUrl: thePictureUrl,
                        textFileUrl: this.state.textFileUrl,
                        videoUrl: values.videoUrl,
                        fixedBudget: values.fixedBudget,
                        fixedCycle: values.fixedCycle,
                        peopleNumber: values.peopleNumber,
                        fixedScheme: values.fixedScheme,
                        costEscrow: values.costEscrow,
                        budgetCost: values.budgetCost,
                        employerId: values.employerId || this.state.data.employerId,
                        releaseStatus: values.releaseStatus,
                        principalId: values.principalId,
                        validityPeriodFormattedDate: values.validityPeriod ? values.validityPeriod.format('YYYY-MM-DD') : undefined,
                        //
                        contacts: values.contacts,
                        status: this.state.status
                    }
                }).done(function (data) {
                    if (!data.error.length) {
                        message.success('保存成功！');
                        this.setState({
                            visible: false
                        });
                        this.props.handleOk();
                    } else {
                        message.warning(data.error[0].message);
                    }
                }.bind(this));
            }
        });
    },
    componentWillMount() {
        this.getSalesmanList();
        if (this.props.data.id) {
            this.loadData(this.props.data.id, this.props.detailApiUrl);
            if (this.props.data.employerId && this.props.detailApiUrl.indexOf('org') >= 0) {
                this.getContactsList(this.props.data.employerId)
            };
        } else {
            this.state.data = {};
        };
    },
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible) {
            this.state.textFileList = [];
            this.state.videoFileList = [];
            if (nextProps.data.id) {
                this.loadData(nextProps.data.id, nextProps.detailApiUrl);
                if (nextProps.data.employerId && nextProps.detailApiUrl.indexOf('org') >= 0) {
                    this.getContactsList(nextProps.data.employerId)
                };
            } else {
                this.state.data = {};
                this.state.tags = [];
                this.state.pictureUrl = [];
            };
            this.props.form.resetFields();
        };
    },
    render() {
        const theData = this.state.data || {};
        const { getFieldDecorator } = this.props.form;
        const FormItem = Form.Item
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 12 },
        };
        return (
            <Form horizontal onSubmit={this.handleSubmit} id="demand-form">
                <div className="clearfix">
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="编号" >
                        <span>{theData.serialNumber}</span>
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="需求名称" >
                        {getFieldDecorator('name', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.name
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item" style={{ display: theData.username ? 'block' : 'none' }}
                        {...formItemLayout}
                        label="雇主名称" >
                        <span>{theData.username}</span>
                    </FormItem>
                    <FormItem className="half-item" style={{ display: theData.username ? 'none' : 'block' }}
                        {...formItemLayout}
                        label="雇主名称" >
                        {getFieldDecorator('employerId', {
                            initialValue: theData.employerId
                        })(
                            <Select
                                placeholder="请选择"
                                notFoundContent="未找到"
                                style={{ width: 260 }}
                                showSearch
                                filterOption={companySearch}
                                onSelect={(e, n) => {
                                    theData.uid = e;
                                    if (this.props.detailApiUrl.indexOf('org') >= 0) {
                                        this.getContactsList(e);
                                    };
                                }}>
                                {this.props.detailApiUrl.indexOf('org') >= 0 ? this.props.companyOption : this.props.userOption}
                            </Select>
                            )}
                    </FormItem>
                    {this.props.detailApiUrl.indexOf('org') >= 0 ? <FormItem className="half-item"
                        {...formItemLayout}
                        label="联系人" >
                        {getFieldDecorator('contacts', {
                            initialValue: theData.contacts
                        })(
                            <Select style={{ width: 260 }}
                                placeholder="请选择联系人"
                                notFoundContent="未获取到联系人列表"
                                showSearch
                                filterOption={companySearch}>
                                {this.state.contactsOption}
                            </Select>
                            )}
                    </FormItem> : <div></div>}
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="负责人" >
                        {getFieldDecorator('principalId', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.principalId
                        })(
                            <Select style={{ width: 260 }}
                                placeholder="请选择负责人"
                                notFoundContent="未获取到负责人列表"
                                showSearch
                                filterOption={companySearch}>
                                {this.state.salesmanOption}
                            </Select>
                            )}
                    </FormItem>
                </div>
                <div className="clearfix">
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="是否发布" >
                        {getFieldDecorator('releaseStatus', {
                            initialValue: theData.releaseStatus
                        })(
                            <Radio.Group>
                                <Radio value="0">未发布</Radio>
                                <Radio value="1">发布</Radio>
                            </Radio.Group>
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="发布时间" >
                        <span>{theData.releaseDateFormattedDate}</span>
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="需求状态" >
                        {(() => {
                            if (theData.status > 1) {
                                return <Radio.Group
                                    value={this.state.status}
                                    onChange={(e) => { this.setState({ status: e }); }}>
                                    <Radio value="2">未解决</Radio>
                                    <Radio value="3">已解决</Radio>
                                </Radio.Group>
                            } else {
                                switch (theData.status) {
                                    case "0":
                                        return <span>草稿</span>;
                                    case "1":
                                        return <span>进行中</span>;
                                };
                            };
                        })()}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="需求创建时间" >
                        <span>{theData.createTimeFormattedDate}</span>
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="信息来源" >
                        {getFieldDecorator('infoSources', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.infoSources
                        })(
                            <Radio.Group>
                                <Radio value="0">平台采集</Radio>
                                <Radio value="1">客户发布</Radio>
                            </Radio.Group>
                            )}
                    </FormItem>
                </div>
                <FormItem
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 20 }}
                    label="关键词" >
                    <KeyWordTagGroup
                        keyWordArr={this.state.tags}
                        tagsArr={this.getTagsArr}
                        visible={this.props.visible} />
                </FormItem>
                <FormItem
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 18 }}
                    label="行业类别" >
                    {getFieldDecorator('industryCategory', {
                        rules: [{ type: 'array', required: true, message: '此项为必填项!' }],
                        initialValue: [theData.industryCategoryA, theData.industryCategoryB]
                    })(
                        <Cascader style={{ width: 300 }} options={IndustryObject} placeholder="请选择一个行业" />
                        )}
                </FormItem>
                <div className="clearfix">
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="需求类型" >
                        {getFieldDecorator('demandType', {
                            rules: [{ required: true, message: '此项为必填项!' }],
                            initialValue: theData.demandType
                        })(
                            <Select style={{ width: 160 }} placeholder="请选择需求类型">
                                {this.props.demandTypeOption}
                            </Select>
                            )}
                    </FormItem>
                </div>
                <FormItem
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 18 }}
                    label="问题说明" >
                    {getFieldDecorator('problemDes', {
                        rules: [{ required: true, message: '此项为必填项!' }],
                        initialValue: theData.problemDes
                    })(
                        <Input type="textarea" rows={4} />
                        )}
                </FormItem>
                <FormItem
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 18 }}
                    label="技术指标要求" >
                    {getFieldDecorator('technicalRequirements', {
                        initialValue: theData.technicalRequirements
                    })(
                        <Input type="textarea" rows={2} />
                        )}
                </FormItem>
                <FormItem
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 18 }}
                    label="需求文件(图片)" >
                    <PicturesWall
                        uid={theData.uid}
                        fileList={this.getPictureUrl}
                        pictureUrl={this.state.pictureUrl}
                        visible={this.props.visible} />
                </FormItem>
                <FormItem
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 6 }}
                    label="需求文件(文本)" >
                    <Upload
                        name="ratepay"
                        action={globalConfig.context + "/api/admin/demand/uploadTextFile"}
                        data={{ 'sign': 'demand_text_file', 'uid': theData.uid }}
                        beforeUpload={beforeUploadFile}
                        fileList={this.state.textFileList}
                        onChange={(info) => {
                            if (info.file.status !== 'uploading') {
                                console.log(info.file, info.fileList);
                            }
                            if (info.file.status === 'done') {
                                if (!info.file.response.error.length) {
                                    message.success(`${info.file.name} 文件上传成功！`);
                                } else {
                                    message.warning(info.file.response.error[0].message);
                                    return;
                                };
                                this.state.textFileUrl = info.file.response.data;
                            } else if (info.file.status === 'error') {
                                message.error(`${info.file.name} 文件上传失败。`);
                            };
                            this.setState({ textFileList: info.fileList.slice(-1) });
                        }} >
                        <Button><Icon type="upload" /> 上传需求文本文件 </Button>
                    </Upload>
                    <p style={{ marginTop: '10px' }}>{theData.textFileUrl ?
                        <span className="download-file">
                            <a onClick={() => { window.open(globalConfig.context + '/api/admin/demand/download?id=' + this.props.data.id) }}>需求文件(文本文件)</a>
                        </span>
                        : <span><Icon type="exclamation-circle" style={{ color: '#ffbf00', marginRight: '6px' }} />未上传！</span>}</p>
                </FormItem>
                <FormItem
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 18 }}
                    label="需求文件(视频地址)" >
                    {getFieldDecorator('videoUrl', {
                        initialValue: theData.videoUrl
                    })(
                        <Input />
                        )}
                </FormItem>
                <div className="clearfix">
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="固定周期" >
                        {getFieldDecorator('fixedCycle', {
                            initialValue: theData.fixedCycle
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="固定人数" >
                        {getFieldDecorator('peopleNumber', {
                            initialValue: theData.peopleNumber
                        })(
                            <InputNumber />
                            )}
                        <span style={{ marginLeft: '20px' }}>人</span>
                    </FormItem>
                </div>
                <FormItem
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 18 }}
                    label="固定方案" >
                    {getFieldDecorator('fixedScheme', {
                        initialValue: theData.fixedScheme
                    })(
                        <Input type="textarea" rows={2} />
                        )}
                </FormItem>
                <div className="clearfix">
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="预算费用" >
                        {getFieldDecorator('budgetCost', {
                            initialValue: theData.budgetCost
                        })(
                            <InputNumber />
                            )}
                        <span style={{ marginLeft: '20px' }}>万元</span>
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="费用托管" >
                        {getFieldDecorator('costEscrow', {
                            initialValue: theData.costEscrow
                        })(
                            <Radio.Group>
                                <Radio value={0}>否</Radio>
                                <Radio value={1}>是</Radio>
                            </Radio.Group>
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="有效期限" >
                        {getFieldDecorator('validityPeriod', {
                            initialValue: theData.validityPeriod ? moment(theData.validityPeriod) : null
                        })(
                            <DatePicker />
                            )}
                    </FormItem>
                </div>
                <div className="clearfix" style={{ display: 'none' }}>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="雇主客户ID" >
                        {getFieldDecorator('employerId', {
                            initialValue: theData.employerName
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="雇主地址" >
                        {getFieldDecorator('employerAddress', {
                            initialValue: theData.employerAddress
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="雇主联系人名称" >
                        {getFieldDecorator('employerContacts', {
                            initialValue: theData.employerContacts
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="雇主联系人电话" >
                        {getFieldDecorator('employerContactsMobile', {
                            initialValue: theData.employerContactsMobile
                        })(
                            <Input />
                            )}
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="雇主联系人邮箱" >
                        {getFieldDecorator('employerContactsMailbox', {
                            initialValue: theData.employerContactsMailbox
                        })(
                            <Input />
                            )}
                    </FormItem>
                </div>
                <div className="clearfix">
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="雇主地址" >
                        <span>{theData.employerAddress}</span>
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="雇主联系人名称" >
                        <span>{theData.employerContacts}</span>
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="雇主联系人电话" >
                        <span>{theData.employerContactsMobile}</span>
                    </FormItem>
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="雇主联系人邮箱" >
                        <span>{theData.employerContactsMailbox}</span>
                    </FormItem>
                </div>
                <FormItem wrapperCol={{ span: 12, offset: 3 }}>
                    <Button className="set-submit" type="primary" htmlType="submit">保存</Button>
                    <Button className="set-submit" type="ghost" onClick={this.props.closeDesc}>取消</Button>
                </FormItem>
            </Form >
        )
    }
}));

const DemandDetail = React.createClass({
    getInitialState() {
        return {
            visible: false
        };
    },
    showModal() {
        this.setState({
            visible: true,
        });
    },
    handleCancel(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false);
    },
    handleOk(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false, true);
    },
    componentWillReceiveProps(nextProps) {
        this.state.visible = nextProps.showDesc;
    },
    render() {
        if (this.props.data) {
            return (
                <div className="patent-desc">
                    <Modal maskClosable={false} title="用户需求详情" visible={this.state.visible}
                        onOk={this.checkPatentProcess} onCancel={this.handleCancel}
                        width='1000px'
                        footer=''
                        className="admin-desc-content">
                        <DemandDetailForm
                            data={this.props.data}
                            detailApiUrl={this.props.detailApiUrl}
                            companyOption={this.props.companyOption}
                            userOption={this.props.userOption}
                            demandTypeOption={this.props.demandTypeOption}
                            closeDesc={this.handleCancel}
                            visible={this.state.visible}
                            handleOk={this.handleOk} />
                    </Modal>
                </div>
            );
        } else {
            return <div></div>
        }
    },
});

export default DemandDetail;