import React from 'react';
import { AutoComplete, Icon, Button, Input, InputNumber, Select, Spin, Table, message, Modal, Row, Col, DatePicker,Switch,Upload} from 'antd';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import moment from 'moment';
import './myClient.less';
const { Column, ColumnGroup } = Table;
import { orderStatusList,cityArr,customerStatus,intentionalService,newFollow} from '../../dataDic.js';
import { beforeUploadFile,getOrderStatus, getSearchUrl,getcustomerTyp,getcityArr,getcustomerStatue,getCompanyIntention,getfllowSituation,getsex} from '../../tools.js';

//查询功能和初始列表

const PublicCustomer = React.createClass({
    loadData(pageNo, detailApiUrl) {    	
        this.state.data = [];
        this.setState({
            loading: true
        });        
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,          
            url:globalConfig.context +'/api/admin/customer/listCompanyCustomer',
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,               
                companyName: this.state.companyNamet, //名称1                
				customerType: this.state.customerTypet, //客户类型1
              	locationProvince:this.state.locationProvincet,//地区
				customerStatus:this.state.customerStatust,//客户状态1
				contactName:this.state.contactNamet,//联系人姓名1							
				contactTel:this.state.contactTelt,//联系人手机
				companyIntention:this.state.companyIntentiont,//意向服务
                followSituation:this.state.followSituationt,//最新跟进进度
				//releaseDateStartDate: this.state.releaseDate[0],
                //releaseDateEndDate: this.state.releaseDate[1],			
            },
            success: function (data) {            	
                let theArr = [];
                if (!data.data || !data.data.list) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };                   
                } else {                	
                    for (let i = 0; i < data.data.list.length; i++) {
                        let thisdata = data.data.list[i];                       
                        theArr.push({
                            key: i,
                            id: thisdata.id,                                                  
                            companyName:thisdata.companyName,//公司名称
                            customerType:thisdata.customerType,
                            _customerType:thisdata._customerType,//客户类型
                            locationProvince:thisdata.locationProvince,//地区                        
                            contactName:thisdata.contactName, //联系人姓名
                            telNum:thisdata.telNum,//手机号
                            _customerStatus:thisdata._customerStatus,//客户状态
                            _companyIntention:thisdata._companyIntention,//意向服务
                            _followSituation:thisdata._followSituation,//最新跟进
                            customerStatus:thisdata.customerStatus,//客户状态
                            companyIntention:thisdata.companyIntention,//意向服务
                            followSituation:thisdata.followSituation,//最新跟进
                            adminName:thisdata.adminName,     //跟进人          
                            followDate:thisdata.followDate,                                                                                   
                        });
                    };
                   
                    this.state.pagination.current = data.data.pageNo;
                    this.state.pagination.total = data.data.totalCount;
                };   
                
                this.setState({
                    dataSource: theArr,
                    pagination: this.state.pagination
                });             
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    },    
    //查看详情
    Detailload(deletedIds){    	
    	$.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/customer/findAllCustomerDetails',
            data: {
                id: deletedIds
            },
            success: function (data) {
                let thisData = data.data; 
                let companyArr=[]; 	
                let companyText=[];
   				let companyString=thisData.companyIntention;				
   				companyArr=companyString.split(",")    				
   				for(var i=0;i<companyArr.length;i++){
   					companyText+=getCompanyIntention(companyArr[i])+"-"
   				}
                if (!thisData) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };
                    thisData = {};
                };
                this.setState({
                	companyIntention:companyText,
                    data: thisData,
                   	followSituation:thisData.followSituation,
		            		customerStatus:thisData.customerStatus,		            		
                });                            
            }.bind(this),
        }).always(function () {
            this.setState({           	
                loading: false
            });
        }.bind(this));  
    },
    getInitialState() {
        return {
            searchMore: true,
            searchType: 0,
            validityPeriodDate: [],
            releaseDate: [],
            selectedRowKeys: [],
            selectedRows: [],
            loading: false,
            pagination: {
                defaultCurrent: 1,
                defaultPageSize: 10,
                showQuickJumper: true,
                pageSize: 10,
                onChange: function (page) {
                    this.loadData(page);
                }.bind(this),
                showTotal: function (total) {
                    return '共' + total + '条数据';
                }
            },
                contactInformation:[
           			 {
				  title: '姓名',
				  dataIndex: 'contactName',
				  key: 'contactName'
						  
					},{
						  title: '性别',
						  dataIndex: 'sex',
						  key: 'sex',
						  render: text => { return getsex(text); }
					},
					{
						  title: '手机号码',
						  dataIndex: 'telNum',
						  key: 'telNum'	 
					},{
						  title: '座机号',
						  dataIndex: 'mobile',
						  key: 'mobile'	 
					},{
						  title: 'QQ号码',
						  dataIndex: 'qq',
						  key: 'qq'	 
					},{
						  title: '邮箱号',
						  dataIndex: 'email',
						  key: 'email'	 
					},{
						  title: '微信',
						  dataIndex: 'wechat',
						  key: 'wechat'	 
					},{
						  title: '部门',
						  dataIndex: 'depatrment',
						  key: 'depatrment'	 
					},{
						  title: '职位',
						  dataIndex: 'customerPosition',
						  key: 'customerPosition'	 
					},
                  ],
            columns: [               
                {
                    title: '公司名称',
                    dataIndex: 'companyName',
                    key: 'companyName',
                }, {
                    title: '客户类型',
                    dataIndex: '_customerType',
                    key: '_customerType',
                    //render: text => { return getcustomerTyp(text); }
                }, {
                    title: '地区',
                    dataIndex: 'locationProvince',
                    key: 'locationProvince',
                    render: text => { return getcityArr(text); }
                }, {
                    title: '联系人姓名',
                    dataIndex: 'contactName',
                    key: 'contactName',                    
                }, 
                {
                    title: '手机号',
                    dataIndex: 'telNum',
                    key:'telNum',                   
                },
                 {
                    title: '客户状态',
                    dataIndex: '_customerStatus',
                    key: '_customerStatus',
                  //render: text => { return getcustomerStatue(text) }
                },
                {
                    title: '意向服务',
                    dataIndex: '_companyIntention',
                    key: '_companyIntention',
                    //render: text => { return getCompanyIntention(text) }
                },
                 {
                    title: '最新跟进',
                    dataIndex: '_followSituation',
                    key: '_followSituation',
                    //render: text => { return getfllowSituation(text) }
                },
                 {
                    title: '跟单人',
                    dataIndex: 'adminName',
                    key: 'adminName',
                },
                {
                    title: '时间',
                    dataIndex: 'followDate',
                    key: 'followDate',
                }
            ],
            dataSource: [],
            searchTime: [],
        };
    },
    componentWillMount() {
        let theArr = [];
        customerStatus.map(function (item) {
            theArr.push(
                <Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
            )
        });            
               
        let intentionalArr = [];
        intentionalService.map(function (item) {
            intentionalArr.push(
                <Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
            )
        });   
        let newArr = [];
        newFollow.map(function (item) {
            newArr.push(
                <Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
            )
        });   
				let auditArr = [];
        cityArr.map(function (item) {
            auditArr.push(
                <Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
            )
        }); 
        this.state.customerStatuarr = theArr;               
        this.state.intentionalOption = intentionalArr;
        this.state.newOption = newArr;
        this.state.auditStatusOption = auditArr;
        
        if (window.location.search) {
            let theObj = getSearchUrl(window.location.search);
            if (theObj.rid) {
                theObj.id = theObj.rid;
                if (theObj.rid != 'null') {
                    this.tableRowClick(theObj);
                };
            };
        };       
        this.loadData();        
    },
    tableRowClick(record) {
        this.state.RowData = record;
        this.setok(record.id);       
        this.setState({
        	hids:record.id
        })
    },
    //点击消失函数
	setModal3Visiblecancel(e) {
	    this.setState({ 
	    	modal3Visible:false
	    });	   	    
	},
	setModal4Visiblecancel(e) {
	    this.setState({ 
	    	modal4Visible:false
	    });	   	    
	},
   
    closeDesc(e, s) {
        this.state.showDesc = e;
        if (s) {
            this.loadData();
        };
    },
    search() {
        this.loadData();
    },
    reset() {
    	this.state.companyNamet='';  
    	this.state.customerTypet=undefined;
        this.state.id = undefined;
        this.state.shareTypet = undefined;
        this.state.companyIntentiont  = undefined;
        this.state.followSituationt  = undefined;
        this.state.locationProvincet  = undefined;
        this.state.customerStatust  = undefined;
        this.state.contactNamet   = undefined;
        this.state.contactTelt = undefined;
        this.state.contactNamet = undefined;  
        this.state.releaseDatet = [];
        this.loadData(); 
    },
    searchSwitch() {
        this.setState({
            searchMore: !this.state.searchMore
        });
    },
    //点击消失函数
    setok(e) {
		    this.setState({ 
		    	 visible:true
		    });	
		    this.Detailload(e)			   
		},
	setcancel(e) {
	    this.setState({ 
	    	 visible:false
	    });	   	    
	},
	setoks(index) {
		this.setState({ 
		    visible1:true
		});			
        this.setState({
            loading: true
        });       
        $.ajax({
                method: "post",
                dataType: "json",
                crossDomain: false,
                url: globalConfig.context + "/api/admin/customer/findCustomerUserList",
                data:{
                	cid:this.state.hids
                },
                 success: function (data) {                	  
                		let theArr = [];
					    let thedata=data.data;
					    for (let i = 0; i < data.data.length; i++) {
	                        let thisdata = data.data[i];                       
	                        theArr.push({
	                        		id:thisdata.id,//联系人ID
	                        		contactName:thisdata.name,//联系人姓名
	                        		sex:thisdata.sex,//联系人性别
	                        		mobile:thisdata.mobile,//座机号
	                        		telNum:thisdata.telNum,//手机号
	                        		email:thisdata.email,//邮箱
	                        		qq:thisdata.qq,//qq
	                        		wechat:thisdata.wechat,//微信号
	                        		depatrment:thisdata.depatrment,//部门
	                        		customerPosition:thisdata.customerPosition,//职位
	                        });
	                    };         
						this.setState({
		                    information: theArr,                    
	                    });
					}.bind(this),
				}).always(function () {
	            this.setState({
	                loading: false
	            });
	        }.bind(this));
		    
	},
	setcancels(e) {
	    this.setState({ 
	    	 visible1:false
	    });	   	    
	},
	
	setModal4VisibleOk(e) {		
		this.setState({ modal4Visible:true });			  
        this.state.data = [];
        this.setState({
            loading: true
        });  
        this.setState({
            selectedRowKeys:[],            
        });
        let deletedIds=this.state.rowId; 
         for (let idx = 0; idx < this.state.selectedRows.length; idx++) {
            let rowItem = this.state.selectedRows[idx];                          
            if (rowItem.id) {
                deletedIds=rowItem.id;               
            };            
        };       
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,          
            url:globalConfig.context + '/api/admin/customer/listCustomerLog',
            data: {
                  customerId:deletedIds                 	
            },
            success: function (data) {            	
                let theArr = [];
                let theWomanID=[];
                let theFollowID=[];
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };                   
                } else {  
                		data.data.map(function (item,index) {	
							theWomanID.push(data.data[index].contactId);					          
						});	
						data.data.map(function (item,index) {	
							theFollowID.push(data.data[index].followId);					          
						});
                    for (let i = 0; i < data.data.length; i++) {
                        let thisdata = data.data[i];
                        theArr.push({
                        		key:i,                            
                                operatorName:thisdata.operatorName,//操作员姓名
                                operatorType:thisdata.operatorType,//操作类型
                                operatorTime:thisdata.operatorTime,//操作时间
                                beforeCustomerStatus:thisdata.beforeCustomerStatus,//修改前客户状态
                                afterCustomerStatus:thisdata.afterCustomerStatus,//修改后客户状态
                                beforeCustomerIntention:thisdata.beforeCustomerIntention,//修改前客户意向
                                afterCustomerIntention:thisdata.afterCustomerIntention,//修改后客户意向
                                beforeFollowSituation:thisdata.beforeFollowSituation,//修改前跟进进度
                                afterFollowSituation:thisdata.afterFollowSituation,//修改后跟进进度
                                beforeAdminName:thisdata.beforeAdminName,//修改前跟进人
                                afterAdminName:thisdata.afterAdminName,//修改后跟进人                                                                                                                                           
                        });
                    };                   
                };               
                this.setState({//导出数据
                    journal: theArr, 
                    theWomanID:theWomanID,
                    theFollowID:theFollowID,
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    }, 
	
	//点击查看跟进记录，点击最新跟进的第一个按钮（跟进状态）执行的函数，将会出现很多跟进列表
	setModal3VisibleOk(e) {		
		this.setState({ modal3Visible:true });			  
        this.state.data = [];
        this.setState({
            loading: true
        });
        this.setState({
            selectedRowKeys:[],            
        });
        let deletedIds=this.state.rowId; 
         for (let idx = 0; idx < this.state.selectedRows.length; idx++) {
            let rowItem = this.state.selectedRows[idx];                          
            if (rowItem.id) {
                deletedIds=rowItem.id;               
            };            
        };       
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,          
            url:globalConfig.context + '/api/admin/customer/listAllFollowUpRecord',
            data: {
                  customerId:deletedIds                 	
            },
            success: function (data) {            	
                let theArr = [];
                let theWomanID=[];
                let theFollowID=[];
                if (!data.data) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };                   
                } else {  
                		data.data.map(function (item,index) {	
							theWomanID.push(data.data[index].contactId);					          
						});	
						data.data.map(function (item,index) {	
							theFollowID.push(data.data[index].followId);					          
						});
                    for (let i = 0; i < data.data.length; i++) {
                        let thisdata = data.data[i];
                        theArr.push({
                        		key:i,
                            _followDate:thisdata._followDate,//跟进时间
                            adminName:thisdata.adminName,//跟进人   
                            contactName:thisdata.contactName, //联系人姓名
                            contactId:thisdata.contactId, //联系人ID
                            contactInfo:thisdata.contactInfo,//联系信息
                            _customerStatus:thisdata._customerStatus,//客户状态     
                            _followSituation:thisdata._followSituation,//最新跟进
                            followResult:thisdata.followResult,//跟进结果
                            attachment:thisdata.attachment,//附件地址
                        });
                    };                   
                };               
                this.setState({//导出数据
                    datahistory: theArr, 
                    theWomanID:theWomanID,
                    theFollowID:theFollowID,
                });
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    }, 
    
    render() {
    	  const theData = this.state.data || {}; 
        const rowSelection = {
            selectedRowKeys: this.state.selectedRowKeys,
            onChange: (selectedRowKeys, selectedRows) => {
                this.setState({
                    selectedRows: selectedRows.slice(-1),
                    selectedRowKeys: selectedRowKeys.slice(-1)
                });
            }
        };
        const hasSelected = this.state.selectedRowKeys.length > 0;
        const { RangePicker } = DatePicker;
        return (
            <div className="user-content" >
                <div className="content-title">                  
                    <span>公司客户管理</span>                  
                </div>
                <div className="user-search">                    
                    <Input placeholder="公司名称"
                        value={this.state.companyNamet}
                        onChange={(e) => { this.setState({ companyNamet: e.target.value }); }} /> 
                    <Select placeholder="客户类型" style={{ width: 120 }}
                            value={this.state.customerTypet }
                            onChange={(e) => { this.setState({ customerTypet : e }) }}>
                            <Select.Option value="0" >个人客户</Select.Option>
                            <Select.Option value="1" >机构单位</Select.Option>
                            <Select.Option value="2" >团体单位</Select.Option>
                    </Select>     
                    <Select placeholder="意向服务"
                            style={{ width: 160 }}
                            value={this.state.companyIntentiont}
                            onChange={(e) => { this.setState({ companyIntentiont: e }) }}>
                            {this.state.intentionalOption}
                    </Select>
                    <Select placeholder="跟进进度"
                            style={{ width: 160 }}
                            value={this.state.followSituationt}
                            onChange={(e) => { this.setState({ followSituationt: e }) }}>
                            {this.state.newOption}
                    </Select>
                    <Select placeholder="地区"
                            style={{ width: 160 }}
                            value={this.state.locationProvincet}
                            onChange={(e) => { this.setState({ locationProvincet: e }) }}>
                            {this.state.auditStatusOption}
                    </Select>
                    <Select placeholder="客户状态" style={{ width: 120 }}
                            value={this.state.customerStatust}
                            onChange={(e) => { this.setState({customerStatust: e }) }}>                           
                            {this.state.customerStatuarr}
                    </Select>
                    <Button type="primary" onClick={this.search}>搜索</Button>
                    <Button onClick={this.reset}>重置</Button>
                    <Button onClick={this.setModal4VisibleOk} style={{marginRight:'10px'}}  disabled={!hasSelected}>查看日志</Button>
                    <Button onClick={this.setModal3VisibleOk} style={{marginRight:'10px'}}  disabled={!hasSelected}>查看跟进记录</Button>
                    <span>更多搜索<Switch defaultChecked={false} onChange={this.searchSwitch} /></span>
                    <div className="search-more" style={this.state.searchMore ? { display: 'none' } : {}}>                    			                  
		                <Input placeholder="联系人姓名" style={{width:'140px',marginRight:'10px'}}
		                    value={this.state.contactNamet}
		                    onChange={(e) => { this.setState({ contactNamet: e.target.value }); }} /> 
		                <Input placeholder="手机号码" style={{width:'140px',marginRight:'10px'}}
		                    value={this.state.contactTelt }
		                    onChange={(e) => { this.setState({ contactTelt: e.target.value }); }} />                          
                    </div>
                </div>
                <div className="patent-table">
                    <Spin spinning={this.state.loading}>
                        <Table columns={this.state.columns}
                            dataSource={this.state.dataSource}
                            rowSelection={rowSelection}
                            pagination={this.state.pagination}
                            onRowClick={this.tableRowClick} />
                    </Spin>
                </div>
                <Modal maskClosable={false} 
                       visible={this.state.visible}
                       onOk={this.setcancel} 
                       onCancel={this.setcancel}
                       width='800px'
                       footer={null}
                       title="客户详情"
                       className="demand-order-content">
                        <Spin spinning={this.state.loading}>                        	
                            <Row style={{marginLeft:'100px'}}>
                                <Col span={3}>客户类型：</Col>
                                <Col span={6}>{theData._customerType}</Col>                               
                            </Row>
                            <Row style={{marginLeft:'100px'}}>
                                <Col span={3}>录入时间：</Col>
                                <Col span={6}>{theData.createTime}</Col>
                                <Col span={3}>跟单人：</Col>
                                <Col span={6}>{theData.adminName}</Col>
                            </Row>
                            <Row style={{marginLeft:'50px'}}>基本资料:</Row>
                            <Row style={{marginLeft:'100px'}}>
                                <Col span={3}>公司名称：</Col>
                                <Col span={6}>{theData.companyName}</Col>
                                <Col span={3}>公司行业：</Col>
                                <Col span={6}>{theData.companyIndustry}</Col>
                            </Row>
                            <Row style={{marginLeft:'100px'}}>
	                            <Col span={3}>意向服务：</Col>
	                            <Col span={18}>{this.state.companyIntention}</Col>
	                         </Row>
                            <Row style={{marginLeft:'100px'}}>
                                
                                <Col span={3}>地区：</Col>
                                <Col span={6}>{getcityArr(theData.locationProvince)}</Col>
                            </Row>
                            <Row style={{marginLeft:'100px'}}>
                                <Col span={3}>最新跟进：</Col>
                                <Col span={6}>{theData._followSituation}</Col>
                                <Col span={3}>客户状态：</Col>
                                <Col span={6}>{theData._customerStatus}</Col>
                            </Row>
                            <Row style={{marginLeft:'100px'}}>
                                <Col span={3}>详细地址：</Col>                                
                                <Col span={6}>{theData.address}</Col>
                            </Row>
                            <Row style={{marginLeft:'100px'}} >   
                                <Col span={3}>备注：</Col>
                                <Col span={18}>{theData.remarks}</Col>
                            </Row>
                                                       
                        </Spin>
               </Modal>
                <Modal
				      footer=''
			          title="历史记录列表"
			          width='800px'
			          visible={this.state.modal3Visible}
			          onOk={this.setModal3Visiblecancel}
			          onCancel={this.setModal3Visiblecancel}							          							          
			        >	
			          <Spin spinning={this.state.loading}>	
						    <Table dataSource={this.state.datahistory} >												    
						      <Column
						        title="时间"
						        dataIndex="_followDate"
						        key="_followDate"
						      />
						      <Column
						        title="客户"
						        dataIndex="contactName"
						        key="contactName"						       						        							       
						      />													    
						    <Column
						      title="跟进人"
						      dataIndex="adminName"
						      key="adminName"
						    />
						    <Column
						      title="联系方式"
						      dataIndex="contactInfo"
						      key="contactInfo"
						    />
						    <Column
						      title="最新跟进状态"
						      dataIndex="_followSituation"
						      key="_followSituation"
						    />
						   <Column
						      title="跟进结果"
						      dataIndex="followResult"
						      key="followResult"							     									      
							/>									  
						</Table>
			        </Spin>	
				</Modal>
				<Modal
				      footer=''
			          title="日志记录列表"
			          width='1400px'
			          visible={this.state.modal4Visible}
			          onOk={this.setModal4Visiblecancel}
			          onCancel={this.setModal4Visiblecancel}							          							          
			        >	
			          <Spin spinning={this.state.loading}>	
						    <Table dataSource={this.state.journal} >												    
						      <Column
						        title="操作员姓名"
						        dataIndex="operatorName"
						        key="operatorName"
						      />
						      <Column
						        title="操作类型"
						        dataIndex="operatorType"
						        key="operatorType"						       						        							       
						      />													    
						    <Column
						      title="操作时间"
						      dataIndex="operatorTime"
						      key="operatorTime"
						    />
						    <Column
						      title="修改前客户状态"
						      dataIndex="beforeCustomerStatus"
						      key="beforeCustomerStatus"
						    />
						    <Column
						      title="修改后客户状态"
						      dataIndex="afterCustomerStatus"
						      key="afterCustomerStatus"
						    />
						   <Column
						      title="修改前客户意向"
						      dataIndex="beforeCustomerIntention"
						      key="beforeCustomerIntention"							     									      
							/>
						    <Column
						      title="修改后客户意向"
						      dataIndex="afterCustomerIntention"
						      key="afterCustomerIntention"							     									      
							/>						   
						    <Column
						      title="修改前跟进进度"
						      dataIndex="beforeFollowSituation"
						      key="beforeFollowSituation"							     									      
							/>
						    <Column
						      title="修改后跟进进度"
						      dataIndex="afterFollowSituation"
						      key="afterFollowSituation"							     									      
							/>
						     <Column
						      title="修改前跟进人"
						      dataIndex="beforeAdminName"
						      key="beforeAdminName"							     									      
							/>
						    <Column
						      title="修改后跟进人"
						      dataIndex="afterAdminName"
						      key="afterAdminName"							     									      
							/>
						</Table>
			        </Spin>	
				</Modal>
            </div >
        );
    }
});
export default PublicCustomer;
