<template>
	<div>
		<div>
			<div ref="print" v-if="isPrint">
				<div v-for="(item,index) in selectionItems" :key="item.id" style="width: 100%;height: 100%;">
					<div :style="{width:printW+'cm',height:printH+'cm'}" style="position: relative;">
						
						
						<template v-for="item in inputs">
							<div class="input-item" :style="{left:item.x+'cm',top:item.y+'cm',width:item.w? item.w+'cm':'auto'}" style="z-index: 2;height: 2.33rem;">
								 {{item.name}}
							</div>
						</template>
						
					</div>
				</div>
			</div>
		</div>
		<div class="all padding-20">
			<el-form :inline="true" label-width="60px">
				<el-form-item label="时间">
					<el-date-picker
						size="medium"
						v-model="formData.time_range"
						type="daterange"
						value-format="yyyy-MM-dd"
						range-separator="至"
						:clearable="false"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
						:picker-options="instantPickerOptions"
					></el-date-picker>
				</el-form-item>
				<el-form-item label="部门">
					<el-cascader
						size="medium"
						v-model="dept_name"
						:options="dept_tree"
						:props="{ checkStrictly: true, value: 'id', label: 'name', children: '_child' }"
						ref="dept"
						clearable
						filterable
						placeholder="全公司"
					></el-cascader>
				</el-form-item>
				<el-form-item label="人员">
					<el-select style="width: 300px;" size="medium" multiple  v-model="employeeId" placeholder="请输入或选择人员">
						<el-option v-for="item in employee_map" :key="item.id" :label="item.name" :value="item.id"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<div  class="flex-box-end">
				<el-button size="small" @click="dialogVisible=true"  plain type="primary">打印配置</el-button>
				<el-button size="small"  type="primary" @click="printFn">打印</el-button>
			</div>
			<el-table :data="list" style="width: 100%;cursor: pointer;" v-loading="loading" @selection-change="deleteEvents">
				<el-table-column width="50" type="selection"></el-table-column>
				<el-table-column label="姓名" align="left">
					<template slot-scope="scope">
						<div class="flex-box">
							<userImage :user_name="scope.row.employee_name" :img_url="scope.row.employee_img_url" width="50px" height="50px"></userImage>
							<span style="line-height: 50px; padding-left: 10px;">{{ scope.row.employee_name }}</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column show-overflow-tooltip label="部门" align="left" min-width="120px" prop="deptName"></el-table-column>
				<el-table-column label="奖票事件" align="left" prop="point"></el-table-column>
				<el-table-column label="积分" align="left" prop="point"></el-table-column>
				<el-table-column label="奖票时间" align="left" prop="point"></el-table-column>
				<el-table-column label="发放人" align="left" prop="point"></el-table-column>
				<el-table-column label="状态">
					<template slot-scope="scope">
						<span  class="blue" style="cursor: pointer;">查看详情</span>
					</template>
				</el-table-column>
				<template slot="empty">
					<div class="nopoint_box">
						<div class="noimg noperson"></div>
						<span class="title">没有对应的数据</span>
					</div>
				</template>
			</el-table>
			<center style="padding: 20px 0;">
				<el-pagination
					background
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="page"
					:page-sizes="[10, 20, 50, 100]"
					layout="total, sizes, prev, pager, next"
					:page-size="page_size"
					:total="total"
				></el-pagination>
			</center>
		</div>
		<!-- 打印配置 -->
		<el-dialog title="打印配置" :visible.sync="dialogVisible" width="900px">
			<div class="flex-box-ce">
				<div class="flex-box-ce flex-1">
					<div class="input-item" :class="selectInput.id==item.id? 'activeInput':''"  @click="selectInput=item" style="margin-right: 10px;position: relative;" v-for="item in inputs" :key="item.id">{{item.name}}</div>
				</div>
				<div class="flex-box-ce">
					<div class="flex-box-ce">
						<div class="label">奖票宽</div>
						<el-input style="width: 60px;" size="small" v-model="printW" @input="[checkCountry($event, 1),(printW = printW.match(/\d+(\.\d{0,1})?/) ? printW.match(/\d+(\.\d{0,1})?/)[0] : '')]"></el-input>
						<span style="font-size: 12px;position: relative;top: 5px;left: 5px;">cm</span>
					</div>
					<div class="flex-box-ce" style="margin-left: 30px;">
						<div class="label">奖票高</div>
						<el-input style="width: 60px;" size="small" v-model="printH" @input="[checkCountry($event, 2),(printH = printH.match(/\d+(\.\d{0,1})?/) ? printH.match(/\d+(\.\d{0,1})?/)[0] : '')]"></el-input>
						<span style="font-size: 12px;position: relative;top: 5px;left: 5px;">cm</span>
					</div>
				</div>
			</div>	
			<div class="flex-box-ce" style="margin: 20px 0;">
				<div class="flex-box-ce">
					<div class="label">X</div>
					<el-input style="width: 60px;" size="small" v-model.number="selectInput.x" @input="[checkCountry($event, 3),(selectInput.x = selectInput.x.match(/\d+(\.\d{0,1})?/) ? selectInput.x.match(/\d+(\.\d{0,1})?/)[0] : '')]"></el-input>
					<span style="font-size: 12px;position: relative;top: 5px;left: 5px;">cm</span>
				</div>
				<div class="flex-box-ce" style="margin-left: 20px;">
					<div class="label">Y</div>
					<el-input style="width: 60px;" size="small" v-model="selectInput.y" @input="[checkCountry($event, 4),(selectInput.y = selectInput.y.match(/\d+(\.\d{0,1})?/) ? selectInput.y.match(/\d+(\.\d{0,1})?/)[0] : '')]"></el-input>
					<span style="font-size: 12px;position: relative;top: 5px;left: 5px;">cm</span>
				</div>
				<div class="flex-box-ce" style="margin-left: 20px;" v-if="selectInput.id==2">
					<div class="label">宽</div>
					<el-input style="width: 60px;" size="small" v-model="selectInput.w" @input="[checkCountry($event, 5),(selectInput.w = selectInput.w.match(/\d+(\.\d{0,1})?/) ? selectInput.w.match(/\d+(\.\d{0,1})?/)[0] : '')]"></el-input>
					<span style="font-size: 12px;position: relative;top: 5px;left: 5px;">cm</span>
				</div>
				<div class="flex-1"></div>
				<el-popover placement="top-end" width="800" trigger="hover">
				  <div><img src="@/assets/image/321.jpg" style="width: 100%;"/></div>
				  <div class="blue cursor" slot="reference">检查单示例</div>
				</el-popover>
				
			</div>
			<div style="width: 100%;height: 10cm;background-color: #f1f1f1;position: relative;">
				<div :style="{width:printW+'cm',height:printH+'cm'}" style="position:relative;background-color: #fff;margin: 0 auto;top: 50%;transform: translate(0, -50%);">
					<template v-for="item in inputs">
						<div class="input-item" style="height: 2.33rem;" v-if="item.id==2" :class="{activeInput:item.id==selectInput.id}" :style="{left:item.x+'cm',top:item.y+'cm',width:item.w? item.w+'cm':'auto'}">
							 {{item.name}}
						</div>
						<div v-else class="input-item" :class="{activeInput:item.id==selectInput.id}" :style="{left:item.x+'cm',top:item.y+'cm',width:item.w? item.w+'cm':'auto'}">
							 {{item.name}}
						</div>
					</template>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false" size="medium">取 消</el-button>
				<el-button type="primary" @click="sumbit" size="medium">保 持</el-button>
			</span>
		</el-dialog>
		
		<el-dialog @close="closeCode"  :visible.sync="innerVisible" width="444px">
			<div style="border-radius: 15px;border: 1px solid #f1f1f1;padding: 10px; width: 346px;box-sizing: border-box;margin: 0 auto;">
				<div id="qrcode" ref="qrcode"></div>
			</div>
			<div style="margin-top: 10px;text-align: center;color: #666;">请使用钉钉APP扫描二维码</div>
		</el-dialog>
	</div>
