import React from 'react';
import { Select, Spin, Input, Table, Button ,DatePicker, Form  , Tabs , Switch,message} from 'antd';
import ajax from 'jquery/src/ajax/xhr.js';
import $ from 'jquery/src/ajax';
import './report.less';
import { post,taskStatus,publishStatus } from '../../../dataDic.js';
import moment from 'moment';
const TabPane = Tabs.TabPane;

const DiurnalStatistics = React.createClass({
	loadData(timeTypes) {
		this.setState({
			loading: true
		});
		$.ajax({
			method: "get",
			dataType: "json",
			crossDomain: false,
			url: globalConfig.context + "/api/admin/report/technicalDepStatistics",
			data: {
				type:'1',
				timeType:this.state.releaseDate[0]?4:timeTypes,
				startTime: this.state.releaseDate[0],
				endTime: this.state.releaseDate[1],
				depId:this.state.superId,//部门机构
				taskStatus:this.state.taskStatus,//任务状态
				publishStatus:this.state.publishStatus,//公示状态
			},
			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) {
						let nub=index+1;
						theArr.push({
							key: index,
							theNumber:false,
							nub:nub,
							orderDep: item.orderDep,//订单部门
							signTotalAmount:item.signTotalAmount,//项目签单金额
							signTime:item.signTime,//签单日期
							contractNo:item.contractNo,//合同编号
							orderRemarks:item.orderRemarks, //订单留言
							contacts:item.contacts,//企业联系人
							contactMobile:item.contactMobile,//联系人电话
							commodityName:item.commodityName,//任务名称
							taskDistributionTime:item.taskDistributionTime,//派单时间
							dutyDep:item.dutyDep, //任务责任部门
							dutyName:item.dutyName,//任务责任人
							dutyContactMobile:item.dutyContactMobile,//责任人联系电话
							taskStatus:item.taskStatus,//任务状态
							finishTime:item.finishTime, //完成时间
							taskComment:item.taskComment,//任务说明
							publishStatus:item.publishStatus, //公示状态
							publishTime:item.publishTime,//公示时间
							salesmanName:item.salesmanName, //营销员
							orgName:item.orgName,//公司名称
						})
					})
				}
				
				this.setState({
					dataSource: theArr,
				})
			}.bind(this),
		}).always(function() {
			this.setState({
				loading: false
			});
		}.bind(this));
	},
	totalData(timeTypes) {
		this.setState({
			loading: true
		});
		$.ajax({
			method: "get",
			dataType: "json",
			crossDomain: false,
			url: globalConfig.context + "/api/admin/report/sales/countsometimeMarketingStatistics",
			data: {
				type:'1',
				timeType:this.state.releaseDate[0]?4:timeTypes,
				startTime: this.state.releaseDate[0],
				endTime: this.state.releaseDate[1],
				depId:this.state.superId,//部门机构
			},
			success: function(data) {
				let thedata = data.data;
				let theArr = [];
				if(!thedata) {
					if(data.error && data.error.length) {
						message.warning(data.error[0].message);
					};
					thedata = {};
				} 
				this.loadData(timeTypes)
				this.selectSuperId();
			}.bind(this),
		}).always(function() {
			this.setState({
				loading: false
			});
		}.bind(this));
	},
	//时间选择
    selTime(value,index){
    	this.setState({
    		Dtime:value,
    		selTime:index
    	})
    },
    //获取上级组织
    selectSuperId() {  
    	this.state.data = []
         $.ajax({
                method: "post",
                dataType: "json",
                crossDomain: false,
                url: globalConfig.context + "/api/admin/organization/selectSuperId",
                data:{
                  
                },
                success: function (data) {                	  
                		let theArr = [];
                		let theId=[];//用于保存上级组织的ID和名称
					    let thedata=data.data;
					    if (!thedata) {
		                    if (data.error && data.error.length) {
		                        message.warning(data.error[0].message);
		                    };	
		                    thedata = {}; 
		              };   
					    var contactIds=[];
				        for(var i=0;i<data.data.length;i++){
		                    let theData = data.data[i];
		                    theArr.push(
		                        <Select.Option value={theData.id} key={theData.id}>{theData.name}</Select.Option>
		                    );
		                    theId.push(
		                        [theData.id,theData.name]
		                    );
		                };
						this.setState({	
							SuperArr:thedata,
		                    contactsOption: theArr, 
		                    theId: theId, 
		                    orderStatusOptions:data.data,
	                    });
	                    
					}.bind(this),
				}).always(function () {
				this.setState({
	                loading: false
	            });
	        }.bind(this));
	},
	//判断浏览器类型
	getExplorer() {
		var explorer = window.navigator.userAgent;
		//ie 
		if(explorer.indexOf("MSIE") >= 0) {
			return 'ie';
		}
		//firefox 
		else if(explorer.indexOf("Firefox") >= 0) {
			return 'Firefox';
		}
		//Chrome
		else if(explorer.indexOf("Chrome") >= 0) {
			return 'Chrome';
		}
		//Opera
		else if(explorer.indexOf("Opera") >= 0) {
			return 'Opera';
		}
		//Safari
		else if(explorer.indexOf("Safari") >= 0) {
			return 'Safari';
		}
	},
    //导出为exel表格
	tabExel() {
		var table = document.querySelector('#daochu');
		var idTmr;
		//debugger;
		//整个表格拷贝到EXCEL中
		if(this.getExplorer() == 'ie') {
			var curTbl = document.getElementById(tableid);
			var oXL = new ActiveXObject("Excel.Application");
			//创建AX对象excel 
			var oWB = oXL.Workbooks.Add();
			//获取workbook对象 
			var xlsheet = oWB.Worksheets(1);
			//激活当前sheet 
			var sel = document.body.createTextRange();
			sel.moveToElementText(curTbl);
			//把表格中的内容移到TextRange中 
			sel.select();
			//全选TextRange中内容 
			sel.execCommand("Copy");
			//复制TextRange中内容  
			xlsheet.Paste();
			//粘贴到活动的EXCEL中       
			oXL.Visible = true;
			//设置excel可见属性
			try {
				var fname = oXL.Application.GetSaveAsFilename("Excel.xls", "Excel Spreadsheets (*.xls), *.xls");
			} catch(e) {
				print("Nested catch caught " + e);
			} finally {
				oWB.SaveAs(fname);

				oWB.Close(savechanges = false);
				//xls.visible = false;
				oXL.Quit();
				oXL = null;
				//结束excel进程，退出完成
				//window.setInterval("Cleanup();",1);
				idTmr = window.setInterval("Cleanup();", 1);
			}
		} else {
			
			this.tableToExcel(table,this.getExplorer());
		}
		function Cleanup() {
			window.clearInterval(idTmr);
			CollectGarbage();
		}
	},
	tableToExcel(table,name) {
		var uri = 'data:application/vnd.ms-excel;base64,',
			template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
			base64 = function(s) {
				return window.btoa(unescape(encodeURIComponent(s)))
			},
			format = function(s, c) {
				return s.replace(/{(\w+)}/g,
					function(m, p) {
						return c[p];
					})
			}
			if(!table.nodeType) table = document.getElementById(table);
			var ctx = {
				worksheet: name || 'Worksheet',
				table: table.innerHTML
			};
			window.location.href = uri + base64(format(template, ctx))
	},
	getInitialState() {
		return {
			releaseDate: [],
			selectedRowKeys: [],
			selectedRows: [],
			loading: false,
			visible: false,
			showDesc: false,
			timeState:false,
			weekColor:true,
			monthColor:false,
			quarterColor:false,
			yearColor:false,
			Dtime:undefined,
			selTime:'',
			columns: [
			{
				title: '序号',
				dataIndex: 'nub',
				width:50,
				key: 'nub',
				fixed:false,
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				    }
				}
			},
			{
				title: '公司名称',
				dataIndex: 'orgName',
				key: 'orgName',
				width:100,
				fixed:false,
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text//&&text.length>6?<span title={text}>{text.substr(0,6)+'…'}</span>:text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:3
      						},
				     	}
				     	
				     }
				     
				}
			}, {
				title: '订单部门',
				fixed:false,
				width:100,
				dataIndex: 'orderDep',
				key: 'orderDep',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				     	
				     }
				     
				}
			},
			{
				title: '项目签单金额',
				fixed:false,
				dataIndex: 'signTotalAmount',
				key: 'signTotalAmount',
				sorter: (a, b) => a.signTotalAmount - b.signTotalAmount,
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:1
      						},
				     	}
				     	
				     }
				     
				}
			}, {
				title: '签单日期',
				fixed:false,
				dataIndex: 'signTime',
				key: 'signTime',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				     	
				     }
				     
				}
			}, {
				title: '合同编号',
				fixed:false,
				dataIndex: 'contractNo',
				key: 'contractNo',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				     	
				     }
				     
				}
			},{
				title: '订单留言',
				fixed:false,
				dataIndex: 'orderRemarks',
				key: 'orderRemarks',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text&&text.length>6?<span title={text}>{text.substr(0,6)+'…'}</span>:text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				     	
				     }
				     
				}
			},{
				title: '企业联系人',
				fixed:false,
				dataIndex: 'contacts',
				key: 'contacts',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				     	
				     }
				     
				}
			},{
				title: '联系人电话',
				fixed:false,
				dataIndex: 'contactMobile',
				key: 'contactMobile',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				     	
				     }
				     
				}
			},{
				title: '任务名称',
				fixed:false,
				dataIndex: 'commodityName',
				key: 'commodityName',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				     	
				     }
				     
				}
			},{
				title: '派单时间',
				fixed:false,
				dataIndex: 'taskDistributionTime',
				key: 'taskDistributionTime',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				     	
				     }
				     
				}
			},{
				title: '部门',
				fixed:false,
				dataIndex: 'dutyDep',
				key: 'dutyDep',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				     	
				     }
				     
				}
			},{
				title: '负责人',
				fixed:false,
				dataIndex: 'dutyName',
				key: 'dutyName',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				     	
				     }
				     
				}
			},{
				title: '负责人电话',
				fixed:false,
				dataIndex: 'dutyContactMobile',
				key: 'dutyContactMobile',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				     	
				     }
				     
				}
			},{
				title: '任务状态',
				fixed:false,
				dataIndex: 'taskStatus',
				key: 'taskStatus',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				     	
				     }
				     
				}
			},{
				title: '项目完成时间',
				fixed:false,
				dataIndex: 'finishTime',
				key: 'finishTime',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				     	
				     }
				     
				}
			},{
				title: '任务说明',
				fixed:false,
				dataIndex: 'taskComment',
				key: 'taskComment',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				     	
				     }
				     
				}
			},{
				title: '公示状态',
				fixed:false,
				dataIndex: 'publishStatus',
				key: 'publishStatus',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				     	
				     }
				     
				}
			},{
				title: '公示时间',
				fixed:false,
				dataIndex: 'publishTime',
				key: 'publishTime',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:0
      						},
				     	}
				     	
				     }
				     
				}
			},
			{
				title: '营销员',
				fixed:false,
				dataIndex: 'salesmanName',
				key: 'salesmanName',
				render:(text,record)=>{
				     if(!record.theNumber){
				     	return text
				     }else{
				     	return {
				     		children: text,
      						props: {
      							colSpan:1
      						},
				     	}
				     	
				     }
				     
				}
			}
			],
			dataSource: [],
		};
	},
	search() {
		this.loadData(0)
	},
	reset() {
		this.state.superId = undefined;//部门机构清零
		this.loadData(0)
		this.setState({
			order:"false",
			weekColor:true,
			monthColor:false,
			quarterColor:false,
			yearColor:false
		})
	},
	week(){
		this.state.releaseDate[0] = undefined;//开始时间清零
		this.state.releaseDate[1] = undefined;//结束时间清零
		this.loadData(0);
		this.setState({
			weekColor:true,
			monthColor:false,
			quarterColor:false,
			yearColor:false
		})
	},
	month(){
		this.state.releaseDate[0] = undefined;//开始时间清零
		this.state.releaseDate[1] = undefined;//结束时间清零
		this.loadData(1);
		this.setState({
			weekColor:false,
			monthColor:true,
			quarterColor:false,
			yearColor:false
		})
	},
	quarter(){
		this.state.releaseDate[0] = undefined;//开始时间清零
		this.state.releaseDate[1] = undefined;//结束时间清零
		this.loadData(2);
		this.setState({
			weekColor:false,
			monthColor:false,
			quarterColor:true,
			yearColor:false
		})
	},
	year(){
		this.state.releaseDate[0] = undefined;//开始时间清零
		this.state.releaseDate[1] = undefined;//结束时间清零
		this.loadData(3);
		this.setState({
			weekColor:false,
			monthColor:false,
			quarterColor:false,
			yearColor:true
		})
	},
	//重构排序
	tabChange(pagination,filter,sorter){
		console.log(pagination)
		console.log(sorter)
	},
	componentWillMount() {
		//this.loadData();
		this.totalData(0);
		let times=new Date();
		let nowTime=times.getFullYear()+'年'+(times.getMonth()+1)+'月'+times.getDate()+'日';
		this.setState({
			Nowtime:nowTime
		})
	},
	render() {
		const { RangePicker } = DatePicker;
		let departmentArr = this.state.departmentArr || [];
		return(
			<div className='set-content'>
				<p style={{fontSize:'20px',marginBottom:'10px'}}>客户营销统计表（部门）</p>
				<div className="clearfix">
					<Button type="primary" onClick={this.tabExel} style={{ float:'right' }}>导出到表格</Button>
					<span style={{fontSize:'16px'}}>部门机构 : </span>
					<Select placeholder="选择部门"
                            style={{ width:'200px',marginRight:'10px' }}
                            value={this.state.superId}
                            onChange={(e) => { this.setState({ superId: e }) }} notFoundContent="未获取到上级组织列表">
                            {this.state.contactsOption}
		          	</Select>
		          	
                  		<Select placeholder="任务状态"
                            style={{ width: 150 ,marginRight:'10px'}}
                            value={this.state.taskStatus}
                            onChange={(e) => { this.setState({ taskStatus: e }) }}>
                            {
                                taskStatus.map(function (item) {
                                        return <Select.Option key={item.value} >{item.key}</Select.Option>
                                })
                            }
                        </Select>
                        <Select placeholder="公示状态"
                            style={{ width: 150 ,marginRight:'10px'}}
                            value={this.state.publishStatus}
                            onChange={(e) => { this.setState({ publishStatus: e }) }}>
                            {
                                publishStatus.map(function (item) {
                                        return <Select.Option key={item.value} >{item.key}</Select.Option>
                                })
                            }
                        </Select>
                        <Button type="primary" onClick={this.search} style={{marginLeft:'10px',marginRight:'10px'}}>搜索</Button>
	                	<Button onClick={this.reset}>重置</Button>
                        <div className="clearfix" style={{marginTop:"10px"}}>
                        	<Button onClick={this.week} style={{marginRight:'5px'}} type={this.state.weekColor?"primary":''}>本周</Button>
				          	<Button onClick={this.month} style={{marginRight:'5px'}} type={this.state.monthColor?"primary":''}>本月</Button>
				          	<Button onClick={this.quarter} style={{marginRight:'5px'}} type={this.state.quarterColor?"primary":''}>本季</Button>
				          	<Button onClick={this.year} style={{marginRight:'5px'}} type={this.state.yearColor?"primary":''}>本年</Button>
				          	<span className="titleTime" style={{marginRight:'5px',marginTop:"0px"}}>起止时间:</span>
								<RangePicker style={{marginRight:'5px',marginTop:"0px"}}
		                            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 id='daochu'>
					<div className="surfaceTitle">
				   	<span style={{marginTop:"10px"}}>客户营销统计表（部门）</span>
					</div>
					<div className="patent-table" id='daochu'>
						<div className="scroll">
		                    <Spin spinning={this.state.loading}>
		                        <Table columns={this.state.columns}
		                            dataSource={this.state.dataSource}
		                            //scroll={{ x: 600,y:500}}
		                            bordered
		                            onChange={this.tabChange}
		                            pagination={false}
		                            />
		                    </Spin>
		                </div>
		            </div>
	            </div>
			</div>
		)
	}
});
export default DiurnalStatistics;