<template>
	<div>
		<el-alert class="diy-tip" title="什么是自动积分?" @close="tips_close" v-if="tips_show" type="success" description show-icon>
			<p>系统按照设定的时间（每月/每周/每日) 自动给员工添加B分，比如某员工有一个工程师证，得到公司的认可，公司就会每月给他加分</p>
		</el-alert>
		<div class="all">
			<div class="flex-box">
				<div class="terr-left">
					<div><el-button size="medium" @click="add_grouping()"   type="primary">新增加分组</el-button></div>
					<div><el-button size="medium" @click="add_rules_detail"   type="primary">新增加分项</el-button></div>

					<!-- 循环分组 -->
					<el-col :span="24" style="padding-right: 0;" v-loading="rule_trees_load">
						<el-menu :default-active='default_active' class="rule_name" :unique-opened="true">
							<el-submenu :index="index.toString()" :key="index" v-for="(item, index) in rule_list">
								<template slot="title">
									<div style="width: 80%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap; height: 47px;line-height: 47px;" >
										<i class="el-icon-edit-outline title_top" @click.stop="edit_grouping(item)"></i>
										<span class="title_top">{{ item.name }}</span>
									</div>
								</template>
								<el-menu-item  :key="index2" :index="returnIndex(index,index2)" v-for="(data, index2) in item.child" @click="open_rights(data)" style="height: 47px;line-height: 47px;">
										<div style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap">
											<span slot="title">{{ data.remark }}</span>
										</div>
								</el-menu-item>
							</el-submenu>
						</el-menu>
					</el-col>
				</div>

				<div class="terr-right border-right flex-1" v-loading="table_loading">
					<el-col :span="24" v-show="rule_list.length == 0 || isShowAdd"  style="text-align: center;margin: 0 auto;position: relative;top: 30%;">
						<p><img src="@/assets/image/nodata_default.png" width="200px" alt="" /></p>
						<p style="color: #909399;">
							还没有<span v-if="rule_list.length == 0">加分组和</span>加分项
						</p>
						<p style="color: #909399;">
							<span v-if="rule_list.length == 0">先</span>
							<span style="color: #26A2FF;cursor:pointer;" v-if="rule_list.length == 0" @click="add_grouping()">【新增加分组】</span>
							<span v-if="rule_list.length == 0">再</span>
							<span v-if="rule_list.length !== 0">请</span>
							<span style="color: #26A2FF;cursor:pointer" @click="add_rules_detail">【新增加分项】</span>
						</p>
					</el-col>
					
					<el-col v-if="!isShowAdd&&right_rules_detail.remark">
						<el-row>
							<el-col :span="24" style="font-size:20px;color:#303133;line-height:36px;">
								{{ right_rules_detail.remark }}
								<span style="padding-left: 10px;">{{ right_rules_detail.min_point }}B分</span>
								<el-button plain style="padding:10px 12px; margin-left: 10px;" @click="edit_rules()">编辑</el-button>
							</el-col>
						</el-row>
						<div class="flex-box btns flex-v-ce">
							<el-button size="small" @click="del_item" type="danger" plain>批量移除</el-button>
							<el-button size="small" type="primary" @click="add_employee_show=true">添加人员</el-button>
						</div>
						<el-table  ref="multipleTable"	:data="table_list"	tooltip-effect="dark"  style="width: 100%;margin-top:20px;"  @selection-change="handleSelectionChange">
							<el-table-column type="selection" width="45"></el-table-column>
							<el-table-column label="姓名">
								<template slot-scope="scope">
									<div style="display:flex">
										<span class="fl">
											<userImage
												:id="scope.row.employee_id"
												width="50px"
												height="50px"
												:user_name="scope.row.employee.name"
												:img_url="scope.row.employee.img_url"
												v-if="scope.row.employee"
											></userImage>
										</span>
										<span style="margin-left: 10px; line-height: 50px; display: inline-block" v-if="scope.row.employee">{{ scope.row.employee.name }}</span>
									</div>
								</template>
							</el-table-column>
							<el-table-column prop="cycle_remark" label="加分周期"></el-table-column>
							<template slot="empty">
								<noData></noData>
							</template>
						</el-table>

						<!-- 分页 -->
						<div style=" text-align: center; padding: 20px;">
							<el-pagination
								background
								layout="total, prev, pager, next"
								:current-page="page"
								@current-change="handleCurrentChange"
								:page-size.sync="pagesize"
								:hide-on-single-page="true"
								:total="total"
							></el-pagination>
						</div>
					</el-col>
				</div>
			</div>

			<!-- 可写公共组建： -->
			<!-- 新增加分组弹出框 -->
			<el-dialog :close-on-click-modal="false" :title="grouping_type ? '编辑加分组' : '新增加分组'" :visible.sync="dialogVisible" width="40%">
				<el-form :model="numberValidateForm" ref="numberValidateForm" label-width="100px" class="demo-ruleForm">
					<el-form-item label="加分组名称" prop="name" :rules="[{ required: true, message: '请输入加分组名称' }]">
						<el-input type="age" v-model="numberValidateForm.name"  placeholder="请输入加分组名称"></el-input>
					</el-form-item>
				</el-form>
				<span slot="footer" class="dialog-footer" style=" overflow: hidden;">
					<el-button class="fl" type="danger" v-show="grouping_type" @click="del_grouping(numberValidateForm)" style="float:left"  :loading="disabled" :disabled="disabled">删除</el-button>
					<el-button @click="dialogVisible = false">取 消</el-button>
					<el-button type="primary" @click="submitForm('numberValidateForm')" :loading="disabled" :disabled="disabled">确 定</el-button>
				</span>
			</el-dialog>

			<!-- 新增加分项 -->
			<el-dialog :title="rules_detail_title ? '编辑加分项' : '新增加分项'" :visible.sync="dialogFormVisible" width="500px">
				<el-form :model="rules_detail_form" ref="rules_detail_form" :rules="rules_rules" label-width="120px">
					<el-form-item label="加分项名称" :label-width="formLabelWidth" prop="remark">
						<el-input v-model="rules_detail_form.remark" placeholder="请输入加分项名称" ></el-input>
					</el-form-item>
					<el-form-item label="加分组" :label-width="formLabelWidth" prop="rule_id">
						<el-select v-model="rules_detail_form.rule_id" style="width: 100%;" placeholder="请选择加分组">
							<el-option v-for="item in rule_list" :key="item.value" :label="item.name" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="B分" prop="min_point">
						<el-input
							v-model="rules_detail_form.min_point"
							placeholder="请输入B分分值"
							oninput="if(this.value=='0'){this.value='';}else{this.value=this.value.replace(/[^0-9]/g,'')}"
						></el-input>
						<!-- <span data-v-a17f1960 style="display: block; font-size: 12px; color: rgb(96, 98, 102);text-align: left;">固定加分加B分</span> -->
					</el-form-item>
					<!-- <el-form-item label="是否与考勤挂钩" prop="is_attendance"><el-switch v-model="is_attendance"></el-switch></el-form-item> -->
					<div style="overflow: hidden;">
						<el-button type="danger" v-show="rules_detail_title" class="fl" @click="del_rules_detail(rules_detail_form)" style="float:left" :loading="disabled" :disabled="disabled">
							删除
						</el-button>

						<el-button v-if="rules_detail_title" class="fr" type="primary" @click="editRule('rules_detail_form')" style="float:right" :loading="disabled" :disabled="disabled">
							确 定
						</el-button>
						<el-button v-else class="fr" type="primary" @click="editRule('rules_detail_form')" style="float:right" :loading="disabled" :disabled="disabled">确 定</el-button>
						<el-button class="fr" @click="rules_detail_close('rules_detail_form')" style="float:right">取 消</el-button>
					</div>
				</el-form>
			</el-dialog>

			<el-dialog title="添加人员" :visible.sync="add_employee_show" :before-close="add_employee_close" width="700px">
				<el-form :model="add_employee_form" ref="add_employee_form" label-width="80px">
					<el-form-item label="加分周期" :rules="[{ required: true, message: '请选择加分周期', trigger: 'change' }]">
						<el-select v-model="task_cycle_name" placeholder="请选择加分周期">
							<el-option v-for="item in task_cycle" :key="item.value" :label="item.name" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
					<div v-loading="staff_loading">
						<EmployeeSelector
							v-if="add_employee_show"
							:max="add_employee_max"
							:user_no_select="false" 
							:can_select_dept="false"
							@confirm="add_employee_confirm"
							ref="Employee"
						></EmployeeSelector>
					</div>
					<el-form-item style="text-align: right; margin-bottom: 0;margin-top: 20px;">
						<el-button @click="add_employee_close()">取消</el-button>
						<el-button type="primary" @click="sub_add_employee('add_employee_form')" :loading="disabled" :disabled="disabled">完成</el-button>
					</el-form-item>
				</el-form>
			</el-dialog>
		</div>
	</div>