</template>
<script>
import moment from 'moment';
import QRCode from 'qrcodejs2';
export default {
	data() {
		return {
			instantPickerOptions: {
				shortcuts: [
					{
						text: '今天',
						onClick(picker) {
							const now = new Date(new Date().toLocaleDateString());
							const start = now.getTime();
							picker.$emit('pick', [moment(start).format('YYYY-MM-DD'), moment(start).format('YYYY-MM-DD')]);
						}
					},
					{
						text: '昨天',
						onClick(picker) {
							const now = new Date(new Date().toLocaleDateString());
							const start = now.getTime() - 60 * 60 * 24 * 1000;
							picker.$emit('pick', [moment(start).format('YYYY-MM-DD'),moment(start).format('YYYY-MM-DD')]);
						}
					},
					{
						text: '本周',
						onClick(picker) {
							const now = new Date(new Date().toLocaleDateString());
							const start = now.getTime() - (now.getDay() - 1) * 24 * 60 * 60 * 1000;
							const end = start + 7 * 24 * 60 * 60 * 1000 - 1000;
							picker.$emit('pick', [moment(start).format('YYYY-MM-DD'), moment(end).format('YYYY-MM-DD')]);
						}
					},
					{
						text: '上周',
						onClick(picker) {
							const now = new Date(new Date().toLocaleDateString());
							const start = now.getTime() - (now.getDay() + 6) * 24 * 60 * 60 * 1000;
							const end = start + 7 * 24 * 60 * 60 * 1000 - 1000;
							picker.$emit('pick', [moment(start).format('YYYY-MM-DD'), moment(end).format('YYYY-MM-DD')]);
						}
					},
					{
						text: '本月',
						onClick(picker) {
						const now = new Date();
							const startDate = new Date(now.getFullYear(), now.getMonth(), 1);
							const endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0);
							picker.$emit('pick', [moment(startDate.getTime()).format('YYYY-MM-DD'), moment(endDate.getTime()).format('YYYY-MM-DD')]);
						}
					},
					{
						text: '上月',
						onClick(picker) {
							const now = new Date();
							const startDate = new Date(now.getFullYear() - (now.getMonth() > 0 ? 0 : 1), (now.getMonth() + 11) % 12, 1);
							const endDate = new Date(now.getFullYear(), now.getMonth(), 0);
							picker.$emit('pick', [moment(startDate.getTime()).format('YYYY-MM-DD'), moment(endDate.getTime()).format('YYYY-MM-DD')]);
						}
					},
					{
						text: '本季',
						onClick(picker) {
							const quarter=Math.ceil((new Date().getMonth()+1)/3)
							let str=moment().format(`YYYY-${(quarter-1)*3+1}-01`);
							let ent=moment(moment().format(`YYYY-${(quarter-1)*3+1}-01`)).add(2,`month`).endOf('month').format("YYYY-MM-DD");
							console.log(str,ent)
							picker.$emit('pick',[str,ent]);
						}
					},
					{
						text: '本年',
						onClick(picker) {
							let year=moment().format('YYYY');
							picker.$emit('pick', [year+'-01-01',year+'-12-31']);
						}
					},
				],
			    onPick: (obj) => {
					if(!this.dialogVisible){
			       	  	this.pickerMinDate = new Date(obj.minDate).getTime();
					}
			    },
				disabledDate : time => {
			        if (this.pickerMinDate && !this.dialogVisible) {
			            const day1 =  30 * 24 * 3600 * 1000//限制只能选一个月的范围区间
			            let maxTime = this.pickerMinDate + day1
			            let minTime = this.pickerMinDate - day1
			            return time.getTime() > maxTime || time.getTime()<minTime
			        }
				}
			},
			total:0,
			page: 1,
			page_size: 10,
			formData: {
				dept_id: '0',
				time_range: []
			},
			dept_name: [],
			dept_tree: [],
			loading: false,
			list:[],
			employee_map: this.$getCache('SET_EMPLOYEE_MAP'),
			employeeId:[],
			dialogVisible:false,
			printW:18,
			printH:7.5,
			inputs:{
				name:{name:'姓名',x:1,y:1.4,w:0,id:1},
				event:{name:'奖票事件',x:1,y:2.4,w:15,id:2},
				point:{name:'积分分值',x:1,y:3.9,w:0,id:3},
				name2:{name:'发放人',x:15,y:4.9,w:0,id:4},
				date:{name:'奖票日期',x:15,y:5.9,w:0,id:5},
			},
			selectInput:{name:'姓名',x:1,y:1.4,w:0,id:1},
			innerVisible:false,
			selectionItems:[1,2,3,4,5,6],
			isPrint:false,
		};
	},
	watch: {
		'formData.time_range'(){
			this.selectBtn();
		},
		dept_name(val) {
			if (val.length !== 0) {
				this.formData.dept_id = val[val.length - 1];
			} else {
				this.formData.dept_id = 0;
			}
			this.employeeId=[];
			this.$nextTick(() => {
				this.$refs.dept.dropDownVisible = false;
				this.getEmployeeList();
				this.selectBtn();
			});
		},
	},
	methods: {
		printFn() {
			//传入dom结构即可
			this.isPrint=true;
			this.$nextTick(()=>{
				this.$print(this.$refs.print);
				this.isPrint=false;
			})
		},
		ruleQRcode() {
			this.innerVisible = true;
			// 使用$nextTick确保数据渲染
			this.$nextTick(() => {
				this.payOrder();
			});
		},
		payOrder () {// 展示二维码
			let url = 'dingtalk://dingtalkclient/action/open_micro_app'
			let appid = '?appId='+this.$appId
			let corpId = '&corpId='+this.$getCache('corpId')
			let page = '&page='+encodeURIComponent(`pages/reportBox/report/report?employee_id=${encodeURIComponent(this.$getUserData().id)}`)//encodeURIComponent('小米')
			let urls = url+appid+corpId+page
			var qrcode = new QRCode('qrcode', {
				text: urls, // 二维码内容
				width: 325,
				height: 325,
				render: 'table', // 设置渲染方式（有两种方式 table和canvas，默认是canvas）
				colorDark: '#34373e', // 二维码色
				colorLight: '#ffffff', // 背景色
				correctLevel: QRCode.CorrectLevel.H // 容错等级，H是heigh，最高，所以二维码看起来很密
			})
		},
		// 关闭弹框,清除已经生成的二维码
		closeCode() {
			setTimeout(() => {
				this.$refs.qrcode.innerHTML = '';
			}, 150);
		},
		checkCountry(e,index) {
		  if(index==1){
			  if(this.printW > 22){
			  	this.printW='22';
			  }
		  }
		  if(index==2){
			  if(this.printH > 9){
				this.printH='9';
			  }
		  }
		},
		deleteEvents(selection) {
			this.selectionItems = selection;
			this.selectionID = selection.map(item => {
				return item.id;
			});
		},
		selectBtn(){
			this.page=1;
			this.get_list();
		},
		getEmployeeList() {
			this.$axios('get', '/api/employee/list', { dept_id: this.formData.dept_id }).then(res => {
				this.employee_map = res.data.data.list;
			});
		},
		sumbit(){
			
		},
		//请求数据
		get_list() {
			let data={
				page:this.page,
				page_size:this.page_size
			};
			this.loading = true;
			this.$axios('get', '/api/integral/statistics/ranking', data, 'v2').then(res => {
				this.labelName = this.formData.pt_id == 2 ? 'A分' : 'B分';
				if (res.data.code == 1) {
					this.list =this.$returnDeptName(res.data.data.list);
					this.total = res.data.data.total;
				} else {
					this.$message.error(res.data.data.msg);
				}
			})
			.finally(() => {
				this.loading = false;
			});
		},
		//获取部门
		getDepartment() {
			this.$axios('get', '/api/department/tree').then(res => {
				this.dept_tree = this.getTreeData(res.data.data.list);
			});
		},
		// 递归判断列表，把最后的children设为undefined
		getTreeData(data) {
			for (var i = 0; i < data.length; i++) {
				data[i].obj = { id: data[i].id, name: data[i].name };
				if (data[i]._child.length < 1) {
					// children若为空数组，则将children设为undefined
					data[i]._child = undefined;
				} else {
					// children若不为空数组，则继续 递归调用 本方法
					this.getTreeData(data[i]._child);
				}
			}
			return data;
		},
		// 页面变更
		handleCurrentChange(val) {
			this.page = val;
			this.get_list();
		},
		handleSizeChange(val) {
			this.page = 1;
			this.page_size = val;
			this.get_list();
		},
	},
	created() {
		if(this.$getToken()){
			this.getEmployeeList();
			this.getDepartment();
		}else{
			this.innerVisible=true;
		}
	},
	mounted() {
		
	    
	}
};
</script>
<style scoped lang="scss">
.print_img{
  width: 20cm;
  height: 10cm;
  text-align: center;
  border: 1px solid #000;
  z-index: 9;
}	
.print-box{
	margin: auto;
	background-color: #fff;
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
}	
.input-item{
	background: #f4f4f5;
	border-radius: 4px;
	padding:6px 10px;
	cursor: pointer;
	color: #909399;
	position: absolute;
}
.activeInput{
	background-color: #ECF5FF;
	color: #26a2ff;
}
.label{
	text-align: right;
	vertical-align: middle;
	float: left;
	font-size: 14px;
	color: #606266;
	line-height: 40px;
	padding: 0 12px 0 0;
	box-sizing: border-box;
	font-weight: 600;
}
.search_box {
	::v-deep button:active {
		background: #26a2ff;
	}
	::v-deep button:active .el-icon-search {
		color: #fff;
	}
}
.date-picker-width {
	width: 100% !important;
}
.nopoint_box {
	display: inline-block;
	text-align: center;
	width: 100%;
	margin-bottom: 10px;
}
.noimg {
	display: inline-block;
	width: 110px;
	height: 110px;
	margin: 22px auto 16px;
	/* background:url("/static/images/nodata_default.png") no-repeat center; */
	background-size: 99%;
}
.noperson {
	display: inline-block;
	width: 110px;
	height: 110px;
	line-height: none;
	margin: 22px auto 16px;
	background: url('/static/images/noperson_default.png') no-repeat center;
	background-size: 99%;
}
.title {
	display: block;
	text-align: center;
	font-size: 12px !important;
	line-height: 30px;
	color: #909399 !important;
	padding: 0;
}
.nopoint_box a {
	color: #26a2ff;
}
.chart_content {
	.chart-legend__wrap {
		text-align: right;
		padding: 20px;
		padding-right: 50px;
		& .chart-legend__pink {
			position: relative;
			padding-left: 12px;
			padding-right: 5px;
			&:after {
				content: '';
				position: absolute;
				margin-top: -2px;
				top: 35%;
				left: 0;
				width: 8px;
				height: 8px;
				background: #f56c6c;
				border-radius: 100%;
			}
		}

		& .chart-legend__green {
			position: relative;
			padding-left: 12px;
			&:after {
				content: '';
				position: absolute;
				margin-top: -2px;
				top: 35%;
				left: 0;
				width: 8px;
				height: 8px;
				background: #53b87f;
				border-radius: 100%;
			}
		}
	}
}
.drawer_title {
	font-size: 18px;
	padding: 20px;
}
.manager_statistics_box {
	background-color: #ffffff;
	padding: 20px;
	min-height: calc(100vh - 160px);
	::v-deep .el-row .el-checkbox .el-checkbox__label {
		line-height: 20px;
	}
}
.diy_tip_bg {
	background: #f5f6f9;
	overflow: hidden;
	.diy-tip {
		margin-bottom: 15px;
		border: 1px solid #67c23a;
		padding: 20px 16px;
		p {
			color: #67c23a !important;
			font-size: 14px;
			margin: 0 !important;
			padding: 4px 0;
		}
	}
}
::v-deep .el-dialog {
	// top: 21%;
}
.picker_er {
	margin-top: 20px;
}
.el-range-editor--medium.el-input__inner {
	width: 280px;
}
::v-deep .el-cascader .el-input .el-input__inner {
	width: 150px;
}
.el-checkbox.is-bordered.el-checkbox--medium {
	padding: 9px 20px 7px 10px;
}
</style>
