import React from 'react';
import '../../css/style.css'
import '../../../config';
import axios from "axios"; //导入axios
import JSZip from 'jszip';
import saveAs from 'file-saver';

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

let plainOptions = []

// 20200604该需求 需要翻页删所有数据【但！获得一张图片时间过久！超过10秒，所以加以下变量】
let querList0604_ = []

class SearchAlarm extends React.Component {
	constructor(props) {
		super(props);
        this.state={
           startTime : '',
					 endTime : '',
					 
					 currentPage: 1,
					 totalPage:1,
					 defaultPageSize:28,
					 data:[],
					 
					 indeterminate: false,
					 checkAll: false,
					 checkedList: [],
					 
					 previewVisible: false,
					 previewImage: '',
					 previewTitle: ''
        };
  }
	
	// 时间
	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) => {
	  // 开始查询【日期选择】
	  let that = this
		
		that.setState({
			data:[]
		},function(){
			that.queryImg()
		})
		
	}
	queryImg = () =>{
	  let that = this
		plainOptions = []
		querList0604_ = []
		axios.post(global.constants.commonUrl+'/syImgMs/queryImg', 
		{
		  'request':'queryImg',
		  'reqInfo':{
			  'dateTimeS':this.state.startTime,
			  'dateTimeE':this.state.endTime,
			  'curPage':this.state.currentPage,
			  'pageNum':this.state.defaultPageSize
		  }
		})
		.then(function (response) {
			var resList = response['data']['resInfo']['imgList']
			querList0604_ = 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) =>{
		console.log(querList0604_)

		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) {
				console.log(querList0604_)
				console.log(response)
					var nowData = response['data']['resInfo']
					var stateData = that.state.data
					
					//0604防止旧查询旧数据出现 需验证querList0604_ 此次得来的图片id应该在querList0604_中，querList0604_始终保持最新查询所得的数据列表
					for(var i=0;i<querList0604_.length;i++){
						if(querList0604_[i]['id'] == nowData['id']){
							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)
							break;
						}
					}
			})
			.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

		var zip = new JSZip();
		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']
					var img = zip.folder("images"); 
					img.file(data[j]['name'], data[j]['data'], {base64: true});
					break;
				}		
			}
		}
		zip.generateAsync({type:"blob"})
		.then(function(content) {
			saveAs(content, "pictures.zip");
		});
	}
	
	// 页码
	onPageChange = page => {
		// 更新新页数据 后端交互
		let that = this

		that.setState({
			currentPage: page,
			data:[]
		},function(){
			that.queryImg()
		});
  };
	
	
	// 图片放大
	handleCancel = () => this.setState({ previewVisible: false });
	handlePreview = (e) => {
		  this.setState({
		    previewImage: e.target.src,
		    previewVisible: true,
		    previewTitle:  e.target.name,
		  });
	};
  render() {
		let { data, currentPage, totalPage, defaultPageSize, previewVisible, previewImage, previewTitle } = 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'
				}}>					
					{
						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: 249, height:190, border:'1px solid rgba(255, 255, 255, 0.3)', margin:'10px', float:'left', position:'relative'}}>
											   <img style={{width:'100%', height:'140px'}}
													onClick = {this.handlePreview}
													name = {item.name}
													src={
														 'data:image/' + item['ext'] + ';base64,'+ item['data']
													}/>
											    <div style={{
													height:'50px',
													display:'flex',
													flexDirection:'column',
													color:'white',
													justifyContent:'center',
													alignItems:'center'
												}}>
													<span> 时间 </span>
													<span> {item.time} </span>
											    </div>
											  

											   <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} />
				
				
				<Modal
				  visible={previewVisible}
				  title={previewTitle}
				  footer={null}
				  onCancel={this.handleCancel}
				>
				  <img alt="example" style={{ width: '100%' }} src={previewImage} />
				</Modal>
			</div>
        );
    }
};
export default SearchAlarm