import React, {
	Component
} from 'react';

import { Tabs, Radio, InputNumber, Checkbox, Select, Modal, Table, Icon, Button } from 'antd';
import axios from 'axios'
import { message } from 'antd';
import WidthDropDown from './WidthDropDown'
import qs from 'qs';
let myObj

function getDataByKey(dataSource, key) {
	for(var i = 0; i < dataSource.length; i++) {
		if(dataSource[i].key == key) {
			myObj = dataSource[i]
			break
		} else {
			if(dataSource[i].children) {
				getDataByKey(dataSource[i].children, key)
			}
		}
	}
}

function collectTypeToStr(arr) {
	let tmpArr = []
	let str = ''
	arr.map(item => {
		tmpArr.push(item.id)
	})
	str = tmpArr.join(',')
	return str
}

function collectCounterItem(arr) {
	let tmpArr = []
	let obj
	arr.map(item => {
		obj = {}
		obj.id = item.id;
		item.calculationMethod ? obj.calculationMethod = item.calculationMethod : null;
		item.displayType ? obj.displayType = item.displayType : null;
		item.fieldType ? obj.fieldType = item.fieldType : null;
		item.config ? obj.config = item.config : null
		tmpArr.push(obj)
	})
	return tmpArr
}

function collectFilterItem(arr) {
	let tmpArr = []
	let obj
	arr.map(item => {
		obj = {}
		obj.id = item.id;
		item.selected && item.selected.length === 0 ? null : obj.selected = item.selected
		tmpArr.push(obj)
	})
	return tmpArr
}
class DetailModal extends React.Component {
	constructor(props) {
		super(props)
		this.state = {
			iconString: 'arrows-alt',
			page: 1,
			pageSize: 10,
			totalCount: 0,
			detailData: [],
			detailColumns: [],
			modalWidth: '99%',
			isMax: false,
			loading:true
		}
	}
	//点击关闭模态窗
	handleCancel() {
		this.props.closeDetailModal()
	}
	//获取数据
	fetchData(page) {
		const self = this
		let {
			i_dataset: setId,
			currentClickInfo:para,
		} = self.props
		
		let { pageSize } = self.state;

		let detailProps = {
			i_dataset: setId,
			params:para,
			page:page,
			pageSize,
			limit_type:true
		}
		this.fetchTableData(detailProps)
	}
	
	
	fetchTableData = (params = {}) => {
		this.setState({ loading: true });
		$.post('/general/appbuilder/web/report/repchart/data', {
			...params
		},(response) => {
			let res = JSON.parse(response);
			let data = {}
			if(res == "0") return
			if(res.status) {
				message.error(res.message)
			} else {
				let columns = [];
				let detailData = [];
				let tableData = JSON.parse(JSON.stringify(res.data));
				for(let i in tableData[0]) {
					columns.push({
						title: i,
						dataIndex: i,
						key: i
					})
				}
				for(let i in tableData) {
					detailData.push({
						key: i,
						...tableData[i]
					})
				}
				this.setState({
					detailColumns: this.tranformColumns(columns),
					detailData,
					page:res.page,
					pageSize:res.pageSize,
					loading:false
				})
				if (res.total) {
					this.setState({
						totalCount:res.total
					})
				}
			}
		})
	}


