import React from 'react';
import { Radio, Icon, Button, AutoComplete,Cascader,Input, Select, Spin, Popconfirm, Table, Switch, message, DatePicker, Upload, Form } from 'antd';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import moment from 'moment';
import { citySelect, provinceList } from '@/NewDicProvinceList';
import AddIntention from './addIntention.jsx';
import { socialAttribute, industry, auditStatusL, lvl, currentMember } from '@/dataDic.js';
import { getSocialAttribute, beforeUploadFile ,getLevel} from '@/tools.js';
import FollowDetail from './followDetail.jsx'
import IntentionDetail from './intentionDetail/intentionDetail.jsx'
import './customer.less';
const IntentionCustomer = Form.create()(React.createClass({
	loadData(pageNo, apiUrl) {
		this.setState({
			visitModul:false,
			loading: true,
			ispage:pageNo,
			modalVisible:false
		});
		let api=apiUrl?apiUrl:this.props.ApiUrl;
		$.ajax({
			method: "post",
			dataType: "json",
			crossDomain: false,
			url: globalConfig.context + api,
			data: {
				pageNo: pageNo || 1,
				pageSize: this.state.pagination.pageSize,
				level:this.state.level?this.state.level:undefined,
				name: this.state.nameSearch,
				province: !(this.state.addressSearch).length ? this.state.provinceSearch : this.state.addressSearch[0],
				city: !(this.state.addressSearch).length ? '' : this.state.addressSearch[1],
				startDate: this.state.releaseDate[0],
				endDate: this.state.releaseDate[1],
			},
			success: function(data) {
				let theArr = [];
				if(data.error.length || 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];
						let diqu=(thisdata.province==null?"":thisdata.province)+(thisdata.city==null?"":"-"+thisdata.city)+(thisdata.area==null?"":"-"+thisdata.area);
						theArr.push({
							key: i,
							id: thisdata.uid,
							aid:thisdata.aid,
							name: thisdata.name,
							contacts: thisdata.contacts,
							contactMobile: thisdata.contactMobile,
							industry: thisdata.industry,
							societyTag: thisdata.societyTag,
							lastFollowTime:thisdata.lastFollowTime&&thisdata.lastFollowTime.split(' ')[0],
							transferTime:thisdata.transferTime&&thisdata.transferTime.split(' ')[0],
							surplusFollowTime:thisdata.surplusFollowTime&&thisdata.surplusFollowTime.split(' ')[0],
							surplusSignTime:thisdata.surplusSignTime&&thisdata.surplusSignTime.split(' ')[0],
							locationProvince: diqu,
							level:thisdata.level,
						});
					};
					this.state.pagination.current = data.data.pageNo;
				    this.state.pagination.total = data.data.totalCount;
				};
				if(data.data&&data.data.list&&!data.data.list.length){
					this.state.pagination.current=0
					this.state.pagination.total=0
				}
				this.setState({
					dataSource: theArr,
					pagination: this.state.pagination,
					selectedRowKeys:[]
				});
			}.bind(this),
		}).always(function() {
			this.setState({
				loading: false
			});
		}.bind(this));
	},
	//品类数据获取
    category(){
		$.ajax({
			method: "get",
			dataType: "json",
			crossDomain: false,
			url: globalConfig.context + "/api/admin/Varieties/getSuperList",
			data: {
				
			},
			success: function(data) {
				let thedata = data.data;
				let theArr=[];
				if(!thedata) {
					if(data.error && data.error.length) {
						message.warning(data.error[0].message);
					};
					thedata = {};
				}else{
					thedata.map(function(item,index){
						theArr.push({
							value:item.id,
							key:item.cname,
						})
					})
				}
				this.setState({
					categoryArr:theArr,
				})
			}.bind(this),
			});
    },
	getInitialState() {
		return {
			addressSearch: [],
			orgCodeUrl: [],
			companyLogoUrl: [],
			visible: false,
			searchMore: true,
			releaseDate: [],
			categoryArr:[],
			visitModul:false,
			keys:false,
			detailApi:'',
			followData:{},
			selectedRowKeys: [],
			selectedRowKey: [],
			selectedRows: [],
			loading: false,
			modalVisible:false,
			pagination: {
				defaultCurrent: 1,
				defaultPageSize: 10,
				showQuickJumper: true,
				pageSize: 10,
				onChange: function(page) {
					this.loadData(page);
				}.bind(this),
				showTotal: function(total) {
					return '共' + total + '条数据';
				}
			},
			columns: [{
					title: '客户名称',
					dataIndex: 'name',
					key: 'name',
				}, {
					title: '地区',
					dataIndex: 'locationProvince',
					key: 'locationProvince',
				}, {
					title: '联系人',
					dataIndex: 'contacts',
					key: 'contacts',
				},
				{
					title: '联系电话',
					dataIndex: 'contactMobile',
					key: 'contactMobile',
				},
				{
					title: '社会性质',
					dataIndex: 'societyTag',
					key: 'societyTag',
					render: text => { return getSocialAttribute(text) }
				},
				{
					title: '客户初始时间',
					dataIndex: 'transferTime',
					key: 'transferTime',
				},
				{
					title: '剩余私有天数',
					dataIndex: 'surplusFollowTime',
					key: 'surplusFollowTime'
				},
				{
					title: '最新跟进时间',
					dataIndex: 'lastFollowTime',
					key: 'lastFollowTime',
				},{
					title: '客户等级',
					dataIndex: 'level',
					key: 'level',
					render:text => { return getLevel(text) }
				},
				{
					title: '跟进操作',
					dataIndex: 'abc',
					key: 'abc',
					render: (text, record, index) => {
						return <div>
                            <Button onClick={(e) =>{ e.stopPropagation(), this.visit(record)}} type="primary">客户跟进</Button>                            							    
                        </div>
					}
				}
			],
			data: [],
			dataman: [],
			dataSource: [],
			visitArrList: [],
			searchTime: [, ]
		};
	},
	
	rankO(rank){
		let deletedIds;
		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/updateUserLevel",
			data: {
				id: deletedIds, //客户的ID
				level:rank
			}
		}).done(function(data) {
			if(!data.error.length) {
				message.success('操作成功！');
				this.setState({
					loading: false,
				});
			} else {
				message.warning(data.error[0].message);
			};
			this.loadData(this.state.ispage);
		}.bind(this));
	},
	
	//进入新增拜访记录
	visit(e) {
		this.setState({
			followData:e,
			visitModul:true,
			modalVisible:false
		})
	},
	//列表删除功能
	delectRow() {
		let deletedIds;
		for(let idx = 0; idx < this.state.selectedRows.length; idx++) {
			let rowItem = this.state.selectedRows[idx];
			if(rowItem.id) {
				deletedIds = rowItem.id;
			};
		};
		this.setState({
			loading: true,
			selectedRowKeys: [],
		});
		$.ajax({
			method: "get",
			dataType: "json",
			crossDomain: false,
			url: globalConfig.context + "/api/admin/customer/deleteCustomer",
			data: {
				uid: deletedIds, //删除的ID    
			}
		}).done(function(data) {
			if(!data.error.length) {
				message.success('删除成功！');
				this.setState({
					loading: false,
				});
			} else {
				message.warning(data.error[0].message);
			};
			this.loadData(this.state.ispage);
		}.bind(this));
	},
	componentWillMount() {
		//城市
		let Province = [];
		provinceList.map(function(item) {
			var id = String(item.id)
			Province.push(
				<Select.Option value={id} key={item.name}>{item.name}</Select.Option>
			)
		});
		//行业
		let intentionalArr = [];
		industry.map(function(item) {
			intentionalArr.push(
				<Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
			)
		});
		//会员等级
		let lvlArr = [];
		lvl.map(function(item) {
			lvlArr.push(
				<Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
			)
		});
		//会员状态customerStatus
		let currentMemberArr = [];
		currentMember.map(function(item) {
			currentMemberArr.push(
				<Select.Option value={item.value} key={item.key}>{item.key}</Select.Option>
			)
		});
		this.state.Provinces = Province;
		this.state.intentionalOption = intentionalArr;
		this.state.lvlArrOption = lvlArr;
		this.state.currentMemberArrOption = currentMemberArr;
		this.loadData();
		this.category()
	},
	addClick() {
		this.state.RowData = {};
		this.setState({
			detailApi:this.props.detailApi,
			showDesc: true,
			modalVisible:false,
			visitModul:false
		});
	},
	closeDesc(e, s) {
		this.state.basicState=e
		this.state.visitModul=e;
		this.state.modalVisible=e;
		this.state.showDesc = e;
		if(s) {
			this.loadData(this.state.ispage);
		};
	},
	search() {
		this.loadData();
	},
	reset() {
		this.state.nameSearch = '';
		this.state.level = undefined;
		this.state.addressSearch = [];
		this.state.provinceSearch = undefined;
		this.state.citySearch = undefined;
		this.state.releaseDate[0] = undefined;
		this.state.releaseDate[1] = undefined;
		this.loadData();
	},
	searchSwitch() {
		this.setState({
			visitModul:false,
			searchMore: !this.state.searchMore
		});
	},
	//整行点击
	tableRowClick(record, index) {
		this.state.visitModul=false;
		this.state.RowData = record;
		this.setState({
			selectedRowKeys: [],
			modalVisible:true,
			basicState:true,
			contactState:true,
		})
	},
	//指定转交人自动补全
	supervisor(e){ 
		$.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/customer/listAdminByName",
            data:{
            	adminName:e
            },
            success: function (data) {                	  
				       let thedata=data.data;
				    if (!thedata) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    };	
                    thedata = {}; 
              }; 
					this.setState({
						customerArr:thedata,	
                    });
				}.bind(this),
			}).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));  
	},
	//上级主管输入框失去焦点是判断客户是否存在
	selectAuto(value,options){
		this.setState({
			auto:value
		})
	},
	blurChange(e){
		let theType='';
		let contactLists=this.state.customerArr||[];
			if (e) {
            contactLists.map(function (item) {
                if (item.name == e.toString()) {
                    theType = item.id;
                }
           });     
   	    }
		this.setState({
			theTypes:theType
		})
	},
	//值改变时请求客户名称
	httpChange(e){
		if(e.length>=1){
			this.supervisor(e); 
		}	
		this.setState({
			auto:e
		})
	},
	//转交
	changeAssigner() {
		if(this.state.theTypes){
			this.setState({
				selectedRowKeys: [],
			});
			let changeIds,oldAid;
			for(let idx = 0; idx < this.state.selectedRows.length; idx++) {
				let rowItem = this.state.selectedRows[idx];
				if(rowItem.id) {
					oldAid=rowItem.aid;
					changeIds = rowItem.id;
				};
			};
			$.ajax({
				method: "get",
				dataType: "json",
				crossDomain: false,
				url: globalConfig.context + "/api/admin/customer/transferToOther",
				data: {
					uid: changeIds, //这一行数据的ID
					aid: this.state.theTypes, //指定转交人的ID 
					oldAid:oldAid
				}
			}).done(function(data) {
				if(!data.error.length) {
					message.success('转交成功！');
					this.setState({
						auto:'',
						loading: false,
					});
				} else {
					message.warning(data.error[0].message);
				};
				this.loadData(Math.min(this.state.ispage==undefined?1:this.state.ispage,Math.ceil((this.state.pagination.total-1)/10)));
			}.bind(this));
		}else{
			message.warning('请输入转交人姓名')
		}
	},

	componentWillReceiveProps(nextProps) {
		if(nextProps.ApiUrl!=this.props.ApiUrl) {
			if(!this.state.searchMore){
				this.state.searchMore=true
			}
			this.state.nameSearch = '';
			this.state.addressSearch = [];
			this.state.provinceSearch = undefined;
			this.state.citySearch = undefined;
			this.state.releaseDate[0] = undefined;
			this.state.releaseDate[1] = undefined;
			this.loadData(null,nextProps.ApiUrl);
		};
	},
	render() {
		const FormItem = Form.Item;
		const rowSelection = {
			selectedRowKeys: this.state.selectedRowKeys,
			onChange: (selectedRowKeys, selectedRows) => {
				this.setState({
					modalVisible:false,
					selectedRows: selectedRows.slice(-1),
					selectedRowKeys: selectedRowKeys.slice(-1)
				});
			},
			onSelect: (recordt, selected, selectedRows) => {
				this.setState({
					modalVisible:false,
					recordt: recordt.id
				})
			},
		};
		const hasSelected = this.state.selectedRowKeys.length > 0;
		const { RangePicker } = DatePicker;
		const dataSources=this.state.customerArr || [];
        const options = dataSources.map((group) =>
				      <Select.Option key={group.id} value={group.name}>{group.name}</Select.Option>
				     )
        const intentionState = this.props.intentionState ||'';
		return(
			<div className="user-content" >
                <div className="content-title">                  
                    <span>{!intentionState?'私有单位客户':'私有专家客户'}</span>
                </div>
                <div className="user-search">                    
                    <Input placeholder="客户名称"
                        value={this.state.nameSearch}
                        onChange={(e) => { this.setState({ nameSearch: e.target.value }); }} />    
                    <Select placeholder="省"
                            style={{ width: 80 }}
                            value={this.state.provinceSearch}
                            onChange={(e) => {this.setState({ provinceSearch: e});}}>
                            {this.state.Provinces}
                    </Select> 
                    <span style={{marginRight:'10px'}}>                   
	                     <Cascader options={citySelect()}  value={this.state.addressSearch} placeholder="选择城市"
    						onChange={(e,pre) => { this.setState({ addressSearch: e }) }} />	                 
                    </span>
                    <Select
                    	style={{ width: 120 }}
						value={this.state.level}
						onChange={(e) => {
							this.setState({ level: e });
						}}
						placeholder="请选择客户等级"
					>
						<Select.Option value="0">一般客户</Select.Option>
						<Select.Option value="1">意向客户</Select.Option>
						<Select.Option value="2">重点客户</Select.Option>
					</Select>
                    <RangePicker
	                        value={[this.state.releaseDate[0] ? moment(this.state.releaseDate[0]) : null,
	                        this.state.releaseDate[1] ? moment(this.state.releaseDate[1]) : null]}
	                        onChange={(data, dataString) => { this.setState({ releaseDate: dataString }); }} />    
                    <Button type="primary" style={{marginLeft:"10px"}} onClick={this.search}>搜索</Button>
                    <Button onClick={this.reset}>重置</Button>                      
                    {/*<Button onClick={() => { window.open(globalConfig.context + '/api/admin/customer/downloadTemplate?type=1') }}>下载批量导入模板</Button>
               		<Upload 
               		    name="file"
                        action={globalConfig.context + "/api/admin/customer/uploadExcel"}                            
                        beforeUpload={beforeUploadFile}
                        showUploadList={false}
                        onChange={(info) => {
                            if (info.file.status !== 'uploading') {
                                console.log(info.file, info.fileList);
                            }
                            if (info.file.status === 'done') {
                                if (!info.file.response.error.length) {
                                    message.success(`${info.file.name} 文件上传成功！`);
                                    this.loadData();
                                } else {
                                    message.warning(info.file.response.error[0].message);
                                    return;
                                };
                            } else if (info.file.status === 'error') {
                                message.error(`${info.file.name} 文件上传失败。`);
                            };
                        }} >
                        <Button>上传批量内容</Button>
                    </Upload>  
                    
	               {adminData.isSuperAdmin?<Popconfirm title="是否删除?" onConfirm={this.delectRow} okText="是" cancelText="否">
							     <Button type="danger" style={{marginLeft:'10px'}}
	                       			 disabled={!hasSelected} 
	                       		 >删除<Icon type="minus" />
	                        </Button>
	                </Popconfirm>:''
	                }*/}
	                <AutoComplete
				        className="certain-category-search"
				        dropdownClassName="certain-category-search-dropdown"
				        dropdownMatchSelectWidth={false}
				        dropdownStyle={{ width: 120 }}
				        style={{ width: '120px'}}
				        dataSource={options}
				        placeholder="输入转交人姓名"
				        value={this.state.auto}
				        onChange={this.httpChange}
				        filterOption={true}
				        onBlur={this.blurChange}
				        onSelect={this.selectAuto}
				        disabled={!hasSelected}
				      >
				        <Input />
				      </AutoComplete>  
					<Button type="primary" onClick={this.changeAssigner}  disabled={!hasSelected} >转交</Button>  
                    <Button type="primary" className="addButton" onClick={this.addClick}>新增客户<Icon type="plus" /></Button> 
                    <div className='clearfix' style={{marginTop:'5px'}}>
	                   <Button onClick={(e) =>{ e.stopPropagation(), this.rankO(0)}} type="primary" style={{marginRight:"10px"}} disabled={!hasSelected}>一般客户</Button>
	                   <Button onClick={(e) =>{ e.stopPropagation(), this.rankO(1)}} type="primary" style={{marginRight:"10px"}} disabled={!hasSelected}>意向客户</Button>
	                   <Button onClick={(e) =>{ e.stopPropagation(), this.rankO(2)}} type="primary" disabled={!hasSelected}>重点客户</Button>
		            </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> 
                <AddIntention
                	api={this.state.detailApi}
                    showDesc={this.state.showDesc}
                    closeDesc={this.closeDesc} 
                    />
    			<FollowDetail 
    			    categoryArr={this.state.categoryArr}
    				followData={this.state.followData}
    				visitModul={this.state.visitModul}
    				closeDesc={this.closeDesc}
    			/>
    			<IntentionDetail 
    				categoryArr={this.state.categoryArr}
    				detailApi={this.props.detailApi}
    				IntentionData={this.state.RowData}
    				modalVisible={this.state.modalVisible}
    				closeDesc={this.closeDesc}
    				basicState={this.state.basicState}
    				contactState={this.state.contactState}
    			/>
          </div >
		);
	}
}));
export default IntentionCustomer;