import React from 'react';
import { Tabs, Table, Icon, Tooltip, Modal, message, AutoComplete, Spin, DatePicker,Upload, Input, InputNumber, Select,TimePicker, Button, Radio, Form, Cascader, Tag, Switch } from 'antd';
import './myClient.less';
import ajax from 'jquery/src/ajax/xhr.js';
import moment from 'moment';
import $ from 'jquery/src/ajax';
import { areaSelect } from '../../NewDicProvinceList';
import { maturityList, innovationList, transferModeList,cityArr ,newFollow,customerStatus,intentionalService,tag} from '../../dataDic';
import { IndustryObject, getIndustryCategory } from '../../DicIndustryList.js';
import { beforeUploadFile, splitUrl, companySearch, getTransferMode, getAchievementCategory, getTechAuditStatus, getDemandType, getMaturity, getInnovation,beforeUpload, getBase64,getsex,getCompanyIntention,getcityArr,getfllowSituation,getcustomerStatue} from '../../tools.js';
import throttle from '../../throttle.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 && 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 (
            <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 key={tag} 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);
    },
    serviceChange(value) {        	
			  console.log(`selected ${value}`);
	},
    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/achievement/uploadPicture"}
                    data={{ 'sign': this.props.pictureSign }}
                    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 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: "post",
            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 = {};
                };
                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);
                };
                console.log(thisData);
            }.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();
                    };
                }.bind(this));
            }
        });
    },
    formSubmit() {
        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/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/findCustomer",
            data: {
                id: 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 },
        }; 
        const selectOption=[];
        intentionalService.map(function (item) {
                    selectOption.push(
                        <Select.Option key={item.id}>{item.name}</Select.Option>
                    )                    
                });
        return (
            <Form horizontal onSubmit={this.handleSubmit} id="demand-form">
                <Spin spinning={this.state.loading}>
                	<div className="clearfix">
                		<FormItem className="half-item"
                            {...formItemLayout}
                            label="客户类型" >
                            <span>{theData._shareType}</span>
                        </FormItem>
                       
                        <div className="clearfix" style={{marginLeft:'40px',marginBottom:'20px',color:'#000000'}}>基本资料:</div>	
               		</div>
                  {/* <FormItem className="half-item"
	                        {...formItemLayout}
	                        label="录入时间" >
	                        {getFieldDecorator('createTime', {
	                        initialValue: theData.createTime ? moment(theData.createTime) : null
	                        })(
	                        <DatePicker />
	                        )}
	                 </FormItem> */} 
                    <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="跟单人" >	                            
	                            <span>{theData.adminName}</span>	                               
	                        </FormItem>
	                
                    <div className="clearfix" style={{marginLeft:'40px',marginBottom:'20px',color:'#000000'}}>公司资料:</div>	                    		                           	                                                       	                                               
                    <div>
                     <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="公司名称" >
	                            {getFieldDecorator('companyName', {
	                                rules: [{ required: true, message: '此项为必填项!' }],
	                                initialValue: theData.companyName
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
	                 <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="公司行业" >
	                            {getFieldDecorator('companyIndustry', {	                                
	                                initialValue: theData.companyIndustry
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>        
                     {/*<FormItem className="half-item"
	                            {...formItemLayout}
	                            label="意向服务" >
	                            {getFieldDecorator('companyIntention', {
	                            	rules: [{ required: true, message: '此项为必填项!' }],
	                                initialValue: theData.companyIntention
	                            })(
	                               <Select placeholder="选择服务类型" >
	                                    {
	                                        intentionalService.map(function (item) {
	                                            return <Select.Option key={item.value} >{item.key}</Select.Option>
	                                        })
	                                    }
	                                </Select>
	                                )}
	                        </FormItem>*/}
                    <FormItem className="half-item"
                        {...formItemLayout}
                        label="意向服务" >                       
						   <Select
                                multiple
                                style={{ width: '80%' }}
                                placeholder="选择服务类型"                               
                                filterOption={(input, option) => { return option.props.children.indexOf(input) >= 0 }}
                                value={this.state.companyIntention}
                                onChange={(pids) => {
                                    this.state.companyIntention = pids;
                                    this.setState({
                                        companyIntention: this.state.companyIntention
                                    })
                                }}
                            >
                                {selectOption}
                            </Select>						
                    </FormItem>
                     <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="地区" >
	                            {getFieldDecorator('locationProvince', {
	                                initialValue: theData.locationProvince
	                            })(
	                                <Select placeholder="选择地区" style={{ width: 160 }} >
	                                    {
	                                        cityArr.map(function (item) {
	                                            return <Select.Option key={item.value} >{item.key}</Select.Option>
	                                        })
	                                    }
	                                </Select>
	                                )}
	                        </FormItem>
	                <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="最新跟进" >
	                            {getFieldDecorator('followSituation', {
	                            	rules: [{ required: true, message: '此项为必填项!' }],
	                                initialValue: getfllowSituation(theData.followSituation)
	                            })(
	                                <Select placeholder="选择跟进进度" style={{ width: 160 }} >
	                                    {
	                                        newFollow.map(function (item) {
	                                            return <Select.Option key={item.value} >{item.key}</Select.Option>
	                                        })
	                                    }
	                                </Select>
	                                )}
	                        </FormItem>
	                 <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="客户状态" >
	                            {getFieldDecorator('customerStatus', {
	                            	rules: [{ required: true, message: '此项为必填项!' }],
	                                initialValue: getcustomerStatue(theData.customerStatus)
	                            })(
	                                <Select placeholder="选择客户状态" style={{ width: 160 }} >
	                                    {
	                                        customerStatus.map(function (item) {
	                                            return <Select.Option key={item.value} >{item.key}</Select.Option>
	                                        })
	                                    }
	                                </Select>
	                                )}
	                        </FormItem>	         
                     <FormItem className="half-item"
		                            {...formItemLayout}
		                            label="详细地址" >
		                            {getFieldDecorator('adress', {		                            	
		                                initialValue: theData.adress
		                            })(
		                                <Input type="text" rows={1}/>
		                                )}
		                    </FormItem>		             
                     <div  className="clearfix">		                        
				                <FormItem
			                        labelCol={{ span: 4 }}
			                        wrapperCol={{ span: 18 }}
			                        label="备注" >
			                        {getFieldDecorator('remarks', {
			                            initialValue: theData.remarks
			                        })(
			                            <Input type="textarea" rows={4} />
			                            )}
			                    </FormItem>
			                </div>
                    </div>  
                    <div className="clearfix" style={{marginLeft:'40px',marginBottom:'20px',color:'#000000'}}>联系资料:</div>
                    <div>
                    <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="姓名" >
	                            {getFieldDecorator('contactName', {
	                                rules: [{ required: true, message: '此项为必填项!' }],
	                                initialValue: theData.contactName
	                            })(
	                                <Input type="text" rows={1}/>
	                                )}
	                        </FormItem>
                     <FormItem className="half-item"
                                {...formItemLayout}
                                label="性别" >
                                {getFieldDecorator('sex', {
                                	rules: [{ required: true, message: '此项为必填项!' }],
                                    initialValue:theData.sex
                                })(
                                    <Radio.Group onChange={(e) => { this.setState({ radios: e.target.value }); }}>
                                        <Radio value="0">男</Radio>
                                        <Radio value="1">女</Radio>
                                    </Radio.Group>
                                    )}
                       		</FormItem>
                    <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="手机号码" >
	                            {getFieldDecorator('telNum', {	
	                            	rules: [{ required: true, message: '此项为必填项!' }],
	                                initialValue: theData.telNum 
	                            })(
	                                <Input type="text" rows={1}/>
	                                )}
	                        </FormItem>
	                 <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="座机号" >
	                            {getFieldDecorator('mobile', {	                              
	                                initialValue: theData.mobile
	                            })(
	                                <Input type="text" rows={1}/>
	                                )}
	                        </FormItem>        
	                <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="QQ号码" >
	                            {getFieldDecorator('qq', {	                              
	                                initialValue: theData.qq
	                            })(
	                                <Input type="text" rows={1}/>
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="邮箱号" >
	                            {getFieldDecorator('email', {	                              
	                                initialValue: theData.email
	                            })(
	                                <Input type="text" rows={1}/>
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="微信" >
	                            {getFieldDecorator('wechat', {	                              
	                                initialValue: theData.wechat
	                            })(
	                                <Input type="text" rows={1}/>
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="部门" >
	                            {getFieldDecorator('depatrment', {	                              
	                                initialValue: theData.depatrment
	                            })(
	                                <Input type="text" rows={1}/>
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="职位" >
	                            {getFieldDecorator('customerPosition', {	                              
	                                initialValue: theData.customerPosition
	                            })(
	                                <Input type="text" rows={1}/>
	                                )}
	                        </FormItem>
	               
 					</div>        
	              	<div className="clearfix" style={{paddingLeft:"200px",marginBottom:"20px"}}>
                       <Button className="set-submit" type="primary" htmlType="submit" id="change_keep" style={{marginTop:"20px"}}>保存</Button>
                       <Button className="set-submit" type="ghost" onClick={this.props.closeDesc} id='change_rem' style={{marginTop:"20px"}}>取消</Button>
                  	</div>
                    
                  {/*  <FormItem wrapperCol={{ span: 12, offset: 4 }}>
                        {theData.auditStatus == 2 ? <Button className="set-submit" type="primary" htmlType="submit">保存</Button> : <span></span>}
                        {theData.auditStatus == 3 ? <Button className="set-submit" type="primary" onClick={() => { this.modifyBroker(); }}>保存</Button> : <span></span>}
                        <Button className="set-submit" type="ghost" onClick={this.props.closeDesc}>取消</Button> */}
                        {/*{window.showAuditStatus ? <Button className="set-submit" loading={this.state.buttonLoading} type="primary" onClick={this.buildMatchList}>生成匹配列表</Button> : <span></span>}*/}
                    {/* </FormItem>  
                    */}
                    
                </Spin>
            </Form >
        )
    }
}));




const AchievementDetailForm = Form.create()(React.createClass({
    getInitialState() {
        return {
            loading: false,
            auditStatus: 0,
            selectOption: [],
            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
            },
            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.transferMode == 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(
                        <Select.Option value={item} key={theData}>{theData}</Select.Option>
                    );
                };
                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) => {                                 
            //url转化
            let theTechnicalPictureUrl = [];
            if (this.state.technicalPictureUrl.length) {
                let picArr = [];
                this.state.technicalPictureUrl.map(function (item) {
                    picArr.push(item.response.data);
                });
                theTechnicalPictureUrl = picArr.join(",");
            };
            let thecoverImg = [];
            if (this.state.coverImg.length) {
                let picArr = [];
                this.state.coverImg.map(function (item) {
                    picArr.push(item.response.data);
                });
                thecoverImg = picArr.join(",");
            };
            let theMaturityPictureUrl = [];
            if (this.state.maturityPictureUrl.length) {
                let picArr = [];
                this.state.maturityPictureUrl.map(function (item) {
                    picArr.push(item.response.data);
                });
                theMaturityPictureUrl = picArr.join(",");
            };
            let companyMore = [];
            if (values.companyIntention.length) {
                let companyList = [];
                values.companyIntention.map(function (item) {
                    companyList.push(item);
                });
                companyMore = companyList.join(",");
            };
            console.log(values.companyIntention)
            if (!err) {
                this.setState({
                    loading: true
                });
                
                $.ajax({
                    method: "POST",
                    dataType: "json",
                    crossDomain: false,
                    url: this.props.data.id ?  globalConfig.context + '/api/admin/customer/updCustomer' : globalConfig.context + '/api/admin/customer/addCustomer',
                    data: {
                        id: this.props.data.id, //编号
                        customerType:values.customerTyp ,//客户信息  1                       
                       // createTime: values.createTime ? values.createTime.format('YYYY-MM-DD') : undefined,//时间 1\                    
                       
                        companyName: values.companyName,//公司名称  1
                        companyIndustry: values.companyIndustry,//公司行业  
                        companyIntention: companyMore,//公司意向1
                        tag: values.tag,
                        locationProvince: values.locationProvince,//省份1
                        adress: values.adress,//详细地址1
                        remarks: values.remarks,//备注1
                        followSituation: values.followSituation,//最新跟进1
                        customerStatus: values.customerStatus,//客户状态1
                        name: values.name,//客户姓名1                        
                        mobile: values.mobile,//座机1
                        telNum: values.telNum,//手机号码1
                        sex: values.sex,//性别1
                        customerPosition: values.customerPosition,//职位1
                        wechat: values.wechat,//微信号1
                        qq: values.qq,//qq     1                 
                        depatrment: values.depatrment,//部门             1
                        email: values.email,//邮箱     1                   
                       	shareType:0,
                        followDates:values.createTime ? values.createTime.format('YYYY-MM-DD'):undefined,//+" "+(values.createTim ? values.createTim.format('YYYY:MM:DD'):undefined),//时间,
                        primaryFlg:0,
                    }
                }).done(function (data) {
                    this.state.auditStatus = 0;
                    this.setState({
                        loading: false
                    });
                    if (!data.error.length) {
                        message.success('保存成功！');
                        this.props.handleOk();
                    } 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();
        };
    },
   
    render() {
        const theData = this.state.data || {};
        const { getFieldDecorator } = this.props.form;
        const FormItem = Form.Item
        const formItemLayout = {
            labelCol: { span: 8 },
            wrapperCol: { span: 14 },
        };       
        const { RangePicker } = DatePicker;
        return (
            <Form horizontal onSubmit={this.handleSubmit} id="demand-form">
                <Spin spinning={this.state.loading}>
                    <div className="clearfix">
                    	<FormItem className="half-item"
		                            {...formItemLayout}
		                            label="客户类型" >
		                            {getFieldDecorator('customerTyp', {
		                                rules: [{ required: true, message: '此项为必填项!' }],
		                                initialValue: theData.customerTyp
		                            })(
		                                <Select placeholder="选择客户类型" style={{ width: 160 }} >
		                                    <Select.Option value="0" >个人客户</Select.Option>
		                                    <Select.Option value="1" >公司客户</Select.Option>                                   
		                                </Select>
		                                )}
		                </FormItem>
                    	<div className="clearfix" style={{marginLeft:'40px',marginBottom:'20px',color:'#000000'}}>基本资料:</div>	                    	                       
                        <div>	                    	
		                <FormItem className="half-item"
                            {...formItemLayout}
                            label="录入时间" >
                            {getFieldDecorator('createTime', {
                            	rules: [{ required: true, message: '此项为必填项!' }],
                                initialValue: theData.createTime ? moment(theData.createTime) : null
                            })(
                                <DatePicker />
                                )}	 
                               
	                    </FormItem> 
	                {/*    <FormItem className="half-item" style={{marginLeft:'-160px'}}
	                            {...formItemLayout}
	                            label="" >
	                                                        
	                    </FormItem> */}
	                      {/*    <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="跟单人" >
	                            {getFieldDecorator('ownerId', {
	                                initialValue: theData.ownerId
	                            })(
	                                <Input />
	                                )}
	                        </FormItem> */}
                        </div>
                        <div className="clearfix" style={{marginLeft:'40px',marginBottom:'20px',color:'#000000'}}>公司资料:</div>	                    		                           	                                                       	                                               
                        <div>
                            <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="公司名称" >
	                            {getFieldDecorator('companyName', {
	                                rules: [{ required: true, message: '此项为必填项!' }],
	                                initialValue: theData.companyName
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="公司行业" >
	                            {getFieldDecorator('companyIndustry', {	                                
	                                initialValue: theData.companyIndustry
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>	                     	                        
			                <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="地区" >
	                            {getFieldDecorator('locationProvince', {
	                                initialValue: getcityArr(theData.locationProvince)
	                            })(
	                                <Select placeholder="选择地区" style={{ width: 160 }} >
	                                    {
	                                        cityArr.map(function (item) {
	                                            return <Select.Option key={item.value} >{item.key}</Select.Option>
	                                        })
	                                    }
	                                </Select>
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="最新跟进" >
	                            {getFieldDecorator('followSituation', {
	                            	rules: [{ required: true, message: '此项为必填项!' }],
	                                initialValue: getfllowSituation(theData.followSituation)
	                            })(
	                                <Select placeholder="选择跟进进度" style={{ width: 160 }} >
	                                    {
	                                        newFollow.map(function (item) {
	                                            return <Select.Option key={item.value} >{item.key}</Select.Option>
	                                        })
	                                    }
	                                </Select>
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="客户状态" >
	                            {getFieldDecorator('customerStatus', {
	                            	rules: [{ required: true, message: '此项为必填项!' }],
	                                initialValue: getcustomerStatue(theData.customerStatus)
	                            })(
	                                <Select placeholder="选择客户状态" style={{ width: 160 }} >
	                                    {
	                                        customerStatus.map(function (item) {
	                                            return <Select.Option key={item.value} >{item.key}</Select.Option>
	                                        })
	                                    }
	                                </Select>
	                                )}
	                        </FormItem>	                       
	                        <FormItem className="half-item"
		                            {...formItemLayout}
		                            label="详细地址" >
		                            {getFieldDecorator('adress', {		                            	
		                                initialValue: theData.adress
		                            })(
		                                <Input />
		                                )}
		                    </FormItem>
		                     <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="标签" >
	                            {getFieldDecorator('tag', {	                            	
	                                initialValue: theData.tag
	                            })(
                               <Select placeholder="选择客户标签" >
                                    {
                                        tag.map(function (item) {
                                            return <Select.Option key={item.key} >{item.key}</Select.Option>
                                        })
                                    }
                                </Select>
	                                )}
	                        </FormItem>
	                        <div  className="clearfix" >	
		                        <FormItem className="half-item" style={{marginLeft:'80px'}}
			                         labelCol={{ span: 4 }}
			                        wrapperCol={{ span: 18 }}
			                        label="意向服务" > 
			                        {getFieldDecorator('companyIntention', {
			                            	rules: [{ required: true, message: '此项为必填项!' }],	
			                            	
	                                })(
									   <Select 
			                                multiple	
			                                style={{width:'600px'}}
			                                placeholder="选择服务类型"                               
			                                filterOption={(input, option) => { return option.props.children.indexOf(input) >= 0 }}
			                                value={this.state.companyIntention}
			                                onChange={(pids) => {
			                                    this.state.companyIntention = pids;
			                                    this.setState({
			                                        companyIntention: this.state.companyIntention
			                                    })
			                                }}
			                            >
			                                {
		                                        intentionalService.map(function (item) {
		                                            return <Select.Option key={item.value} >{item.key}</Select.Option>
		                                        })
		                                    }
			                            </Select>)}					
			                    </FormItem>
		                    </div>
	                        <div  className="clearfix">		                        
				                <FormItem
			                        labelCol={{ span: 4 }}
			                        wrapperCol={{ span: 18 }}
			                        label="备注" >
			                        {getFieldDecorator('remarks', {
			                            initialValue: theData.remarks
			                        })(
			                            <Input type="textarea" rows={4} />
			                            )}
			                    </FormItem>
			                </div>
                        </div>  
                        <div className="clearfix" style={{marginLeft:'40px',marginBottom:'20px',color:'#000000'}}>联系资料:</div>
                        <div>
                        	<FormItem className="half-item"
	                            {...formItemLayout}
	                            label="姓名" >
	                            {getFieldDecorator('name', {
	                                rules: [{ required: true, message: '此项为必填项!' }],
	                                initialValue: theData.name
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
                                {...formItemLayout}
                                label="性别" >
                                {getFieldDecorator('sex', {
                                	rules: [{ required: true, message: '此项为必填项!' }],
                                    initialValue: getsex(theData.sex)
                                })(
                                    <Radio.Group>
                                        <Radio value="0">男</Radio>
                                        <Radio value="1">女</Radio>
                                    </Radio.Group>
                                    )}
                       		</FormItem>
                       		<FormItem className="half-item"
	                            {...formItemLayout}
	                            label="手机号码" >
	                            {getFieldDecorator('telNum', {	
	                            	
	                                initialValue: theData.telNum 
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="座机号" >
	                            {getFieldDecorator('mobile', {	                              
	                                initialValue: theData.mobile
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="QQ号码" >
	                            {getFieldDecorator('qq', {	                              
	                                initialValue: theData.qq
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="邮箱号" >
	                            {getFieldDecorator('email', {	                              
	                                initialValue: theData.email
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="微信" >
	                            {getFieldDecorator('wechat', {	                              
	                                initialValue: theData.wechat
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="部门" >
	                            {getFieldDecorator('depatrment', {	                              
	                                initialValue: theData.depatrment
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
	                        <FormItem className="half-item"
	                            {...formItemLayout}
	                            label="职位" >
	                            {getFieldDecorator('customerPosition', {	                              
	                                initialValue: theData.customerPosition
	                            })(
	                                <Input />
	                                )}
	                        </FormItem>
                        </div>                        
        			</div>
                    <FormItem wrapperCol={{ span: 12, offset: 4 }}>
                        <Button className="set-submit" type="primary" htmlType="submit">保存</Button>
                        {/*<Button className="set-submit" type="ghost" onClick={(e) => { this.state.auditStatus = 1; }} htmlType="submit">发布</Button>*/}
                        <Button className="set-submit" type="ghost" onClick={this.props.closeDesc}>取消</Button>
                    </FormItem>
                   
                </Spin>
            </Form >
        )
    }
}));

const AchievementDetail = React.createClass({
    getInitialState() {
        return {
            visible: false,
            tabsKey: 1,
            loading: false,
            columns: [
                {
                    title: '客户信息',
                    dataIndex: 'id',
                    key: 'id',
                    render: text => {
                        switch (text) {
                            case "0":
                                return <span>个人客户</span>;
                            case "1":
                                return <span>公司客户</span>;                           
                        }
                    }
                }, {
                    title: '名称',
                    dataIndex: 'companyNmae',
                    key: 'companyNmae',
                }, {
                    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: [],
        };
    },
    
    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,
                            createTime: thisdata.createTime,
                            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,
                        });
                    };
                };
                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);
    },
    
    componentWillReceiveProps(nextProps) {
        if (!this.state.visible && nextProps.showDesc) {
            this.state.tabsKey = "1";
        };
        this.state.visible = nextProps.showDesc;
    },
    render() {
        if (this.props.data) {
            return (
                <div className="patent-desc">
                    <Modal maskClosable={false} visible={this.state.visible}
                        onOk={this.checkPatentProcess} onCancel={this.handleCancel}
                        width='1000px'
                        footer=''
                        className="admin-desc-content">
                        <Spin spinning={this.state.loading}>
                            <Tabs activeKey={this.state.tabsKey}
                                onChange={(e) => {
                                    this.setState({ tabsKey: e });
                                    if (e == "2") {
                                        this.getTableList();
                                    };
                                }} >
                                <Tabs.TabPane tab="客户详情" key="1">
                                    {(() => {
                                        if (this.props.data.id && this.props.data.auditStatus != "0" && this.props.data.auditStatus != "4") {
                                            return <AchievementDetailShow
                                                data={this.props.data}
                                                detailApiUrl={this.props.detailApiUrl}
                                                techBrodersOption={this.state.techBrodersOption}
                                                techBrodersObj={this.state.techBrodersObj}
                                                closeDesc={this.handleCancel}
                                                visible={this.state.visible}
                                                handleOk={this.handleOk} />
                                        } else {
                                            return <AchievementDetailForm
                                                data={this.props.data}
                                                detailApiUrl={this.props.detailApiUrl}
                                                achievementCategoryOption={this.props.achievementCategoryOption}
                                                techBrodersObj={this.state.techBrodersObj}
                                                closeDesc={this.handleCancel}
                                                visible={this.state.visible}
                                                handleOk={this.handleOk} />
                                        };
                                    })()}
                                </Tabs.TabPane>                                
                            </Tabs>
                        </Spin>
                    </Modal>
                </div>
            );
        } else {
            return <div></div>
        }
    },
});


export default AchievementDetail;