</template>

<script>
import EmployeeSelector from '@/components/EmployeeSelector';
import noData from '@/components/noData';
export default {
	data() {
		return {
			pd_tianjia:false,
			default_active:'0-0',
			table_list: [],
			tips_show: false,
			rule_trees_load: false,
			dialogVisible: false,

			rules_detail_show: false, //是否弹出添加人员弹窗
			add_employee_visible: false,
			add_employee_max: 0,
			add_employee_show: false,

			task_cycle_name: 1,
			add_employee_form: {
				employee_ids: []
			},
			
			isShowAdd:false,
			del_arr: {
				ids: []
			},
			val_page: '', //存入某一页文本框选中的数量
			page: 1, //默认页数  为1
			total: 0, //返回的总数据
			pagesize: 10, //每页显示的数据
			table_loading: false,
			staff_loading: false,

			dialogFormVisible: false,
			form: {
				name: '',
				region: '',
				date1: '',
				date2: '',
				delivery: false,
				type: [],
				resource: '',
				desc: ''
			},
			formLabelWidth: '120px',

			numberValidateForm: {
				name: ''
			},
			disabled: false, //按钮不能被多次点击
			grouping_type: '',
			rules_detail_title: '',
			rule_list: [], //分类集合
			item_list: [], //规则集合

			right_rules_detail: {},

			add_employee_id: '',
			rules_detail_form: {
				rule_id: '',
				range_type: '1',
				prize_type: '1',
				min_point: '',
				remark: '',
				is_attendance: '0',
				cycle_type: '2',
				pt_id: '3'
			},
			is_attendance: false,
			rules_rules: {
				remark: [
					{
						required: true,
						message: '请输入规则名称',
						trigger: 'blur'
					},
					{
						max: 100,
						message: '分类名称不能大于100个字符',
						trigger: 'blur'
					}
				],
				min_point: [
					{
						required: true,
						message: '请输入积分',
						trigger: 'blur'
					}
				],
				rule_id: [
					{
						required: true,
						message: '请选择分类',
						trigger: 'blur'
					}
				]
			},
			task_cycle: [
				{
					name: '每天自动加分',
					value: 1
				},
				{
					name: '每周自动加分',
					value: 2
				},
				{
					name: '每月自动加分',
					value: 3
				}
			]
		};
	},
	watch:{
		// add_employee_show(val){
		// 	this.add_employee_visible=val;
		// },
	},
	// computed:{
	// 	returnIndex(str,str2){
	// 		console.log(str);
	// 		return str+"-"+str2;
	// 	}
	// },
	components: {
		EmployeeSelector,
		noData
	},
	created() {},
	mounted() {
		if (localStorage.getItem('voluntarilyPoint')) {
			this.tips_show = false;
		} else {
			this.tips_show = true;
		}
		this.get_role_lists(true);
	},
	methods: {
		returnIndex(str,str2){
			return str+"-"+str2;
		},
		handleCurrentChange(val) {
			this.page = val;
			this.open_right();
		},
		open_rights(data){
			this.page=1;
			this.open_right(data);
		},
		// 组建
		add_employee_confirm(val) {
			this.add_employee_form.employee_ids = [];
			if (val.employee.length !== 0) {
				val.employee.forEach(element => {
					this.add_employee_form.employee_ids.push(element.id);
				});
			}
		},

		// 添加成员点击取消
		add_employee_close() {
			this.add_employee_show = false;
		},
		
		// 添加成员点击完成
		sub_add_employee(form) {
			let self = this;
			if (!self.task_cycle_name) {
				self.$message.error('请选择加分周期');
				return false;
			}
			this.$refs.Employee.confirm(); //调用组件的confirm（）；
			if (this.add_employee_form.employee_ids.length <= 0) {
				this.$message.error('请选择员工');
				return false;
			}
			let data = {
				employee_ids: this.add_employee_form.employee_ids,
				task_cycle: self.task_cycle_name,
				item_id: self.add_employee_id,
				rule_id: self.add_rulse_id
			};
			self.$refs[form].validate(valid => {
				if (valid) {
					if (data.rule_id == '' || data.item_id == '') {
						self.$message.error('请先选择细则');
					} else {
						this.disabled = true;
						self.staff_loading = true;
						self.$axios('post','/api/integral/auto/add',data).then(res => {
								if (res.data.code == 1) {
									self.$message.success('此次操作成功' + res.data.data.success + '条,失败' + res.data.data.error + '条,已经存在的' + res.data.data.exist + '条');
									self.open_right();
								} else {
									self.$message.error(res.data.msg);
								}
							})
							.finally(() => {
								self.add_employee_show = false;
								self.staff_loading = false;
								this.disabled = false;
							});
					}
				} else {
					return false;
				}
			});
		},
		handleSelectionChange(val) {
			this.del_arr.ids = [];
			val.forEach(element => {
				this.del_arr.ids.push(element.id);
			});
			this.val_page = val;
		},
		// 批量删除
		del_item() {
			let self = this;
			if (self.del_arr.ids.length !== 0) {
				self.$confirm('此操作将永久删除该人员的自动加分, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					self.$axios('post','/api/integral/auto/delete/many',self.del_arr).then(res => {
							if (res.data.code == 1) {
								self.$message.success(res.data.msg);
								// 判断当页的总数与选中的数量是否相等，如果相等，此页就无数据，就请求上一页的数据
								if (this.table_list.length == this.val_page.length) {
									if (this.page !== 1) {
										//判断不在第一页的时候执行
										this.page = this.page - 1;
									}
								}
								self.open_right();	
							} else {
								self.$message.error(res.data.msg);
							}
						})
						.finally(() => {
							self.loading = false;
						});
				});
			} else {
				self.$message.error('请选择要移除的人员');
			}
		},
		// 关闭提示语
		tips_close() {
			localStorage.setItem('voluntarilyPoint', 'true');
			this.tips_show = false;
		},
		//新增加分项
		add_rules_detail() {
			this.rules_detail_form={
				rule_id: '',
				range_type: '1',
				prize_type: '1',
				min_point: '',
				remark: '',
				is_attendance: '0',
				cycle_type: '2',
				pt_id: '3'
			}
			this.dialogFormVisible = true;
			this.rules_detail_title = false;
		},
		//编辑加分项
		editRule(form) {
			let self = this;
			let data = null;
			self.rules_detail_form.max_point = self.rules_detail_form.min_point;
			if (this.rules_detail_title == false) {
				data = {
					items: [self.rules_detail_form]
				};
			} else {
				self.rules_detail_form.item_id = self.rules_detail_form.id;
				data = self.rules_detail_form;
			}
			self.$refs[form].validate(valid => {
				if (valid) {
					this.disabled = true;
					// if (this.is_attendance) {
					// 	self.rules_detail_form.is_attendance = 1;
					// } else {
					// 	self.rules_detail_form.is_attendance = 0;
					// }
					var url=this.rules_detail_title ? 'api/integral/rule/items/edit' : '/api/integral/rule/items';
					self.$axios('post',url,data).then(res => {
							// setTimeout(() => {
							// 	this.is_attendance = false;
							// }, 300);
							if (res.data.code == 1) {
								self.$message.success(res.data.msg);
								self.rules_detail_show = false;
								if (this.rules_detail_title) {//当为编辑时
									 if(self.rules_detail_form.rule_id!=self.right_rules_detail.rule_id){//当编辑规则修改了上级时
										self.get_role_lists(true);
									 }else{//正常编辑
										 self.get_role_lists();
										 self.right_rules_detail.remark=data.remark;
										 self.right_rules_detail.min_point=data.min_point;
									 }	 
								}else{//当为添加时
									self.add_employee_id = res.data.data.item_id;//规则ID
									self.add_rulse_id = self.rules_detail_form.rule_id;//分类ID
									self.get_role_lists(true,true);
									setTimeout(() => {
										self.add_employee_show = true;
									}, 600);
								}
							} else {
								self.$message.error(res.data.msg);
							}
						}).finally(() => {
							this.dialogFormVisible = false;
							self.disabled = false;
						});
				} else {
					return false;
				}
			});
		},
		//点击取消
		rules_detail_close(form) {
			this.dialogFormVisible = false;
			this.rules_detail_show = false;
			this.$refs[form].resetFields();
		},
		//获取右边表格数据
		open_right(data,updata) {
			let self = this;
			self.table_loading = true;
			this.isShowAdd=false;
			if (data&&!updata) {
				self.add_employee_id = data.id;
				self.add_rulse_id = data.rule_id;
				self.right_rules_detail = data;	
				
			}else if(updata){
				self.right_rules_detail = data;	
			}else{
				self.add_employee_id = self.right_rules_detail.id;
				self.add_rulse_id = self.right_rules_detail.rule_id;
			}
			var params = {
					item_id: self.add_employee_id || '',
					employee_id: self.employee_id || '',
					page: self.page,
					page_size: Number(this.pagesize)
			};
			self.$axios('get','/api/integral/auto/list', params).then(res => {
					if (res.data.code == 1) {
						self.table_list = res.data.data.list || [];
						self.total = res.data.data.total;
					} else {
						self.$message.error(res.data.msg);
					}
			}).finally(() => {
				self.table_loading = false;
			});
		},

		//  编辑规则
		edit_rules() {
			this.rules_detail_title = true;
			this.dialogFormVisible = true;
			this.rules_detail_form = JSON.parse(JSON.stringify(this.right_rules_detail));
			// this.is_attendance = this.rules_detail_form.is_attendance == '0' ? false : true;
		},
		// 删除规则
		del_rules_detail(item) {
			this.$confirm('此操作将永久删除该加分项, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.disabled = true;
				this.$axios('post','/api/integral/rule/items/destroy',{item_id: item.id}).then(res => {
						if (res.data.code == 1) {
							this.$message.success('删除成功');
							this.rules_detail_show = false;
							this.get_role_lists(true);
						} else {
							this.$message.error(res.data.msg);
							this.get_role_lists();
						}
					}).finally(() => {
							this.dialogFormVisible = false;
							this.disabled = false;
					});
			});
		},

		//新增加分组展示不同渲染
		add_grouping() {
			this.numberValidateForm={
				name:''
			}
			this.dialogVisible = true;
			this.grouping_type = false;
		},
		// 新增加分组
		submitForm(formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
					let data = this.grouping_type
						? {
								rule_id: this.numberValidateForm.id,
								pid: '0',
								name: this.numberValidateForm.name
						  }
						: {
								cycle_type: '2',
								pid: '0',
								name: this.numberValidateForm.name
						  };
					this.disabled = true;
					var url=this.grouping_type ? '/api/integral/rule/edit' : '/api/integral/rule';
					this.$axios('post',url,data).then(res => {
							if (res.data.code == '1') {
								this.get_role_lists();
								this.$message.success(this.grouping_type ? '修改积分规则' : res.data.msg);
							}
						}).finally(() => {
							this.dialogVisible = false;
							this.disabled = false;
						});
				} else {
					console.log('error submit!!');
					return false;
				}
			});
		},
		//修改分组
		edit_grouping(item) {
			this.dialogVisible = true;
			this.numberValidateForm = JSON.parse(JSON.stringify(item));
			this.grouping_type = true;
		},
		//删除分组
		del_grouping(item) {
			this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.disabled = true;
				this.$axios('post','/api/integral/rule/destroy',{rule_id: item.id}).then(res => {
						this.dialogVisible = false;
						this.disabled = false;
						if (res.data.code == 1) {
							this.get_role_lists();
							this.$message.success('删除成功');
						}
					}).catch(err => {
						this.dialogVisible = false;
						this.disabled = false;
					});
				}).catch(() => {
					setTimeout(() => {
						this.dialogVisible = false;
					}, 300);
				});
		},
		// 获取初始化数据
		get_role_lists(is,noUpdata) {
			this.table_loading = true;
			this.rule_trees_load = true;
			this.$axios('get','/api/integral/rule/trees', {cycle_type: '2'}).then(res => {
					// this.is_attendance = this.rules_detail_form.is_attendance == '0' ? false : true;
					var	rule_list = res.data.data.rule_tree||[];
					var	item_list = res.data.data.item_list||[];
					var itemListAll=[];
					for (let i in item_list) {
					  for (let k in item_list[i]) {
						itemListAll.push(item_list[i][k])
					  }
					}
					rule_list.map(item=>{
						item.child=itemListAll.filter((item2)=>{return item2.rule_id==item.id});
					})
					this.rule_list=rule_list;
					this.item_list=itemListAll;
					if(is){
						this.default_active="";
						if(rule_list[0].child[0]){
							this.right_rules_detail={};
							this.table_list=[];
							this.page=1;
							this.open_right(rule_list[0].child[0],noUpdata);
							setTimeout(()=>{
								this.default_active = '0-0'
							},500)
						}else{
							this.right_rules_detail={};
							this.isShowAdd=true;
						}
					}
			}).finally(err=>{
				setTimeout(()=>{
					this.rule_trees_load = false;
					this.table_loading = false;
				},700)
			});
		}
	}
};
</script>

