import React from 'react';
import '../../css/style.css'
import '../../../config';
import axios from "axios"; //导入axios

import { Row, Col, DatePicker, Checkbox, Pagination, Button } from 'antd';
const { RangePicker } = DatePicker;

let plainOptions = []
class SearchAlarm extends React.Component {
	constructor(props) {
		super(props);
        this.state={
           startTime : '',
		   endTime : '',
		   
		   currentPage: 1,
		   totalPage:10,
		   defaultPageSize:55,
		   data:[],
		   
		   indeterminate: false,
		   checkAll: false,
		   checkedList: []
        };
    }
	
	// 时间
	onTimeChange = (value,dateString) => {
	  let that = this;
	  this.setState({
		  startTime:dateString[0],
		  endTime:dateString[1]
	  },function(){
		  console.log(that.state.startTime)
		  console.log(that.state.endTime)
	  })
	}
	
	onOk = (value) => {
	  // 开始查询【日期选择】
	  this.queryImg()
	}
	queryImg = () =>{
	    let that = this
		plainOptions = []
		axios.post(global.constants.commonUrl+'/syImgMs/queryImg', 
		{
		  'request':'queryImg',
		  'reqInfo':{
			  'dateTimeS':this.state.startTime,
			  'dateTimeE':this.state.endTime,
			  'curPage':1,
			  'pageNum':this.state.defaultPageSize
		  }
		})
		.then(function (response) {
			var resList = response['data']['resInfo']['imgList']
			that.setState({
			  data:[],
			  indeterminate: false,
			  checkAll: false,
			  checkedList: [],
			  totalPage: response['data']['resInfo']['totalPages']
			});
			that.getImgData(resList,0)
		})
		.catch(function (error) {
			//console.log(error);
		});
	}
	getImgData = (resList, currI) =>{
		var that = this
		if(currI == resList.length)
			return;
		else{
			axios.post(global.constants.commonUrl+'/syImgMs/getImgData', 
			{
			  'request':'getImgData',
			  'reqInfo':{
				  'imgId':resList[currI]['id']
			  }
			})
			.then(function (response) {
				var nowData = response['data']['resInfo']
				var stateData = that.state.data
				stateData.push({
					'id': nowData['id'],
					'name': nowData['name'],
					'time': nowData['time'],
					'ext': nowData['ext'],
					'data': nowData['data']
				})
				that.setState({
				  data:stateData
				});
				plainOptions.push(nowData['id'])
				that.getImgData(resList, currI+1)
			})
			.catch(function (error) {
				//console.log(error);
			});
		}
	}
	
