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 { socialAttribute, industry, auditStatusL, lvl, currentMember } from '@/dataDic.js';
import { getSocialAttribute, beforeUploadFile } 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,
				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,
							type: thisdata.type,
							name: thisdata.name,
							shareType:thisdata.shareType,
							contacts:thisdata.contacts,
							contactMobile:thisdata.contactMobile,
							societyTag:thisdata.societyTag,
							surplusSignTime:thisdata.surplusSignTime,
							transferTime:thisdata.transferTime&&thisdata.transferTime.split(' ')[0],
							lastSignTime:thisdata.lastSignTime&&thisdata.lastSignTime.split(' ')[0],
							lastFollowTime:thisdata.lastFollowTime&&thisdata.lastFollowTime.split(' ')[0],
							locationProvince: diqu,
						});
					};
					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));
	},

	getInitialState() {
		return {
			addressSearch: [],
			orgCodeUrl: [],
			companyLogoUrl: [],
			visible: false,
			searchMore: true,
			releaseDate: [],
			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: 'lastSignTime',
					key: 'lastSignTime',
				},{
					title: '最新跟进日期',
					dataIndex: 'lastFollowTime',
					key: 'lastFollowTime',
				},
				{
					title: '剩余签单天数',
					dataIndex: 'surplusSignTime',
					key: 'surplusSignTime'
				}, 
				{
					title: '联系人',
					dataIndex: 'contacts',
					key: 'contacts',
				},
				{
					title: '联系电话',
					dataIndex: 'contactMobile',
					key: 'contactMobile',
				},
				{
					title: '社会属性',
					dataIndex: 'societyTag',
					key: 'societyTag',
					render:text=>{return getSocialAttribute(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: [],
			dataSource: [],
		};
	},
	
	
	
	//进入新增拜访记录
	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>
			)
		});
		this.state.Provinces = Province;
		this.state.intentionalOption = intentionalArr;
		this.loadData();
	},
	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.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));  
	},
	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>
                    <Button type="primary" onClick={this.search}>搜索</Button>
                    <Button onClick={this.reset}>重置</Button>                      
	               {adminData.isSuperAdmin?<Popconfirm title="是否删除?" onConfirm={this.delectRow} okText="是" cancelText="否">
							     <Button type="danger" style={{marginLeft:'10px'}}
	                       			 disabled={!hasSelected} 
	                       		 >删除<Icon type="minus" />
	                        </Button>
	                </Popconfirm>:''
	                }
	                <span style={{marginLeft:'10px',marginRight:'20px'}}>更多搜索<Switch checked={!this.state.searchMore} onChange={this.searchSwitch} /></span>
                    <div className='clearfix' style={{marginTop:'5px'}}>
	                  <div className="search-more" style={this.state.searchMore ? { display: 'none' } : {}}>                    			                  
			                <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 }); }} />    
			            </div>  
		            </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> 
    			<FollowDetail 
    				followData={this.state.followData}
    				visitModul={this.state.visitModul}
    				closeDesc={this.closeDesc}
    				loadData={this.loadData}
    			/>
    			<IntentionDetail 
    				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;