<template>
	<div>
		<div class="all">
			<el-form ref="form" :inline="true" label-width="80px">
			  <el-form-item label="规则分类">
			    <el-cascader
			    	class="date-picker-width"
			    	v-model="rule"
			    	:options="rule_trees"
			    	:props="props"
			    	@change="rule_null"
					size="medium"
			    	ref="rule"
			    	clearable
			    	placeholder="全部规则分类"
			    ></el-cascader>
			  </el-form-item>
			  <el-form-item label="积分分类">
				  <el-select class="date-picker-width" size="medium" v-model="formData.pt_id" clearable placeholder="请选择积分分类">
				  	<el-option v-for="item in point_types" :key="item.name" :label="item.name" :value="item.id"></el-option>
				  </el-select>
			  </el-form-item>
			  <el-form-item label="部门">
				  <el-cascader
				    size="medium"
				  	class="date-picker-width"
				  	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="时间" style="margin-top: 1px;">
				  <el-date-picker
				  	v-model="time_slot"
				  	type="daterange"
					size="medium"
				  	value-format="yyyy-MM-dd"
				  	range-separator="至"
				  	start-placeholder="开始日期"
				  	end-placeholder="结束日期"
				  ></el-date-picker>
			  </el-form-item>
			  <el-form-item style="margin-top: 2px;">
				  <el-input size="medium" v-model="formData.keyword" placeholder="输入同事姓名" max="200" @keyup.enter.native="keyWordSelect" class="persons_name">
				  	<el-button size="medium" slot="append" icon="el-icon-search" @click="keyWordSelect"></el-button>
				  </el-input>
			  </el-form-item>
			  <el-form-item>
				  <el-button type="success" size="medium" @click="excelImportShow = true" plain>导入数据</el-button>
				  <el-button type="primary" size="medium" @click="exportExcel" plain>导出当前数据</el-button>
				  <!-- <el-button type="primary" size="medium" plain @click="swiperShow = true">轮播事件</el-button> -->
			  </el-form-item>
			</el-form> 
			 <!-- 表格 -->
			<div>
				<el-table :data="list" style="width: 100%" v-loading="loading" @row-click="open_detail">
					<el-table-column prop="employee_name" label="姓名" align="left" width="200px">	
						<template slot-scope="scope">
							<div class="flex-box">
								<userImage	class="fl" :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 prop="dept" label="部门" align="left" width="200px"></el-table-column>
					<el-table-column prop="point" label="积分" align="left" width="80px">
						<template slot-scope="scope">
							<span :class="scope.row.point < 0 ? 'color_green' : 'color_red'">{{ scope.row.point }} {{ point_name(scope.row.pt_id) }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="remark" show-overflow-tooltip label="事件" align="left"></el-table-column>
					<el-table-column prop="source_type" label="来源" align="left" width="120px">
						<template slot-scope="scope">
							<span v-show="scope.row.source_type == 1">积分录入</span>
							<span v-show="scope.row.source_type == 2">任务</span>
							<span v-show="scope.row.source_type == 3">积分系统分配</span>
							<span v-show="scope.row.source_type == 4">考勤系统分配</span>
							<span v-show="scope.row.source_type == 5">积分申请</span>
							<span v-show="scope.row.source_type == 6">绩效任务包</span>
							<span v-show="scope.row.source_type > 6">其他</span>
						</template>
					</el-table-column>
					<el-table-column prop="create_time" label="录入时间" align="left" width="110px">
						<template slot-scope="scope">
							{{ cuttString(scope.row.create_time) }}
						</template>
					</el-table-column>
				
					<template slot="empty">
						<noData></noData>
					</template>
				</el-table>
				<center class="pagination">
					<el-pagination
						background
						@size-change="handleSizeChange"
						@current-change="handleCurrentChange"
						:current-page="formData.page"
						:page-sizes="[10, 20, 30, 40, 50, 100]"
						layout="total, sizes, prev, pager, next"
						:page-size="pageLimit"
						:total="total"
					></el-pagination>
				</center>
			</div>
		</div>
		<el-drawer title="事件详情" :visible.sync="detail_popup" ref="drawer" :with-header="false" :width="'500px'" direction="rtl">
			<div class="drawer_title">事件详情</div>
			<div class="detail_popup" v-loading="detail_loading" v-if="detail_info !== null">
				<el-row style="padding-bottom:10px;border-bottom:1px #f8f8f8 solid;">
					<div class="flex-box flex-v-ce">
						<userImage :user_name="detail_info.employee_name" width="50px" height="50px" fontSize="1"></userImage>
						<span style="font-size: 18px;line-height:50px; margin-left:10px;margin-right:4px;">{{ detail_info.employee_name }}</span>
						<span class="color_red point" v-show="detail_info.point >= 0">+{{ detail_info.point }} {{ point_name(detail_info.pt_id) }}</span>
						<span class="color_green point" v-show="detail_info.point < 0">{{ detail_info.point }} {{ point_name(detail_info.pt_id) }}</span>
					</div>
				</el-row>

				<el-row>
					<el-col :span="6">任务描述</el-col>
					<el-col :span="18" v-if="detail_info.remark">{{ detail_info.remark && (detail_info.remark.customize || detail_info.remark.rule) }}</el-col>
				</el-row>

				<el-row>
					<el-col :span="6">规则分类</el-col>
					<el-col :span="18">{{ detail_info.rule_list }}</el-col>
				</el-row>

				<el-row v-show="detail_info.rule_list">
					<el-col :span="6">事件时间</el-col>
					<el-col :span="18">{{ detail_info.date }}</el-col>
				</el-row>

				<el-row v-show="detail_info.source_type_mark">
					<el-col :span="6">来源类型</el-col>
					<el-col :span="18">{{ detail_info.source_type_mark }}</el-col>
				</el-row>

				<el-row v-show="!detail_info.rule_id">
					<el-col :span="6">记录人</el-col>
					<el-col :span="18">{{ detail_info.employee_name }}</el-col>
				</el-row>

				<el-row v-show="detail_info.files !== null && detail_info.files.length > 0">
					<el-col :span="6">图片</el-col>
					<el-col :span="18"><el-image style="width: 100px; height: 100px" :src="detail_info.files[0]" :preview-src-list="detail_info.files"></el-image></el-col>
				</el-row>

				<div v-show="detail_info.rule_id">
					<p class="row_title">规则依据</p>
					<el-row>
						<el-col :span="6">规则分类</el-col>
						<el-col :span="18">{{ detail_info.rule_list }}</el-col>
					</el-row>
					<el-row v-show="detail_info.remark.rule">
						<el-col :span="6">积分规则</el-col>
						<el-col :span="18">{{ detail_info.remark.rule }}</el-col>
					</el-row>
					<el-row>
						<el-col :span="6">积分</el-col>
						<el-col :span="18" v-show="detail_info.rule_item.min_point == detail_info.rule_item.max_point">{{ detail_info.rule_item.min_point }}</el-col>
						<el-col :span="18" v-show="detail_info.rule_item.min_point != detail_info.rule_item.max_point">
							{{ detail_info.rule_item.min_point }} ~ {{ detail_info.rule_item.max_point }}
						</el-col>
					</el-row>
				</div>

				<div v-show="detail_info.rule_id">
					<p class="row_title">
						审批
						<span class="row_tips">多人审批时，以最后一人为准</span>
					</p>
					<div class="examine_steps">
						<el-steps direction="vertical" :space="50">
							<el-step v-for="(item, index) in detail_info.process" :key="index" style="margin-bottom: 5px;">
								<template slot="icon">
									<userImage width="36px" height="36px" :img_url="item.img_url" :user_name="item.name"></userImage>
								</template>
								<template slot="title">
									<div style="color: #303133;font-size:14px;margin-top:-2px;">
										{{ item.name }} {{ item.remark }}
										<strong v-show="item.point !== 0" style="font-weight: 500;">
											<span class="color_red point" v-show="item.point >= 0">+{{ item.point }}</span>
											<span class="color_green point" v-show="item.point < 0">{{ item.point }}</span>
										</strong>
									</div>
								</template>
								<template slot="description" style="">
									{{ item.time }}
								</template>
							</el-step>
						</el-steps>
					</div>
				</div>
				<div style="position: absolute; bottom: 20px; display: block; right: 20px;">
					<el-button @click="close_integral_event">取消</el-button>
					<el-button type="danger" @click="del_integral_event(detail_info)">删除</el-button>
				</div>
			</div>
		</el-drawer>

		<!-- 导入数据 -->
		<el-dialog title="导入积分事件数据" width="600px" :visible.sync="excelImportShow" :close-on-click-modal="false" :before-close="close_import">
			<div style="padding:0 50px;">
				<div class="flex-box flex-v-ce margin-bottom">
					<div style="margin-right: 10px;">1、下载积分事件模版，批量录入积分事件</div>
					<el-button size="medium" type="primary" @click="downloadTemplate"  plain>下载模板</el-button>
				</div>
				<div class="margin-bottom">
					<el-upload  
					:limit="1" 
					:headers="ATOKEN" 
					ref="upload" 
					:action="action" 
					:on-remove="handleRemove"
					:on-success="handlePictureCardPreview" 
					:file-list="fileList"
					:before-upload="beforeFilesUpload">
						<p>2、上传积分事件数据Excel表<el-button  style="margin-left: 10px;" size="medium" type="primary" plain>选择文件</el-button></p>
					</el-upload>
				</div>
				<!-- <div>3、选择文件后点击下方【上传】按钮</div> -->
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="close_import"  size="medium">取 消</el-button>
				<!-- <el-button type="primary" @click="uploadFile()"  size="medium" :loading="update_btn">上传</el-button> -->
			</div>
		</el-dialog>

		<el-dialog title="导入错误信息" :visible.sync="importErrorInfoShow" width="30%">
			<div>
				<el-table :data="error_list" border stripe>
					<el-table-column prop="name" label="错误信息">
						<template slot-scope="scope">
							{{ scope.row }}
						</template>
					</el-table-column>
				</el-table>
			</div>
			<span slot="footer"><el-button type="primary"  size="medium" @click="importErrorInfoShow = false">确 定</el-button></span>
		</el-dialog>

		<el-dialog title="轮播事件" :visible.sync="swiperShow" width="500px">
			<div>
				<el-row>
					<el-col :span="5" style="line-height: 36px;">仅展示最新的</el-col>
					<el-col :span="6">
						<el-select v-model="page_size" placeholder="请选择">
							<el-option v-for="item in swiperPageList" :key="item.value" :label="item.value" :value="item.value"></el-option>
						</el-select>
					</el-col>
					<el-col :span="6" style="line-height: 36px;">条积分事件来轮播</el-col>
				</el-row>
			</div>
			<span slot="footer">
				<el-button  size="medium" @click="swiperShow = false" style="margin-right: 10px;">取 消</el-button>
				<router-link :to="{ path: '/deptRankSwiper?' + '&page=1&page_size=' + this.page_size + '&type=1' }" target="_blank">
					<el-button  size="medium" type="primary">开始轮播</el-button>
				</router-link>
			</span>
		</el-dialog>
	</div>
</template>
<script>
import noData from '@/components/noData';
export default {
	data() {
		return {
			action:process.env.VUE_APP_BASE_API+'api/integral/import',
			ATOKEN: { 'A-TOKEN': this.$getToken(),'Accept':'application/vnd.test.v2+json' },
			
			loading: false,
			swiperShow: false,
			swiperPageList: [{ value: '10' }, { value: '30' }, { value: '50' }],
			page_size: 10,
			point_types: this.$getTyps(),
			dept_name: [],
			dept_tree: [],
			formData: {
				page: 1,
				page_size: 10
			},
			time_slot: null,
			rule_trees: [],
			props: {checkStrictly: true, value: 'id', label: 'name', children: 'child' },
			rule: [],
			list: [],
			total: null,
			detail_info: null,
			detail_popup: false,
			detail_loading: false,
			pageLimit: 10,
			excelImportShow: false,
			update_btn: false,
			error_list: [],
			importErrorInfoShow: false,
			fileList: [],
		};
	},
	components: { noData },
	created() {},
	mounted() {
		this.getDepartment();
		this.get_rule_trees();
		this.get_integral_list(this.formData);
	},
	watch: {
		'formData.pt_id'(val, old_val) {
			this.formData.page = 1;
			!val ? delete this.formData.pt_id : '';
			this.get_integral_list(this.formData);
		},
		'formData.page'(val, old_val) {
			this.get_integral_list(this.formData);
		},
		time_slot(val, old_val) {
			this.formData.page = 1;
			if (val !== null) {
				this.formData.start_day = val[0];
				this.formData.end_day = val[1];
			} else {
				delete this.formData.start_day;
				delete this.formData.end_day;
			}
			this.get_integral_list(this.formData);
		},
		dept_name(val, old_val) {
			this.formData.page = 1;
			if (val.length !== 0) {
				this.formData.dept_ids = val[val.length - 1];
			} else {
				this.formData.dept_ids = 0;
			}
			this.$nextTick(() => {
				this.$refs.dept.dropDownVisible = false;
				this.get_integral_list(this.formData);
			});
		}
	},
	methods: {
		handleRemove(file, fileList) {
			// if (fileList !== null && fileList.length != 0) {
			// 	this.import_btn_show = true;
			// } else {
			// 	this.import_btn_show = false;
			// }
		},
		// 导入相关
		close_import() {
			this.excelImportShow = false;
			this.$refs.upload.clearFiles();
		},
		// keyword
		keyWordSelect() {
			this.formData.page = 1;
			this.get_integral_list(this.formData);
		},
		downloadTemplate() {
			window.open(process.env.VUE_APP_BASE_API+'api/download/integral/template',);
		},
		uploadFile() {
			let params = {};
			params.file = this.file;
			this.update_btn = true;
			this.$axios("post",'/api/integral/import', params,'v2').then(res => {
					if (res.data.code == 1) {
						if (res.data.data.error.length == 0) {
							this.$message({ type: 'success', message: '导入成功' });
							this.excelImportShow = false;
						} else {
							this.$message({ type: 'error', message: '导入错误' });
							this.error_list = res.data.data.error;
							this.importErrorInfoShow = true;
						}
					} else {
						this.$message({ type: 'error', message: res.data.msg });
					}
				}).finally(() => {
					setTimeout(() => {
						this.update_btn = false;
					}, 3000);
				});
		},
		handlePictureCardPreview(response) {
			if (response.code == 1) {
				if(response.data.error.length>0){
					var htmls=response.data.error;
					var str="<div class='red'></div>";
					htmls.forEach(item=>{
						str+=`<div>${item}</div>`;
					})
					this.close_import();
					this.$notify.error({
					          title: '导入错误',
					          dangerouslyUseHTMLString: true,
					          message: str,
							  duration:0,
							  offset:50,
							  customClass:'notifyBox',
					});
				}else{
					this.file = response.data;
					this.$message.success({ message: response.msg });
					this.keyWordSelect();
					this.close_import();
				}
			}
		},
		beforeFilesUpload(file) {
			const $ext_list = ['xlsx', 'xls'];
			let len = file.name.split('.').length - 1;
			const $ext_name = file.name.split('.')[len];
			if ($ext_list.indexOf($ext_name) != -1) {
			} else {
				this.$message.warning('文件格式上传错误,仅支持上传xlsx,xls）');
				return false;
			}
		},
		onFilePreView() {},
		exportExcel() {
			window.open(process.env.VUE_APP_BASE_API +'api/download/integral?employee_id='+this.$getUserData().id+'&page=' +this.formData.page +
					'&page_size=' +
					this.formData.page_size +
					(this.formData.rule_id ? '&rule_id=' + this.formData.rule_id : '') +
					(this.formData.pt_id ? '&pt_id=' + this.formData.pt_id : '') +
					(this.formData.dept_ids ? '&dept_ids=' + this.formData.dept_ids : '') +
					(this.formData.start_day ? '&start_day=' + this.formData.start_day : '') +
					(this.formData.end_day ? '&end_day=' + this.formData.end_day : '') +
					(this.formData.keyword ? '&keyword=' + this.formData.keyword : ''),
				'_blank'
			);
		},
		// end 文件上传
		handleSizeChange(val) {
			this.pageLimit = val;
			this.formData.page_size = this.pageLimit;
			this.get_integral_list(this.formData);
		},
		cuttString(data) {
			return data.substring(5);
		},
		open_detail(item) {
			this.detail_popup = true;
			let data = {
				event_id: item.id
			};
			this.detail_loading = true;
			this.$axios("get",'/api/integral/statistics/integral/info',data).then(res => {
					if (res.data.code == 1) {
						this.detail_info = res.data.data;
					} else {
						this.$message.error(res.data.data.msg);
					}
				})
			.finally(() => {
					this.detail_loading = false;
			});
		},
		//获取部门
		getDepartment() {
			this.$axios('get','/api/department/tree').then(res => {
				this.dept_tree =this.getTreeData(res.data.data.list);
			});
		},
		//获取规则
		get_rule_trees() {
			this.$axios('get','/api/integral/rule/trees').then(res => {
				this.rule_trees =this.getRuleTreeData(res.data.data.rule_tree);
			});
		},
		get_integral_list(data) {
			this.loading = true;
			this.$axios('get','/api/integral/statistics/integral',data).then(res => {
					if (res.data.code == 1) {
						this.list = res.data.data.list;
						this.total = res.data.data.total;
					} else {
						this.$message.error(res.data.data.msg);
					}
				})
				.finally(() => {
					this.loading = false;
				});
		},
		handleCurrentChange(val) {
			this.formData.page = val;
		},
		rule_null(val) {
			if (val.length == 0) {
				this.formData.rule_id = 0;
			} else {
				this.formData.rule_id = this.rule[this.rule.length - 1];
			}
			this.$nextTick(() => {
				this.$refs.rule.dropDownVisible = false;
				this.get_integral_list(this.formData);
			});
		},
		del_integral_event(item) {
			this.$confirm('删除事件的同时也会撤销积分，确定删除吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$axios("post",'/api/integral/statistics/integral/destroy',{ event_id: item.event_id }).then(res => {
						if (res.data.code == 1) {
							this.$message.success(res.data.msg);
							this.detail_popup = false;
							this.get_integral_list(this.formData);
						} else {
							this.$message.error(res.data.msg);
						}
				})
			});
		},
		close_integral_event() {
			this.detail_popup = false;
		},
		point_name(id) {
			
			return this.point_types.find(item => {
				if (item.id == id) {
					return item.name;
				}
			}).name;
		},
		// 递归判断列表，把最后的children设为undefined
		getTreeData(data) {
			for (var i = 0; i < data.length; i++) {
				if (data[i]._child.length < 1) {
					// children若为空数组，则将children设为undefined
					data[i]._child = undefined;
				} else {
					// children若不为空数组，则继续 递归调用 本方法
					this.getTreeData(data[i]._child);
				}
			}
			return data;
		},
		// 规则递归 children
		getRuleTreeData(data) {
			for (var i = 0; i < data.length; i++) {
				if (data[i].child.length < 1) {
					// children若为空数组，则将children设为undefined
					data[i].child = undefined;
				} else {
					// children若不为空数组，则继续 递归调用 本方法
					this.getRuleTreeData(data[i].child);
				}
			}
			return data;
		},
	}
};
</script>
<style scoped lang="scss">
.all{
	padding: 20px;
}	
header.el-drawer__header {
	font-size: 18px;
	font-family: MicrosoftYaHei;
	color: #303133;
	width: 500px;
	span {
		:focus {
			outline: 0;
		}
	}
}
.display_flex {
	display: flex;
}
.label {
	line-height: 36px;
	padding-right: 10px;
}
.time_section {
	.el-range-editor {
		width: 330px;
	}
}
.color_green {
	color: #67c23a;
}
.pagination {
	padding: 20px 0;
}
.detail_popup {
	padding: 20px;
	height: 100%;
	.row_title {
		position: relative;
		margin: 0 0 20px 0;
		padding-top: 12px;
		font-size: 16px;
		color: #303133;
		line-height: 22px;
	}
	.row_title:before {
		position: absolute;
		top: 0;
		content: ' ';
		width: 100%;
		border-top: 1px #f8f8f8 solid;
	}
	.el-row {
		margin-bottom: 10px;
		font-size: 14px;
		.el-col-4 {
			color: #606266;
		}
	}
}
.color_red {
	color: #f56c6c;
}
.color_green {
	color: #67c23a;
}
span.point {
	font-size: 16px;
}
.drawer_title {
	font-size: 18px;
	padding: 20px;
	border-bottom: 1px #efefef solid;
}
.row_tips {
	display: block;
	color: #909399;
	font-size: 12px;
	margin-top: 0px;
}
.el-range-editor--medium .el-range-separator {
	width: 25px;
}
.integral_event_box {
	background-color: #ffffff;
	padding: 20px;
	min-height: calc(100vh - 160px);
}
.examine_steps ::v-deep .el-step.is-vertical .el-step__title {
	padding-bottom: 0;
}
</style>