	// 下载
	onCheckBoxChange =  checkedList => {
		this.setState({
			checkedList,
			indeterminate: !!checkedList.length && checkedList.length < plainOptions.length,
			checkAll: checkedList.length === plainOptions.length,
		});
	};
	onChange = checkedList => {
		this.setState({
			checkedList,
			indeterminate: !!checkedList.length && checkedList.length < plainOptions.length,
			checkAll: checkedList.length === plainOptions.length,
		});
	};
	onCheckAllChange = e => {
		let that = this
		this.setState({
			checkedList: e.target.checked ? plainOptions : [],
			indeterminate: false,
			checkAll: e.target.checked,
		},function(){
			console.log(that.state.checkedList)
		});
	};
	clickBtn = e =>{
		console.log(this.state.checkedList)
		var checkedList = this.state.checkedList
		var data = this.state.data

		for(var i=0;i<checkedList.length;i++){
			for(var j=0;j<data.length;j++){
				if(checkedList[i] == data[j]['id']){
					var imgUrl	= 'data:image/' + data[j]['ext'] + ';base64,'+ data[j]['data']
					// 如果浏览器支持msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
					if (window.navigator.msSaveOrOpenBlob) {
						let bstr = atob(imgUrl.split(",")[1]);
						let n = bstr.length;
						let u8arr = new Uint8Array(n);
						while (n--) {
						  u8arr[n] = bstr.charCodeAt(n);
						}
						let blob = new Blob([u8arr]);
						window.navigator.msSaveOrOpenBlob(blob, data[j]['name'] + "." + data[j]['ext']);
					} else {
						// 这里就按照chrome等新版浏览器来处理
						let a = document.createElement("a");
						a.href = imgUrl;
						a.setAttribute("download", data[j]['name']);
						a.click();
					}
					
					break;
				}		
			}
		}
		
		
// 	var imgUrl	= 'data:image/' + data['ext'] + ';base64,'+ data['data']
// 		this.state.data[0]['src']
// 		// 如果浏览器支持msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
//       if (window.navigator.msSaveOrOpenBlob) {
//         let bstr = atob(imgUrl.split(",")[1]);
//         let n = bstr.length;
//         let u8arr = new Uint8Array(n);
//         while (n--) {
//           u8arr[n] = bstr.charCodeAt(n);
//         }
//         let blob = new Blob([u8arr]);
//         window.navigator.msSaveOrOpenBlob(blob, "chart-download" + "." + "png");
//       } else {
//         // 这里就按照chrome等新版浏览器来处理
//         let a = document.createElement("a");
//         a.href = imgUrl;
//         a.setAttribute("download", "chart-download");
//         a.click();
//       }
// 	  
// 	  var imgUrl	= this.state.data[1]['src']
// 	  	// 如果浏览器支持msSaveOrOpenBlob方法（也就是使用IE浏览器的时候），那么调用该方法去下载图片
// 	    if (window.navigator.msSaveOrOpenBlob) {
// 	      let bstr = atob(imgUrl.split(",")[1]);
// 	      let n = bstr.length;
// 	      let u8arr = new Uint8Array(n);
// 	      while (n--) {
// 	        u8arr[n] = bstr.charCodeAt(n);
// 	      }
// 	      let blob = new Blob([u8arr]);
// 	      window.navigator.msSaveOrOpenBlob(blob, "chart-download" + "." + "png");
// 	    } else {
// 	      // 这里就按照chrome等新版浏览器来处理
// 	      let a = document.createElement("a");
// 	      a.href = imgUrl;
// 	      a.setAttribute("download", "chart-download");
// 	      a.click();
// 	    }
		
	}
	
	// 页码
	onPageChange = page => {
		// 更新新页数据 后端交互
		this.setState({
		  currentPage: page
		});
		this.queryImg()
    };
	
    render() {
		let { data, currentPage, totalPage, defaultPageSize } = this.state
		let that = this
		
        return (
			<div style={{
				width:'100%',
				position:'relative'
			}}> 
				<div style={{
					padding:'20px 0',
				}}>
					<RangePicker
					  showTime={{ format: 'HH:mm' }}
					  format="YYYY-MM-DD HH:mm"
					  onChange={this.onTimeChange}
					  onOk={this.onOk}
					/>
					    <Checkbox
							indeterminate={this.state.indeterminate}
							onChange={this.onCheckAllChange}
							checked={this.state.checkAll}
							style={{
								margin:'0 20px',
								color:'white'
							}}
					    >
						   Check all
					    </Checkbox>
					    <Button type="primary" onClick={this.clickBtn} style={{
							margin:'0 20px'
						}}>downLoad</Button>
				</div>
				<div style={{
					height:'calc(100% - 105px)',
					top:'80px',
					width:'calc(100% - 20px)',
					margin:'0 10px',
					backgroundColor:'rgba(239, 192, 192, 0.1)'
				}}>					
					{
						data.length==0?null:
							<Checkbox.Group style={{ width: '100%' }} onChange={that.onCheckBoxChange} value={this.state.checkedList}>
								{
									data.map((item)=>{
									//console.log(item)
									return  <div key={item.id} style={{ width: 150, height:140, border:'1px solid rgba(255, 255, 255, 0.3)', margin:'10px', float:'left', position:'relative'}}>
											   <img style={{width:'100%', height:'100%'}} src={
												   'data:image/' + item['ext'] + ';base64,'+ item['data']
											   }/>
											   <Checkbox style={{
												   position:'absolute',
												   top:'-8px',
												   right:'-8px'
											   }} value={item.id} defaultChecked ></Checkbox>
											</div>
									})
								}
							</Checkbox.Group>
					}
				</div>
				<Pagination hideOnSinglePage={true} showTitle={false} current={currentPage} onChange={this.onPageChange} pageSize={defaultPageSize} total={totalPage*defaultPageSize} />
			</div>
        );
    }
};
export default SearchAlarm