import React from 'react';
import { Tabs, Table, Icon, Tooltip, Modal, message, AutoComplete, Spin, Upload, Input, InputNumber, Select, Button, Radio, Form, Cascader, Tag, Switch } from 'antd';
import './techAchievement.less';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import { maturityList, innovationList, transferModeList } from '../../dataDic';
import { IndustryObject, getIndustryCategory } from '../../DicIndustryList.js';
import { beforeUploadFile, splitUrl, companySearch, getTransferMode, getAchievementCategory, getTechAuditStatus, getDemandType, getMaturity, getInnovation,beforeUpload, getBase64,getboutique } from '../../tools.js';
import throttle from '../../throttle.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 AchievementDetailShow = Form.create()(React.createClass({
    getInitialState() {
        return {
            loading: false,
            buttonLoading: false,
            contactsObj: {},
            data: {},
            tags: [],
            technicalPictureUrl: [],
            coverImg: [],
            maturityPictureUrl: [],           
            textFileList: [],
            techPlanFileList: [],
            businessPlanFileList: []
        };
    },
    loadData(id, detailApiUrl) {
        this.setState({
            loading: true
        });
      
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + detailApiUrl,
            data: {
                id: id,
                ownerType:this.props.data.ownerType
            },
            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,
                    orgDisplay: thisData.ownerType,
                    switchValue: Boolean(!thisData.ownerId),
                    radios:thisData.hot==='1'?true:false,
                    tags: thisData.keyword ? (thisData.keyword.replace(/(,|、)/g, ",")).split(',') : [],
                    technicalPictureUrl: thisData.technicalPictureUrl ? splitUrl(thisData.technicalPictureUrl, ',', globalConfig.avatarHost + '/upload') : [],
                    coverImg: thisData.coverImg ? splitUrl(thisData.coverImg, ',', globalConfig.avatarHost + '/upload') : [],
                    maturityPictureUrl: thisData.maturityPictureUrl ? splitUrl(thisData.maturityPictureUrl, ',', globalConfig.avatarHost + '/upload') : [],                  
                });
                if (thisData.ownerId) {
                    this.getContactsList(thisData.ownerId);
                };
            }.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/admin/achievement/offShelf",
            data: { "id": this.props.data.id }
        }).done(function (data) {
            if (!data.error.length) {
                message.success('撤销成功!');
                this.setState({
                    visible: false,
                    releaseSubmitVisible: false
                });
                this.props.handleOk();
            } else {
                message.warning(data.error[0].message);
            }
        }.bind(this));
    },
    modifyBroker() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.setState({
                    loading: true
                });
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + '/api/admin/audit/modifyAchievementTechBroker',
                    data: {
                        id: this.props.data.id,
                        techBrokerId: values.modifyTechBrokerId
                    }
                }).done(function (data) {
                    this.state.auditStatus = 0;
                    this.setState({
                        loading: false
                    });
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    } else {
                        message.success('保存成功!');
                        this.props.handleOk();
                        this.componentWillMount();
                    };
                }.bind(this));
            }
        });
    },
    formSubmit() {
        this.props.form.validateFields((err, values) => {
            if (values.auditStatus == 3 && !values.techBrokerId) {
                message.warning('必须选择一个技术经纪人!');
                return
            };
            if (!err) {
                this.setState({
                    loading: true
                });
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: globalConfig.context + '/api/admin/audit/achievement',
                    data: {
                        id: this.props.data.id,
                        techBroderId: values.techBrokerId,
                        auditStatus: values.auditStatus
                    }
                }).done(function (data) {
                    this.state.auditStatus = 0;
                    this.setState({
                        loading: false
                    });
                    if (!data.error.length) {
                        message.success('保存成功!');
                        this.setState({
                            formSubmitVisible: false
                        });
                        this.props.handleOk();
                    } else {
                        message.warning(data.error[0].message);
                    };
                }.bind(this));
            }
        });
    },
    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (values.auditStatus == 4) {
                this.setState({
                    formSubmitVisible: true
                });
            } else {
                this.formSubmit();
            };
        });
    },
    buildMatchList() {
        this.setState({
            buttonLoading: true
        });
        $.ajax({
            method: "POST",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/achievement/matchDemand',
            data: {
                id: this.props.data.id,
            }
        }).done(function (data) {
            this.setState({
                buttonLoading: false
            });
            if (!data.error.length) {
                message.success('匹配完成!匹配到' + data.data + '条记录');
            } else {
                message.warning(data.error[0].message);
            };
        }.bind(this));
    },
    getContactsList(theUid) {
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/getContacts",
            data: {
                uid: theUid
            },
            success: function (data) {
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                        return;
                    };
                } else {
                    this.setState({
                        contactsObj: data.data || {}
                    });
                };
            }.bind(this),
        });
    },
    componentWillMount() {
    	
        this.loadData(this.props.data.id, this.props.detailApiUrl);
    },
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible) {
            this.loadData(nextProps.data.id, nextProps.detailApiUrl);
            this.state.textFileList = [];
            this.state.techPlanFileList = [];
            this.state.businessPlanFileList = [];
            this.props.form.resetFields();
        };
    },
    render() {
        const theData = this.state.data || {};
        const { getFieldDecorator } = this.props.form;
        const FormItem = Form.Item
        const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 14 },
        };
        return (
            
        )
    }
}));
const AchievementDetailForm = Form.create()(React.createClass({
    getInitialState() {
        return {
            loading: false,
            auditStatus: 0,
            textFileList: [],
            switchValue: false,
            radios: false,
            techPlanFileList: [],
            data: {},
            tags: [],
            technicalPictureUrl: [],
            coverImg: [],
            maturityPictureUrl: [],            
            businessPlanFileList: [],
            dataSource: [],
        };
    },
    loadData(id, detailApiUrl) {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + detailApiUrl,
            data: {
                id: id,
                ownerType:this.props.data.ownerType
            },
            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,
                    orgDisplay: thisData.ownerType,
                    switchValue: Boolean(!thisData.ownerId),
                    radios: thisData.hot == '1' ? true : false,
                    transferPriceDis: thisData.bargainingMode == 1 ? true : false,
                    tags: thisData.keyword ? (thisData.keyword.replace(/(,|、)/g, ",")).split(',') : [],
                    technicalPictureUrl: thisData.technicalPictureUrl ? splitUrl(thisData.technicalPictureUrl, ',', globalConfig.avatarHost + '/upload') : [],
                    coverImg: thisData.coverImg ? splitUrl(thisData.coverImg, ',', globalConfig.avatarHost + '/upload') : [],
                    maturityPictureUrl: thisData.maturityPictureUrl ? splitUrl(thisData.maturityPictureUrl, ',', globalConfig.avatarHost + '/upload') : [],                                      
                });
                if (thisData.ownerType == "1" && thisData.ownerId) {
                    this.getContactsList(thisData.ownerId);
                };
            }.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(
                        {theData}
                    );
                };
                this.setState({
                    contactsOption: theOption
                });
            }.bind(this),
        });
    },
    getTagsArr(e) {
        this.setState({ tags: e });
    },
    getMaturityPictureUrl(e) {
        this.setState({ maturityPictureUrl: e });
    },
    getTechnicalPictureUrl(e) {
        this.setState({ technicalPictureUrl: e });
    },
    getcoverImg(e) {
        this.setState({coverImg: e });
    },
    handleSearch(e) {
        if (this.props.detailApiUrl.indexOf('org') != -1) {
            $.ajax({
                method: "get",
                dataType: "json",
                crossDomain: false,
                url: globalConfig.context + "/api/admin/achievement/orgOwner",
                data: { name: e },
                success: function (data) {
                    let theArr = [];
                    let theObj = {};
                    if (!data.data) {
                        if (data.error && data.error.length) {
                            message.warning(data.error[0].message);
                        };
                    } else if (!$.isEmptyObject(data.data)) {
                        data.data.map(function (item) {
                            theArr.push(item.unitName);
                            theObj[item.unitName] = item.uid;
                        });
                    };
                    this.setState({
                        dataSource: theArr,
                        dataSourceObj: theObj
                    });
                }.bind(this),
            });
        } else {
            $.ajax({
                method: "get",
                dataType: "json",
                crossDomain: false,
                url: globalConfig.context + "/api/admin/achievement/userOwner",
                data: { name: e },
                success: function (data) {
                    let theArr = [];
                    let theObj = {};
                    if (!data.data) {
                        if (data.error && data.error.length) {
                            message.warning(data.error[0].message);
                        };
                    } else if (!$.isEmptyObject(data.data)) {
                        for (let item in data.data) {
                            theArr.push(data.data[item]);
                            theObj[data.data[item]] = item;
                        };
                    };
                    this.setState({
                        dataSource: theArr,
                        dataSourceObj: theObj
                    });
                }.bind(this),
            });
        };
    },
    handleSubmit(e) {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            //keyword长度判断
           
            if ((this.state.tags ? this.state.tags.length : this.props.tags.length) < 3) {
                message.warning('关键词数量不能小于3个!');
                return;
            };
            if (values.bargainingMode == 1 && !values.transferPrice) {
                message.warning('议价方式为[ 定价 ]时, [ 转让价格 ]不能为空!');
                return;
            }
            if(values.field[0]==undefined){
            	message.warning('应用领域不能为空!')
            	return false;
            }
            //url转化
            let theTechnicalPictureUrl = [];
            if (this.state.technicalPictureUrl.length) {
                let picArr = [];
                this.state.technicalPictureUrl.map(function (item) {
                    if ( item.response && item.response.data && item.response.data.length ){
                        picArr.push(item.response.data);
                    }
                });
                theTechnicalPictureUrl = picArr.join(",");
            };
            let thecoverImg = [];
            if (this.state.coverImg.length) {
                let picArr = [];
                this.state.coverImg.map(function (item) {
                    if ( item.response && item.response.data && item.response.data.length ){
                        picArr.push(item.response.data);
                    }
                });
                thecoverImg = picArr.join(",");
            };
            let theMaturityPictureUrl = [];
            if (this.state.maturityPictureUrl.length) {
                let picArr = [];
                this.state.maturityPictureUrl.map(function (item) {
                    if ( item.response && item.response.data && item.response.data.length ){
                        picArr.push(item.response.data);
                    }
                });
                theMaturityPictureUrl = picArr.join(",");
            };
            if (!err) {
                this.setState({
                    loading: true
                });
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: this.props.data.id ? globalConfig.context + '/api/admin/achievement/update' : globalConfig.context + '/api/admin/achievement/apply',
                    data: {
                        id: this.props.data.id,
                        dataCategory: values.dataCategory,
                        serialNumber: this.props.data.serialNumber,
                        name: values.name,
                        keyword: this.state.tags ? this.state.tags.join(",") : this.props.tags.join(","),
                        keywords: this.state.tags ? this.state.tags : this.props.tags,
                        category: values.category,
                        summary: values.summary,
                        introduction: values.introduction,
                        remark: values.remark,
                        technicalPictureUrl: theTechnicalPictureUrl,
                        coverImg: thecoverImg,
                        fieldA: values.field ? values.field[0] : undefined,
                        fieldB: values.field ? values.field[1] : undefined,
                        maturity: values.maturity,
                        maturityPictureUrl: theMaturityPictureUrl,
                        maturityTextFileUrl: this.state.maturityTextFileUrl,
                        maturityVideoUrl: values.maturityVideoUrl,
                        innovation: values.innovation,
                        //
                        switchSign: this.state.switchValue ? 1 : 0,
                        //
                        ownerId: !this.state.switchValue ? (this.state.dataSourceObj ? this.state.dataSourceObj[values.iOwnerName] : this.state.data.ownerId) : undefined,
                        contacts: !this.state.switchValue ? values.contacts : undefined,
                        ownerType: this.state.orgDisplay,//this.props.detailApiUrl.indexOf('org') != -1 ? 1 : 0,
                        //自定义
                        ownerName: this.state.switchValue ? values.ownerName : undefined,
                        ownerIdNumber: this.state.switchValue ? values.ownerIdNumber : undefined,
                        ownerMobile: this.state.switchValue ? values.ownerMobile : undefined,
                        ownerEmail: this.state.switchValue ? values.ownerEmail : undefined,
                        ownerPostalAddress: this.state.switchValue ? values.ownerPostalAddress : undefined,
                        //
                        cooperationMode: values.cooperationMode,
                        transferMode: values.transferMode,
                        bargainingMode: values.bargainingMode,
                        transferPrice: values.transferPrice,
                        technicalScene: values.technicalScene,
                        breakthrough: values.breakthrough,
                        patentCase: values.patentCase,
                        awards: values.awards,
                        teamDes: values.teamDes,
                        parameter: values.parameter,
                        releaseStatus: values.releaseStatus,
                        techPlanUrl: this.state.techPlanUrl,
                        businessPlanUrl: this.state.businessPlanUrl,
                        auditStatus: this.state.auditStatus,                       
                        boutique: values.boutique,
                        internationalFlag:values.internationalFlag,
                        hot: values.hot,      
                        
                    }
                }).done(function (data) {
                    this.state.auditStatus = 0;
                    this.setState({
                        loading: false
                    });
                    if (!data.error.length) {
                        message.success('保存成功!');
                        this.props.handleOk();
                        this.componentWillMount();
                    } else {
                        message.warning(data.error[0].message);
                    }
                }.bind(this));
            }
        });
    },
    componentWillMount() {
        this.state.therottleSearch = throttle(this.handleSearch, 1000, { leading: false }).bind(this);
        if (this.props.data && this.props.data.id) {
            this.loadData(this.props.data.id, this.props.detailApiUrl);
        };
    },
    componentWillReceiveProps(nextProps) {
        if (!this.props.visible && nextProps.visible) {
            if (nextProps.data && nextProps.data.id) {
                this.loadData(nextProps.data.id, nextProps.detailApiUrl);
            };
            this.state.data = {};
            this.state.tags = [];
            this.state.switchValue = false;
            this.state.radios = false;
            this.state.technicalPictureUrl = [];
            this.state.coverImg = [];
            this.state.maturityPictureUrl = [];
            this.state.textFileList = [];
            this.state.techPlanFileList = [];
            this.state.businessPlanFileList = [];
            this.props.form.resetFields();
            this.state.orgDisplay=undefined;
        };
    },
    render() {
        const theData = this.state.data || {};
        const { getFieldDecorator } = this.props.form;
        const FormItem = Form.Item
        const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 14 },
        };
		return (
            
        )
    }
}));
const AchievementDetail = React.createClass({
    getInitialState() {
        return {
            visible: false,
            tabsKey: 1,
            loading: false,
            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: 'demandType',
                    key: 'demandType',
                    render: text => { return getDemandType(text); }
                }, {
                    title: '所有人名称',
                    dataIndex: 'theName',
                    key: 'theName',
                }, {
                    title: '发布时间',
                    dataIndex: 'releaseDateFormattedDate',
                    key: 'releaseDateFormattedDate',
                }, {
                    title: '有效期限',
                    dataIndex: 'validityPeriodFormattedDate',
                    key: 'validityPeriodFormattedDate',
                },
            ],
            dataSource: [],
        };
    },
    getTechBrodersList() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/audit/techBroders",
            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(
                        {data.data[item]}
                    )
                };
                this.setState({
                    techBrodersOption: theArr,
                    techBrodersObj: data.data
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    getTableList() {
        this.setState({
            loading: true
        });
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/achievement/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,
                            demandType: thisdata.demandType,
                            theName: thisdata.username || thisdata.unitName,
                            releaseDateFormattedDate: thisdata.releaseDateFormattedDate,
                            validityPeriodFormattedDate: thisdata.validityPeriodFormattedDate,
                            coverImg: thisdata.coverImg,
                            hot: thisdata.hot,
                            internationalFlag:thisdata.internationalFlag,
                        });
                    };
                };
                this.setState({
                    dataSource: theArr,
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },
    tableRowClick(record, index) {
        window.open(globalConfig.context + '/portal/detail/demandDetail.html?id=' + record.id + '&type=' + record.dataCategory);
    },
    handleCancel(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false);
    },
    handleOk(e) {
        this.setState({
            visible: false,
        });
        this.props.closeDesc(false, true);
    },
    componentWillMount() {
        this.getTechBrodersList();
    },
    componentWillReceiveProps(nextProps) {
        if (!this.state.visible && nextProps.showDesc) {
            this.state.tabsKey = "1";
        };
        this.state.visible = nextProps.showDesc;
    },
    render() {
        if (this.props.data) {
            return (
                
                    
                        
                             {
                                    this.setState({ tabsKey: e });
                                    if (e == "2") {
                                        this.getTableList();
                                    };
                                }} >
                                
                                    {(() => {
                                        if (this.props.data.id && this.props.data.auditStatus != "0" && this.props.data.auditStatus != "4") {
                                            return 
                                        } else {
                                            return 
                                        };
                                    })()}
                                
                                
                                    
                                
                            
                        
                    
                 
            );
        } else {
            return 
        }
    },
});
export default AchievementDetail;