import React from 'react';
import { Icon, Tabs, Table, Tooltip, Modal, Popover, 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 { getTechField } from '../../DicTechFieldList.js';
import { IndustryObject, getIndustryCategory } from '../../DicIndustryList.js';
import { beforeUploadFile, splitUrl, companySearch, getDemandType, getAchievementCategory } from '../../tools.js';
import ImgList from "../../common/imgList";
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 && inputValue.replace(/(^\s*)|(\s*$)/g, "").length != 0) {
            tags = [...tags, inputValue.replace(/(^\s*)|(\s*$)/g, "")];
        }
        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 (
            
                {tags.map((tag, index) => {
                    const isLongTag = tag.length > 10;
                    const tagElem = (
                         this.handleClose(tag)}>
                            {isLongTag ? `${tag.slice(0, 10)}...` : tag}
                        
                    );
                    return isLongTag ? {tagElem} : tagElem;
                })}
                {inputVisible && (
                     this.input = input}
                        type="text"
                        style={{ width: 78 }}
                        value={inputValue}
                        onChange={this.handleInputChange}
                        onBlur={this.handleInputConfirm}
                        onPressEnter={this.handleInputConfirm}
                    />
                )}
                {!inputVisible && }
            
        );
    }
});
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 = (
            
        );
        return (
            
                {
                        this.handleChange(infor)
                    }}
                    fileList={fileList}
                />
             
        );
    }
});
const DemandDetailShow = Form.create()(React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false,
            contactsObj: {},
            salesmanObj: {},
            pictureUrl: [],
            tags: []
        };
    },
    loadData(id) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + (window.userData.type == '1' ? '/api/user/demand/orgDemandDetail' : '/api/user/demand/userDemandDetail'),
            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({
                    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));
    },
    offShelf() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/demand/offShelf",
            data: { "id": this.props.data.id }
        }).done(function (data) {
            this.setState({
                loading: false
            });
            if (!data.error.length) {
                message.success('撤销成功!');
                this.setState({
                    visible: false,
                    releaseSubmitVisible: false
                });
                this.props.handleOk();
            } else {
                message.warning(data.error[0].message);
            }
        }.bind(this));
    },
    componentWillMount() {
        if (this.props.data.id) {
            this.loadData(this.props.data.id);
        } else {
            this.state.data = {};
        };
    },
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible) {
            if (nextProps.data.id) {
                this.loadData(nextProps.data.id);
            } else {
                this.state.data = {};
            };
            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 (
            
        )
    }
}));
const DemandDetailForm = Form.create()(React.createClass({
    getInitialState() {
        return {
            visible: false,
            loading: false,
            auditStatus: 0,
            textFileList: [],
            videoFileList: [],
            pictureUrl: [],
            tags: []
        };
    },
    loadData(id) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + (window.userData.type == '1' ? '/api/user/demand/orgDemandDetail' : '/api/user/demand/userDemandDetail'),
            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({
                    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));
    },
    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个!');
                return;
            };
            //url转化
            let thePictureUrl = [];
            if (this.state.pictureUrl.length) {
                let picArr = [];
                this.state.pictureUrl.map(function (item) {
                    if ( item.response && item.response.data && item.response.data.length ){
                        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/user/demand/update' : globalConfig.context + '/api/user/demand/apply',
                    data: {
                        id: this.props.data.id,
                        dataCategory: Number(window.userData.type),
                        serialNumber: this.props.data.serialNumber,
                        name: values.name,
                        keyword: this.state.tags ? this.state.tags.join(",") : [],
                        keywords: this.state.tags,
                        infoSources: 1,
                        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,
                        auditStatus: this.state.auditStatus
                    }
                }).done(function (data) {
                    this.state.auditStatus = 0;
                    this.setState({
                        loading: false
                    });
                    if (!data.error.length) {
                        message.success('保存成功!');
                        this.setState({
                            visible: false
                        });
                        this.props.handleOk();
                    } else {
                        message.warning(data.error[0].message);
                    }
                }.bind(this));
            }
        });
    },
    componentWillMount() {
        if (this.props.data.id) {
            this.loadData(this.props.data.id);
        } 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);
            } 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 (
            
        )
    }
}));
const DemandDetail = React.createClass({
    getInitialState() {
        return {
            visible: false,
            contactsObj: {},
            tabsKey: "1",
            columns: [
                {
                    title: '编号',
                    dataIndex: 'serialNumber',
                    key: 'serialNumber',
                }, {
                    title: '数据类型',
                    dataIndex: 'dataCategory',
                    key: 'dataCategory',
                    render: text => {
                        switch (text) {
                            case "0":
                                return 成果;
                            case "1":
                                return 技术;
                            case "2":
                                return 项目;
                        }
                    }
                }, {
                    title: '名称',
                    dataIndex: 'name',
                    key: 'name',
                }, {
                    title: '关键字',
                    dataIndex: 'keyword',
                    key: 'keyword',
                }, {
                    title: '类型',
                    dataIndex: 'category',
                    key: 'category',
                    render: text => { return getAchievementCategory(text); }
                }, {
                    title: '所有人名称',
                    dataIndex: 'theName',
                    key: 'theName',
                }, {
                    title: '所有人类型',
                    dataIndex: 'ownerType',
                    key: 'ownerType',
                    render: text => {
                        switch (text) {
                            case "0":
                                return 个人;
                            case "1":
                                return 组织
                        }
                    }
                }, {
                    title: '发布时间',
                    dataIndex: 'releaseDateFormattedDate',
                    key: 'releaseDateFormattedDate',
                }
            ],
            dataSource: [],
        };
    },
    getContactsList() {
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/cognizance/getContacts",
            success: function (data) {
                let theOption = [];
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                } else {
                    for (let item in data.data) {
                        let theData = data.data[item];
                        theOption.push(
                            {theData}
                        );
                    };
                };
                this.setState({
                    contactsOption: theOption,
                    contactsObj: data.data || {}
                });
            }.bind(this),
        });
    },
    getTableList() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/user/demand/achievementDemand",
            data: { id: this.props.data.id },
            success: function (data) {
                let theArr = [];
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                } else if (data.data.length) {
                    for (let i = 0; i < data.data.length; i++) {
                        let thisdata = data.data[i];
                        theArr.push({
                            key: i,
                            id: thisdata.id,
                            serialNumber: thisdata.serialNumber,
                            dataCategory: thisdata.dataCategory,
                            name: thisdata.name,
                            keyword: thisdata.keyword,
                            category: thisdata.category,
                            ownerType: thisdata.ownerType,
                            theName: thisdata.username || thisdata.unitName,
                            releaseDate: thisdata.releaseDate,
                            releaseDateFormattedDate: thisdata.releaseDateFormattedDate
                        });
                    };
                };
                this.setState({
                    dataSource: theArr,
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    tableRowClick(record, index) {
        window.open(globalConfig.context + '/portal/detail/achievementDetail.html?id=' + record.id + '&type=' + record.ownerType);
    },
    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);
    },
    componentWillMount() {
        this.getContactsList();
    },
    componentWillReceiveProps(nextProps) {
        if (nextProps.showDesc) {
            this.state.tabsKey = "1";
            this.state.tabBool = true;
        };
        this.state.visible = nextProps.showDesc;
    },
    render() {
        if (this.props.data) {
            return (
                
                    
                         {
                                this.setState({ tabsKey: e });
                                if (e == "2" && this.state.tabBool) {
                                    this.getTableList();
                                    this.state.tabBool = false;
                                };
                            }} >
                            
                                {(() => {
                                    if (this.props.data.id && this.props.data.auditStatus != "0" && this.props.data.auditStatus != "4") {
                                        return 
                                    } else {
                                        return 
                                    }
                                })()}
                            
                            
                                
                            
                        
                    
                 
            );
        } else {
            return 
        }
    },
});
export default DemandDetail;