<style scoped="scoped" lang="scss">
.rule_name {
	border-right: 0;
	margin-top: 16px;
	li {
		border-bottom: 1px #f8f8f8 solid;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		::v-deep .el-submenu__title {
			padding: 0 10px !important;
			i.el-submenu__icon-arrow.el-icon-arrow-down {
				color: #909399 !important;
			}
		}
		// li:hover .el-submenu__title {
		// 	background: #e7f6ff;
		// }
		// ul {
		// 	li.is-active {
		// 		background-color: #e7f6ff !important;
		// 	}
		// }
	}
	// ::v-deep .is-opened .el-submenu__title .title_top {
	// 	color: #409eff !important;
	// }
	// ::v-deep .is-opened .el-menu .el-menu-item span {
	// 	color: #333;
	// }
	// ::v-deep .is-opened .el-menu .is-active span {
	// 	color: #409eff;
	// }
}
::v-deep .el-submenu__title {
    height: 47px !important;
    line-height: 47px !important;
}
.rule_list {
	position: relative;
	display: table-cell;
}

.rule_list:after {
	content: ' ';
	position: absolute;
	top: 0;
	left: 0;
	bottom: 0;
	width: 1px;
	background: #ebeef5;
}
.terr-right {
	min-height: calc(100vh - 224px);
	.name {
		height: 100%;
		font-size: 18px;
		margin-right: 20px;
	}
	.btns button {
		margin-top: 20px;
		margin-right: 5px;
	}
}
.terr-left button {
	margin: 0 auto;
	display: block;
	margin-bottom: 10px;
}
</style>