	componentDidUpdate() {
		let tableInfo = document.querySelectorAll('.detail-table table')[0]
		let tableWidth = this.getTableWidth()
		if(tableWidth) {

			tableInfo.style.width = `${tableWidth}px`;

			// tableInfo.style.minWidth = ``;
		} else {

			// tableInfo.style.minWidth = `100%`;
			// tableInfo.style.width = ``;
		}
		//		console.log(tableInfo)
	}
	//计算table的宽度
	getTableWidth = () => {
		let arr = [...this.state.detailColumns]

		function getTotal(arr) {
			let total = 0

			function loop(arr) {
				arr.forEach(item => {
					if(item.children) {
						loop(item.children)
						item.width = getTotal(item.children)
					} else {
						total = total + parseInt(item.width)
					}
				});
			}
			loop(arr)
			return total
		}
		let tableWidth = getTotal(arr)
		return tableWidth
	}
	handleChangeWidth(item, e) {
		if(!this.state.isMax) {
			//没
			jQuery(".ant-modal").css({
				"max-width": 1200
			})
		} else {
			jQuery(".ant-modal").css({
				"max-width": jQuery(document).width()
			})
		}

		let reg = /^[0-9]*$/
		if(reg.test(e)) {
			let inputNum = parseInt(e)
			if(inputNum < 50) {
				// message.error(`最小宽度为50`)
			} else {
				let tmp = [...this.state.detailColumns]
				getDataByKey(tmp, item.key)
				myObj.width = `${e}px`
				// console.log(tmp)
				this.setState({
					detailColumns: tmp
				})
			}

		} else {
			message.error('请输入数字');
		}
	}
	createNewTab = url => {
		// if (window.parent && typeof window.parent.createTab == 'function') {
		//   window.parent.createTab(url, '添加数据源', url)
		// } else {
		//   window.open(url, '_blank')
		// }
		window.open(url, '_blank')
	}
	//转换列
	tranformColumns = (arr = []) => {
		const me = this
		const loop = (arr = []) => {
			let _arr = []
			arr.forEach((item, key) => {
				//				if(item.children) {
				//					let _children = loop(item.children)
				//					_arr.push({
				//						key: item.key,
				//						dataIndex: item.dataIndex,
				//						title: item.title
				//					})
				//				} else {
				//					_arr.push({
				//						key: item.key,
				//						dataIndex: item.dataIndex,
				//						width: item.width || '140px',
				//						title: item.title
				//					})
				//				}
				_arr.push({
					key: item.key,
					dataIndex: item.dataIndex,
					width: item.width || '140px',
					title: item.title,
					render: function(text, record, index) {
						if(text.url) {
							return <a onClick={me.createNewTab.bind(me, text.url)}>{text.val}</a>
						} else {
							return <span>{text.val}</span>
						}
					}
				})
			})
			return _arr
		}
		return loop(arr)
	}
	maxWin = (e) => {
		//全屏表格
		// console.log(e)
		if(document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) {
			var winHeight = document.documentElement.clientHeight;
			var winWidth = document.documentElement.clientWidth;
		}
		let content = document.querySelectorAll('.vertical-center-modal-special .ant-modal-content')[0]
		let modal = document.querySelectorAll('.vertical-center-modal-special .ant-modal ')[0]
		if(this.state.isMax) {
			content.style.height = ``
			jQuery(".ant-modal").css({
				"max-width": 1200
			})
			this.setState({
				modalWidth: '1000px',
				isMax: false,
				iconString: 'arrows-alt'
			})

			//弥补出表格放大时  下方的阴影和高度额问题，用css设定高度和盒阴影
			jQuery('.ant-modal-mask').css('background-color', 'rgba(55, 55, 55, 0.6)')
			jQuery(".ant-modal-content").css({
				"box-shadow": "0 2px 8px rgba(0, 0, 0, 0.2)"
			})
			jQuery(window).off('resize')
			jQuery(".modal-height").css({
				height: "auto"
			})
		} else {
			if(jQuery('.vertical-center-modal-special .ant-modal table').height() > jQuery(window).height()) {
				jQuery('.vertical-center-modal-special .ant-modal-content').height(730)
			} else {
				jQuery('.vertical-center-modal-special .ant-modal-content').height(jQuery(window).height() - 1)
			}
			jQuery(".ant-modal").css({
				"max-width": jQuery(document).width()
			})
			jQuery(".ant-modal-content").css({
				"box-shadow": "none"
			})
			jQuery('.ant-modal-mask').css('background-color', 'white')
			jQuery(".modal-height").css({
				height: "100%"
			})
			content.style.height = `${winHeight}px`
			this.setState({
				modalWidth: '100%',
				isMax: true,
				iconString: 'shrink'
			})
			jQuery(window).resize(function() {
				if(jQuery('.vertical-center-modal-special .ant-modal table').height() > jQuery(window).height()) {
					jQuery('.vertical-center-modal-special .ant-modal-content').height(730)
				} else {
					jQuery('.vertical-center-modal-special .ant-modal-content').height(jQuery(window).height() - 1)
				}
			});
		}
		if(this.state.isMax) {
			jQuery(".ant-modal").width(jQuery(document).width())
			content.style.height = ``
			this.setState({
				modalWidth: '99%',
				isMax: false,
				iconString: 'arrows-alt'
			})
		} else {
			content.style.height = `${winHeight}px`
			this.setState({
				modalWidth: '100%',
				isMax: true,
				iconString: 'shrink'
			})
		}
	}
	render() {
		const self = this
		const pagination = {
			page: self.state.page,
			total: self.state.totalCount,
			onChange(current) {
				self.fetchData(current)
			}
        };
        let showExport = this.props.showExport ? true : false;
        if(this.props.showModalExport!==undefined){            
            showExport = this.props.showModalExport ? true : false;
        }
		return (
			<div className="pivot-table-content-container">
            <Modal width={this.state.modalWidth} 
                wrapClassName="vertical-center-modal-special" 
                className="modal-height" 
                visible={true} 
                onCancel={this.handleCancel.bind(this)} 
                title={(<div>数据表<div style={{ float: 'right', marginRight: 40 }} onClick={(e) => {this.maxWin(e)}}><Icon className="icon" type={this.state.iconString}/></div> </div>)}
                footer={null}
            >
                {
                    showExport ? <div className="clearfix"><Button type="ghost" onClick={this.handleExportMenuClick.bind(this)} style={{"float":"right","marginBottom":"10px"}}>导出Excel文件</Button></div> : null
                }
                <Table loading={this.state.loading} columns={this.state.detailColumns} dataSource={this.state.detailData} className = "detail-table" pagination = {pagination} bordered / >
            </Modal>
            </div>
        )
    }
    handleExportMenuClick() {
        let {
            i_dataset,
            currentClickInfo,
		} =  this.props
		
         window.location.href = `/general/appbuilder/web/report/repchart/export?id=${this.props.reportId}&category=excel&method=${JSON.stringify(this.props.method)}&searchParams=${JSON.stringify(this.props.searchParams.concat(this.props.dataFilterParams))}&params=${JSON.stringify(currentClickInfo)}`;
    }
    componentDidMount() {
		const self = this
		let {
			i_dataset: setId,
			currentClickInfo:para
		} = self.props;
		let { page,pageSize } = self.state;
		let detailProps = {
			i_dataset: setId,
			params:para,
			page:page,
			pageSize,
			limit_type:true
		}
		self.fetchTableData(detailProps)
    }
}

export default DetailModal