<template>
	<div class="all-box">
		
		<!-- 头部提示 -->
		<el-alert class="diy-tip" title="如何使用积分规则?" type="success" @close="tips_close" v-if="tips_show" description show-icon>
			<p>1.先【添加规则分类】，再【添加规则】</p>
			<p>2.拖拽积分‘分类’与‘规则’节点即可排序</p>
		</el-alert>
		
		<div class="all">
			<div class="flex-box" v-loading="rule_loading">
				<div class="terr-left">
					<el-button size="medium" @click="add_class"  type="primary">+ 添加规则分类</el-button>
					<div style="background-color: #ecf5ff;padding: 10px;margin-bottom: 10px;font-size: 13px;" class="fontColorC"><i class="el-icon-warning blue"></i>  拖拽下方分类即可排序</div>
					<div class="rule_class_box" v-loading="leftLoading">
<!-- 						<el-tree
						  :data="rule_tree"
						  node-key="id"
						  :props="defaultProps"
						  @node-drop="handleDrop"
						  draggable
						  :allow-drop="allowDrop"
						  @node-click="handleNodeClick($event)"
						  >
						</el-tree> -->
						
						<Rule :data="rule_tree" :paddingl="false" :sum="1" :selectId="selectId" @ruleDrag="ruleDrag" @ruleActive="handleNodeClick"></Rule>
					</div>
				</div>
				<div class="terr-right border-right flex-1">
					<div class="flex-box flex-v-ce" style="margin-bottom: 12px;">
						<div class="name">{{ selectItem.name }}  <span style="font-size: 13px;cursor: pointer;" @click="copy()" v-if="selectItem.id">（分类id：<span>{{selectItem.id}}</span>）</span></div>
						<el-button size="medium" plain v-if="selectItem.id" @click="edit_class">编辑</el-button>
					</div>
					
					<div class="flex-box-ce flex-d-wrap fontColorB" v-if="selectItem.dept_info.length>0">
						可见范围：<span v-for="(item,index) in selectItem.dept_info" :key="index">{{item.name}} 、</span>
					</div>
					
					<div class="flex-box ruleSearch" style="padding-top: 8px;">
						<div class="flex-box btns flex-v-ce">
							<el-button size="small" @click="del_item" type="danger" plain>批量删除</el-button>
							<el-button size="small" @click="add_rule" type="primary">添加规则</el-button>
							<el-button size="small" type="success" @click="toleadShw = true" plain>导入规则</el-button>
							<el-button size="small" type="success" @click="derivedRule" plain>导出规则</el-button>
						</div>
						<el-input placeholder="搜索规则内容" style="width: 250px;margin-left: 10px;" maxlength="20" v-model="keyword" clearable/>
					</div>
					<div  style="margin-top: 20px;">
						<div class="table-header flex-box-ce">
							<div style="width: 55px;padding: 0 10px;box-sizing: border-box;">
								<el-checkbox v-model="checked_all" @change="checkedAll"></el-checkbox>
							</div>
							<div class="flex-1" style="text-align: left;">内容</div>
							<div class="flex-1" style="text-align: center;">分值</div>
							<div class="flex-1" style="text-align: center;">操作</div>
						</div>
						<div class="table-content" v-loading="rightLoading">
							<transition-group name="drag" tag="div" v-if="item_list.length>0">
								<div 
								 v-for="(item,index) in item_list" :key="item.id" 
								 class="flex-box-ce"
								 :class="{'border_bottom': (border_bottom==item.id&&directionIndex==1),'border_top': (border_bottom==item.id&&directionIndex==2)}"
								 draggable 
								 @dragstart.stop="dragstart($event,item,index)" 
								 @dragenter.stop="dragenter($event,item,index)"  
								 @dragover.stop="dragover($event, item,index)"  
								 @drop.stop="drop($event,item,index)"
								 @dragend.stop="dragend($event,item,index)">
									<div style="width: 55px;padding: 0 10px;box-sizing: border-box;">
										<el-checkbox v-model="item.checked" @change="handleSelectionChange"></el-checkbox>
									</div>
									<div class="flex-1" style="text-align: left;" @click="editDetails(item)">{{item.remark}}</div>
									<div class="flex-1" style="text-align: center;" @click="editDetails(item)">
										<div v-if="item.range_type == 1">
											<span :class="item.min_point > 0 ? 'red' : 'green'">{{ item.min_point }} {{ item.pt_Obj.name }}</span>
										</div>
										<div v-if="item.range_type == 2">
											<span :class="item.min_point > 0 ? 'red' : 'green'">{{ item.min_point }}</span>
											至
											<span :class="item.max_point > 0 ? 'red' : 'green'">{{ item.max_point }} {{ item.pt_Obj.name }}</span>
										</div>
									</div>
									<div class="flex-1" style="text-align: center;" @click="editDetails(item)">
										<!-- <span>{{item.sort}}</span> -->
										<span @click.stop="ruleQRcode(item)" class="lookQrcode">查看二维码</span>
										<span class="blue" style="padding-left: 10px;cursor: pointer;">编辑</span>
									</div>
								</div>
							</transition-group>	
							<noData v-if="item_list.length==0"></noData>
							<center style="padding: 20px 0;">
								<el-pagination
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									:current-page="page"
									layout="total, prev, pager, next"
									:page-size="page_size"
									:total="total"
								></el-pagination>
							</center>
						</div>
					</div>
							
				</div>
			</div>
		</div>
		
		<el-dialog @close="closeCode" :visible.sync="innerVisible" width="444px" append-to-body>
			<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 class="qrcodesave" ><span @click.stop="downloadE">下载保存此二维码</span></div>
		</el-dialog>

		<!-- 编辑添加分类 -->
		<el-dialog
			:title="class_type == 'add' ? '添加规则分类' : '编辑规则分类'"
			:visible.sync="class_show"
			@close="add_dept_close('dept_formdata')"
			:close-on-click-modal="false"
			width="600px"
		>
			<el-form :model="dept_formdata" ref="dept_formdata" :rules="dept_formdata_rules" label-width="80px">
				<el-form-item label="规则分类" prop="name"><el-input style="width: 400px;" placeholder="分类名称" v-model="dept_formdata.name" maxlength="10" show-word-limit></el-input></el-form-item>
				<el-form-item label="上级分类">
					<el-cascader
						style="width: 400px;"
						ref="pid"
						v-model="dept_formdata.pid"
						:options="rule_tree"
						:props="{ checkStrictly: true, label: 'name', value: 'id', children: 'child' }"
						clearable
						filterable
					></el-cascader>
				</el-form-item>
				<el-form-item label="可见范围" prop="dept_ids">
					<el-cascader
						size="medium"
						style="width: 400px;"
						v-model="dept_name"
						@change="handleChange"
						:options="dept_tree"
						collapse-tags
						:props="{ checkStrictly: true, value: 'id', label: 'name', multiple: true, children: '_child' }"
						ref="dept"
						clearable
						placeholder="全公司"
					></el-cascader>
					<div style="color:#b5b7bb;padding-left:10px;">不选时，默认所有人可见</div>
				</el-form-item>
				<div class="flex-box">
					<el-button type="danger" @click="del_dept" v-show="class_type == 'edit'">删除分类</el-button>
					<div class="flex-1"></div>
					<el-button @click="add_dept_close('dept_formdata')">取消</el-button>
					<el-button type="primary" @click="submit_add_dept('dept_formdata')" :loading="dept_loading" :disabled="dept_loading">确定</el-button>
				</div>
			</el-form>
		</el-dialog>
		
		<!-- 添加编辑规则 -->
		<el-dialog :title="rule_type == 'add' ? '添加规则' : '编辑规则'" :visible.sync="rule_show" :close-on-click-modal="false" width="600px">
			<el-form :model="rules_detail_form" ref="rules_detail_form" :rules="rules" label-width="80px">
				<el-form-item label="规则内容" prop="remark">
					<el-input v-model="rules_detail_form.remark" placeholder="请输入规则内容" type="textarea" :rows="5" maxlength="300" show-word-limit></el-input>
				</el-form-item>
				<el-form-item label="所属分类" prop="rule_id">
					<div style="position: relative;">
						<div style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; z-index: 9;"	@click="not_data"	v-show="rule_tree !== null && rule_tree.length == 0"></div>
						<el-cascader
							ref="dept2"
							placeholder="请选择分类"
							v-model="rules_detail_form.rule_id"
							:options="rule_tree"
							:props="{ checkStrictly: true, label: 'name', value: 'id', children: 'child' }"
							clearable
							filterable
						></el-cascader>
					</div>
				</el-form-item>
				<el-form-item label="规则类型" prop="pt_id">
					<el-radio v-model="rules_detail_form.pt_id" :label="item.id" v-for="(item, index) in point_types" :key="index" v-show="item.name !== '绩效分'">
						{{ item.name }}
					</el-radio>
				</el-form-item>
				<el-form-item label="规则积分" prop="range_type">
					<el-radio-group v-model="rules_detail_form.range_type">
						<el-radio :label="item.value" v-for="(item, index) in range_type_arr" :key="index">{{ item.name }}</el-radio>
					</el-radio-group>
				</el-form-item>
				<div class="flex-box flex-v-ce">
					<el-form-item class="select_width">
						<el-input placeholder="请输入分值" v-model.number="rules_detail_form.min_point" type="age">
							<el-select v-model="integral_select_name1" slot="prepend" placeholder="请选择类型">
								<el-option v-for="(item, index) in integral_select" :key="index" :label="item.name" :value="item.value"></el-option>
							</el-select>
						</el-input>
					</el-form-item>

					<div v-if="rules_detail_form.range_type == 2" style="position: relative;bottom: 10px;padding: 0 10px;">至</div>
					<el-form-item v-if="rules_detail_form.range_type == 2" class="form-right select_width">
						<el-input placeholder="请输入分值" v-model.number="rules_detail_form.max_point" type="age">
							<el-select v-model="integral_select_name2" slot="prepend" placeholder="请选择类型">
								<el-option v-for="(item, index) in integral_select" :key="index" :label="item.name" :value="item.value"></el-option>
							</el-select>
						</el-input>
					</el-form-item>
				</div>

				<div class="flex-box flex-v-ce">
					<el-button type="danger" @click="del_rule" :loading="delRule_loading" :disabled="delRule_loading" v-show="rule_type == 'edit'">删除规则</el-button>
					<div class="flex-1"></div>
					<el-button @click="rule_close('rules_detail_form')">取消</el-button>
					<el-button type="primary" v-show="rule_type == 'add'" :loading="rule_loading2" :disabled="rule_loading2" @click="add_submit_rule('rules_detail_form')">
						确定
					</el-button>
					<el-button type="primary" v-show="rule_type == 'edit'" :loading="rule_loading2" :disabled="rule_loading2" @click="edit_submit_rule('rules_detail_form')">
						确定
					</el-button>
				</div>
				
			</el-form>
		</el-dialog>

		<!-- 导入规则 -->
		<toLead :visible.sync="toleadShw" :nowIndex.sync="nowIndex" :tolead="toleadResult" @confirm="tealConfirm" :export_type="'rule_items'" :dstyle="'height:180px;padding: 40px 80px;'">
			<template slot="1">
				<el-row v-if="nowIndex == 1">
					<el-col :span="12">
						<div class="text-center">
							<p>1、下载规则模版，填写好规则</p>
							<p><img src="@/assets/image/rules_mould.png" alt="" /></p>
							<p>规则表</p>
							<span>
								<a target="_blank" :href="downloadUrl"><el-button type="primary">下载模板</el-button></a>
							</span>
						</div>
					</el-col>
					<el-col :span="12">
						<div class="text-center">
							<p>2、上传填好的规则表</p>
							<p><img src="@/assets/image/rules_mould1.png" alt="" /></p>
							<p>仅支持xls、xlsx格式文件</p>
							<el-upload
								class="upload-demo"
								:headers="ATOKEN"
								ref="upload"
								:limit="1"
								:action="action"
								:on-remove="handleRemove"
								:on-success="handleSuccess"
								:before-upload="beforeFilesUpload"
								:file-list="fileList"
								:on-progress="handleOnthecross"
							>
								<el-button slot="trigger" type="primary">选取文件</el-button>
							</el-upload>
						</div>
					</el-col>
				</el-row>
			</template>
		</toLead>
	
	</div>
</template>

<script>

import QRCode from 'qrcodejs2';
import toLead from '@/components/toLead';
import Rule from '@/components/Rule';
import {_debounce} from '@/api/auth';
export default {
	data() {
		return {
			keyword:'',//搜索关键字
			ruleDetails: {},
			innerVisible: false,
			bodyLoad: false,
			action: process.env.VUE_APP_BASE_API + 'api/rule/import',
			downloadUrl: process.env.VUE_APP_BASE_API + 'api/download/rule_item',
			ATOKEN: { 'A-TOKEN': this.$getToken(), Accept: 'application/vnd.test.v2+json' },
			tips_show: true,
			rule_loading: false,
			rule_tree: [],
			item_list: [],
			all_item_list: [],
			defaultProps: {
				id: 'id',
				children: 'child',
				label: 'name'
			},
			selectItem: { name: '积分规则',dept_info:[] }, //选择的分类
			//添加分类
			class_show: false,
			delRule_loading: false,
			dept_formdata_rules: {
				name: [
					{
						required: true,
						message: '请输入规则分类',
						trigger: 'blur'
					},
					{
						min: 2,
						max: 20,
						message: '长度在 2 到 20 个字符',
						trigger: 'blur'
					}
				]
			},
			dept_formdata: {
				name: '',
				pid: '0',
				cycle_type: '1',
				dept_ids:[],
			},
			class_type: 'add',
			dept_loading: false,

			// 规则相关
			del_item_id: [], //选择规则ID集合
			rule_loading2: false,
			rule_type: 'add',
			rule_show: false,
			rules_detail_form: {
				rule_id: '',
				range_type: '1',
				prize_type: '0',
				min_point: '',
				max_point: '',
				min_point2: '',
				max_point2: '',
				remark: '',
				is_attendance: '0',
				cycle_type: '1',
				pt_id: 0
			},
			rules: {
				remark: [
					{
						required: true,
						message: '请输入规则名称',
						trigger: 'blur'
					}
				],
				rule_id: [
					{
						required: true,
						message: '请选择分类',
						trigger: 'change'
					}
				]
			},
			integral_select_name1: '1',
			integral_select_name2: '1',
			point_types: [],
			range_type_arr: [
				{
					name: '固定分值',
					value: '1'
				},
				{
					name: '范围分值',
					value: '2'
				}
			],
			integral_select: [
				{
					name: '奖分',
					value: '1'
				},
				{
					name: '扣分',
					value: '2'
				}
			],
			//导入规则
			import_rules_show: false,
			save_loading: false,
			import_btn_show: false,
			fileList: [],
			file: null,
			// item_lists:[],
			//导入相关
			toleadShw: false,
			nowIndex: 1,
			toleadResult: {},
			
			dept_tree:[],
			dept_name:[],
			employee_selected: { dept: [], employee: [] },
			oneruleId: [],
			echoGather: [],
			
			selectId:0,
			leftLoading:false,
			rightLoading:false,
			
			checked_all:false,//全选
			dragIndex:0,
			border_bottom:0,
			isTd:false,//是否移动位置
			
			directionIndex:0,
			page:1,
			page_size:100,
			total:0,
		};
	},
	components: {toLead,Rule},
	watch: {
		toleadShw(val){
			if(val) this.nowIndex = 1
		},
		'dept_formdata.pid'(val, old_val) {
			this.$nextTick(() => {
				this.$refs.pid.dropDownVisible = false;
			});
		},
		'rules_detail_form.rule_id'(val, old_val) {
			this.$nextTick(() => {
				this.$refs.dept2.dropDownVisible = false;
			});
		},
		keyword:_debounce(function(val){
			this.page=1;
			this.getRuleList(this.selectId)
		}),
	},
	created() {
		this.point_types = this.$getTyps().reverse();
	},
	mounted() {
		this.$nextTick(function() {
			if (this.$getCache('rule')) {
				this.tips_show = false;
			} else {
				this.tips_show = true;
			}
		});
		this.getData();
		this.getRuleList();
		this.getDepartment();
	},
	methods: {
		
		getArrIndex(arr,id,data,func){
			if(arr&&arr.length>0){
				arr.some((e,index)=>{
					if(e.id==id){
						data={
						  id:id,
						  prev_id:arr[index-1]? arr[index-1].id:0,
						  sibling_id:arr[index+1]? arr[index+1].id:0,
						}
						func(data)
						return true
					}else{
						this.getArrIndex(e.child,id,data,func);
					}
				})
			}
		},
		
		handleDrop(draggingNode, dropNode, dropType, ev) {
			let oneId,twoId;
		    var data={}
			this.getArrIndex(this.rule_tree,draggingNode.data.id,data,(val)=>{
				this.ruleDrag(val);
			});
		},
		//拖拽时判定目标节点能否被放置
		allowDrop(draggingNode, dropNode, type) {
			if(type=='inner'){
				return false;
			}
			if(draggingNode.data.pid==dropNode.data.pid){
				return true;
			}else{
				return false
			}
		},
		
		checkedAll(val){
			let item_list=JSON.parse(JSON.stringify(this.item_list));
			item_list.forEach(e=>{
				e.checked=val
			})
			this.item_list=item_list
			this.$nextTick(()=>{
				this.handleSelectionChange();
			})
		},
		
		dragstart(e,item,index) {
		  this.dragIndex = index;
		  this.isTd=true;
		  setTimeout(() => {
		  	e.target.classList.add('moveing')
		  }, 0)
		},
		
		//dragenter,进入目标元素触发，相当于mouseover
		dragenter(e,item,index) {
		  e.preventDefault();
		  if(this.dragIndex!=index){
			if(index>this.dragIndex){
			   this.directionIndex=1;
			}else{
			   this.directionIndex=2;
			}
			this.border_bottom=item.id
		  }else{
			this.border_bottom=0;
		  }
		},
		//dragover,进入目标、离开目标之间，连续触发
		dragover(e,item,index) {
		  e.preventDefault();
		},
		// 鼠标松开 防抖触发排序
		drop(e,item,index) {
			// return false
			this.border_bottom=0;
			if (this.dragIndex !== index&&this.isTd) {
			  this.isTd=false;
			  let moving = this.item_list[this.dragIndex]; //获取之前记录的元素
			  this.item_list.splice(this.dragIndex, 1); //删除列表的记录元素
			  this.item_list.splice(index,0, moving);//插入元素
			  this.dragIndex = index;
			  
			  // oneId前一个ID twoId后一个ID
			  let oneId=this.item_list[index-1]? this.item_list[index-1].id:0;
			  let twoId=this.item_list[index+1]? this.item_list[index+1].id:0;
			  let data={
				  id:this.item_list[index].id,
				  prev_id:oneId,
				  sibling_id:twoId,
			  }
			  this.rightLoading = true;
			  this.$axios('post','api/integral/rule/items/drag',data).then(res => {}).finally(() => {
			  	this.rightLoading = false;
			  });
			}
		},
		//用户完成拖动后触发
		dragend(e,item,index){
			this.border_bottom=0;
			e.target.classList.remove('moveing')
		},
		
		
		ruleDrag(data){
			this.leftLoading = true;
			this.$axios('post','api/integral/rule/drag',data).then(res => {
				
			}).finally(() => {
				this.leftLoading = false;
			});
		},
		copy (index) {
			  //创建input标签
			  var input = document.createElement('input')
			  //将input的值设置为需要复制的内容
			  input.value =this.selectItem.id
			  //添加input标签
			  document.body.appendChild(input)
			  //选中input标签
			  input.select()
			  //执行复制
			  document.execCommand('copy')
			  //成功提示信息
			  this.$message.success('分类ID复制成功')
			  //移除input标签
			  document.body.removeChild(input)
		},
		//编辑分组
		edit_class() {
			this.class_show = true;
			this.class_type = 'edit';
			this.echoGather=[];
			this.dept_formdata = {
				child: this.selectItem.child,
				id: this.selectItem.id,
				name: this.selectItem.name,
				pid: this.selectItem.pid,
				dept_ids:this.selectItem.dept_ids,
			};
			console.log(this.selectItem)
			for (let i in this.selectItem.dept_ids) {
				this.getTreeDatas(this.dept_tree, this.selectItem.dept_ids[i]);
			}
			this.dept_name = this.echoGather;
		},
		//添加分组
		submit_add_dept(form) {
			this.dept_loading = true;
			this.$refs[form].validate(valid => {
				if (valid) {
					let pidData=JSON.parse(JSON.stringify(this.dept_formdata.pid))//备份选择的规则，因为提交时间PID会被重新赋值
					if (this.class_type == 'edit') {
						delete this.dept_formdata.child;
						this.dept_formdata.rule_id = this.dept_formdata.id;
						if (typeof this.dept_formdata.pid == 'number') {
							
						} else {
							if (this.dept_formdata.pid.length > 0) {
								this.dept_formdata.pid = this.dept_formdata.pid[this.dept_formdata.pid.length - 1];
							} else {
								this.dept_formdata.pid = 0;
							}
						}
						let dept_formdata=JSON.parse(JSON.stringify(this.dept_formdata))
						dept_formdata.dept_ids=JSON.stringify(dept_formdata.dept_ids)
						this.$axios('post', '/api/integral/rule/edit',dept_formdata)
							.then(res => {
								if (res.data.code == 1) {
									this.selectItem.name = this.dept_formdata.name;
									this.$message.success('修改积分分类成功');
									this.getData(true);
									this.add_dept_close('dept_formdata');
								}
							})
							.finally(() => {
								this.dept_formdata.pid=pidData
								this.dept_loading = false;
							});
					} else {
						if (this.dept_formdata.pid !== null && this.dept_formdata.pid.length == 0) {
							this.dept_formdata.pid = 0;
						} else {
							this.dept_formdata.pid = this.dept_formdata.pid[this.dept_formdata.pid.length - 1];
						}
						let dept_formdata=JSON.parse(JSON.stringify(this.dept_formdata))
						dept_formdata.dept_ids=JSON.stringify(dept_formdata.dept_ids)
						this.$axios('post', '/api/integral/rule',dept_formdata).then(res => {
							if (res.data.code == 1) {
								this.$message.success('添加积分分类成功');
								this.getData();
								this.add_dept_close('dept_formdata');
							}
						}).finally(() => {
							this.dept_formdata.pid=pidData
							this.dept_loading = false;
						});
					}
				} else {
					this.dept_loading = false;
				}
			});
		},
		getTreeDatas(data, item) {
			for (let i in data) {
				if (data[i].id == item) {
					if (data[i].parentid == 1) {
						this.oneruleId.unshift(data[i].id);
						this.echoGather.push(this.oneruleId);
						this.oneruleId = [];
						break;
					} else {
						this.oneruleId.unshift(data[i].id);
						this.getTreeDatas(this.dept_tree, data[i].parentid);
					}
				} else {
					if (data[i]._child) {
						this.getTreeDatas(data[i]._child, item);
					}
				}
			}
			return;
		},
		handleChange(val) {
			let data = [];
			for (let i in val) {
				data.push(val[i][val[i].length - 1]);
			}
			this.dept_formdata.dept_ids = data;
		},
		handleOnthecross(event, file, fileList){
			this.nowIndex = 2
		},
		//导出规则按钮
		derivedRule(){
		  let userData=this.$getUserData();
		  window.open(process.env.VUE_APP_BASE_API+'/api/download/rule_item/item?employee_id='+userData.id)
		},
		//获取部门
		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++) {
				if (data[i]._child.length < 1) {
					// children若为空数组，则将children设为undefined
					data[i]._child = undefined;
				} else {
					// children若不为空数组，则继续 递归调用 本方法
					this.getTreeData(data[i]._child);
				}
			}
			return data;
		},
		downloadE() {
			let rule_remark = '';
			if (this.ruleDetails.remark.length > 10) {
				rule_remark = this.ruleDetails.remark;
				rule_remark = rule_remark.slice(0, 10);
			} else {
				rule_remark = this.ruleDetails.remark;
			}
			var canvasData = this.$refs.qrcode.getElementsByTagName('canvas')
			var a = document.createElement("a");
			var event = new MouseEvent("click"); // 创建一个单击事件
			a.href = canvasData[0].toDataURL("image/png");
			a.download = rule_remark;
			a.dispatchEvent(event); // 触发a的单击事件
		},
		payOrder (row) {// 展示二维码
			let url = 'dingtalk://dingtalkclient/action/open_micro_app'
			let appid = '?appId='+this.$appId
			let corpId = '&corpId='+this.$getCache('corpId')
			// let corpId = '&corpId=ding011f57ab048cf202ffe93478753d9884'
			let page = '&page='+encodeURIComponent(`pages/workbench/apply/apply?id=${encodeURIComponent(row)}`)//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，最高，所以二维码看起来很密
			})
		},
		ruleQRcode(row) {
			this.ruleDetails = row;
			// 生成二维码
			this.innerVisible = true;
			// 使用$nextTick确保数据渲染
			this.$nextTick(() => {
				this.payOrder(row.id);
			});
		},
		// 关闭弹框,清除已经生成的二维码
		closeCode() {
			setTimeout(() => {
				this.$refs.qrcode.innerHTML = '';
			}, 150);
		},

		// 导入相关
		close_import() {
			this.import_rules_show = false;
			this.import_btn_show = false;
			this.$refs.upload.clearFiles();
		},

		tealConfirm(){
			this.page=1;
			this.getRuleList(this.selectId);
		},
		
		handleSuccess(response) {
			if(response.code == 1){
				response.data.id = 1
			}else{
				response.data.id = 0
				response.data.name = response.msg
			}
			this.toleadResult = response.data
			this.nowIndex = 3
			return

			if (response.code == 1) {
				if (response.data.length > 0) {
					var htmls = response.data;
					var str = "<div class='red'></div>";
					htmls.forEach(item => {
						str += `<div>${item.errors}</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.getData();
					this.close_import();
				}
			}else{
				this.$message.error({ message: response.msg });
			}
		},
		
		handleRemove(file, fileList) {
			if (fileList !== null && fileList.length != 0) {
				this.import_btn_show = true;
			} else {
				this.import_btn_show = false;
			}
		},
		
		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.toleadResult.id = 0
				this.toleadResult.name = '文件格式上传错误,仅支持上传xlsx,xls）'
				this.nowIndex = 3
				return false;
			}
		},

		//添加规则
		add_submit_rule(form) {
			let self = this;
			self.$refs[form].validate(valid => {
				if (valid) {
					if (self.integral_select_name1 != '1' && self.rules_detail_form.min_point >= 0) {
						self.rules_detail_form.min_point = '-' + self.rules_detail_form.min_point;
					}
					if (self.integral_select_name2 != '1' && self.rules_detail_form.max_point >= 0) {
						self.rules_detail_form.max_point = '-' + self.rules_detail_form.max_point;
					}
					if (self.rules_detail_form.range_type == 1) {
						self.rules_detail_form.max_point = self.rules_detail_form.min_point;
					}
					if (self.rules_detail_form.min_point == 0 || !self.rules_detail_form.min_point || self.rules_detail_form.max_point == 0 || !self.rules_detail_form.max_point) {
						this.$message.error('积分不能为空或为0');
						return;
					}
					if (Array.isArray(self.rules_detail_form.rule_id)) {
						self.rules_detail_form.rule_id = self.rules_detail_form.rule_id[self.rules_detail_form.rule_id.length - 1];
					}
					if (parseFloat(self.rules_detail_form.min_point) > parseFloat(self.rules_detail_form.max_point)) {
						this.$confirm('填写的规则积分是' +self.rules_detail_form.min_point +' ～ ' +self.rules_detail_form.max_point +'，应该是 ' +self.rules_detail_form.max_point +' ～ ' +self.rules_detail_form.min_point +'吧？','提示',
							{
								confirmButtonText: '确定',
								cancelButtonText: '取消',
								type: 'warning'
							}
						).then(() => {
							this.rule_loading2 = true;
							let min_point = this.rules_detail_form.min_point;
							this.rules_detail_form.min_point = this.rules_detail_form.max_point;
							this.rules_detail_form.max_point = min_point;
							if (this.rules_detail_form.min_point == 0 && this.rules_detail_form.range_type == 1) {
								this.$message.error('积分不能为零');
								this.rule_loading2 = false;
								return false;
							}
							let data = {
								items: [this.rules_detail_form]
							};
							this.$axios('post', '/api/integral/rule/items', data).then(res => {
								this.$message.success(res.data.msg);
								this.getRuleList(this.selectId)
								this.rule_close(form);
							}).finally(() => {
								this.rule_loading2 = false;
							});
						});
					} else {
						this.rule_loading2 = true;
						self.rules_detail_form.item_id = self.rules_detail_form.id;
						if (self.rules_detail_form.min_point == 0 && self.rules_detail_form.range_type == 1) {
							self.$message.error('积分不能为零');
							this.rule_loading2 = false;
							return false;
						}
						let data = {
							items: [self.rules_detail_form]
						};
						this.$axios('post', '/api/integral/rule/items', data)
							.then(res => {
									this.$message.success(res.data.msg);
									this.getRuleList(this.selectId)
									this.rule_close(form);
							})
							.finally(() => {
								this.rule_loading2 = false;
							});
					}
				} else {
					this.rule_loading2 = false;
					return false;
				}
			});
		},
		//编辑规则
		edit_submit_rule(form) {
			let self = this;
			self.$refs[form].validate(valid => {
				if (valid) {
					if (!self.rules_detail_form.min_point) {
						this.$message.error('积分不能为空或为0');
						return;
					}
					if (self.integral_select_name1 != '1' && self.rules_detail_form.min_point >= 0) {
						self.rules_detail_form.min_point = '-' + self.rules_detail_form.min_point;
					}
					if (self.integral_select_name2 != '1' && self.rules_detail_form.max_point >= 0) {
						self.rules_detail_form.max_point = '-' + self.rules_detail_form.max_point;
					}
					if (self.rules_detail_form.range_type == 1) {
						self.rules_detail_form.max_point = self.rules_detail_form.min_point;
					}
					if (Array.isArray(self.rules_detail_form.rule_id)) {
						self.rules_detail_form.rule_id = self.rules_detail_form.rule_id[self.rules_detail_form.rule_id.length - 1];
					}
					if (parseFloat(self.rules_detail_form.min_point) > parseFloat(self.rules_detail_form.max_point)) {
						this.$confirm(
							'填写的规则积分是' +
								self.rules_detail_form.min_point +
								' ～ ' +
								self.rules_detail_form.max_point +
								'，应该是 ' +
								self.rules_detail_form.max_point +
								' ～ ' +
								self.rules_detail_form.min_point +
								'吧？',
							'提示',
							{
								confirmButtonText: '确定',
								cancelButtonText: '取消',
								type: 'warning'
							}
						).then(() => {
							this.rule_loading2 = true;
							let min_point = self.rules_detail_form.min_point;
							self.rules_detail_form.min_point = self.rules_detail_form.max_point;
							self.rules_detail_form.max_point = min_point;
							let data = self.rules_detail_form;
							data.item_id = self.rules_detail_form.id;
							if(data.sort){
								delete data.sort
							}
							if (self.rules_detail_form.min_point == 0 && self.rules_detail_form.range_type == 1) {
								self.$message.error('积分不能为零');
								this.rule_loading2 = false;
								return false;
							}
							this.$axios('post', '/api/integral/rule/items/edit', data)
								.then(res => {
									if (res.data.code == 1) {
										self.$message.success(res.data.msg);
										this.getRuleList(this.selectId)
										self.rule_close(form);
									}
								})
								.finally(err => {
									this.rule_loading2 = false;
								});
						});
					} else {
						this.rule_loading2 = true;
						self.rules_detail_form.item_id = self.rules_detail_form.id;
						let data = self.rules_detail_form;
						data.item_id = self.rules_detail_form.id;
						if (self.rules_detail_form.min_point == 0 && self.rules_detail_form.range_type == 1) {
							self.$message.error('积分不能为零');
							this.rule_loading2 = false;
							return false;
						}
						if(data.sort){
							delete data.sort
						}
						this.$axios('post', '/api/integral/rule/items/edit', data)
							.then(res => {
								if (res.data.code == 1) {
									self.$message.success(res.data.msg);
									this.getRuleList(this.selectId)
									self.rule_close(form);
								}
							})
							.finally(() => {
								this.rule_loading2 = false;
							});
					}
				} else {
					this.rule_loading2 = false;
					return false;
				}
			});
		},
		
		//删除规则
		del_rule() {
			let self = this;
			let data = {
				item_ids:JSON.stringify([this.rules_detail_form.id])
			};
			this.delRule_loading = true;
        	const h = this.$createElement;
			self.$msgbox({
				title: '提示',
				message: h('div', null, [
					h('p', null, [
						h('i', { class: "el-icon-info", style: "color: #e6a23c; "}, null),
						h('span', { style: "font-size: 16px; color: black; padding-left: 5px;" }, '删除操作可能造成以下影响')
					]),
					h('ul', { style: "list-style: disc; padding: 0 0 0 21px; color: #6d6d6d; margin: 5px 0; " },[
						h('li', {style: "margin: 5px 0;"}, '与当前积分规则关联的积分审批，以此规则作为依据的审批单只能作废'),
						h('li', {style: "margin: 5px 0;"}, '与当前积分规则关联的自定义积分排名，此规则产生的积分将不再统计'),
					]),
					h('p', { style: "font-size: 15px; color: #616161; " }, '请确保无上述审批单或排名数据影响后，再操作删除'),
				]),
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				showCancelButton: true,
				customClass: 'winClass',//弹窗样式
			}).then(
				() => {
					this.$axios('post', '/api/integral/rule/items/destroy', data).then(res => {
						this.$message.success(res.data.msg);
						this.rule_show = false;
						this.getRuleList(this.selectId);
					}).finally(() => {
						this.delRule_loading = false;
					});
				},
				err => {
					this.delRule_loading = false;
				}
			);
		},
		//关闭规则弹窗
		rule_close(form) {
			this.rule_show = false;
			this.$refs[form].resetFields();
		},
		not_data() {
			this.$confirm('暂时没有积分分类,是否前往添加?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.rule_show = false;
				this.class_show = true;
			});
		},
		add_rule() {
			this.rule_show = true;
			this.rule_type = 'add';
			this.rules_detail_form = {
				rule_id: '',
				range_type: '1',
				prize_type: '0',
				min_point: '',
				max_point: '',
				min_point2: '',
				max_point2: '',
				remark: '',
				is_attendance: '0',
				cycle_type: '1',
				pt_id: 3
			};
			this.integral_select_name1 = '1';
			this.integral_select_name2 = '1';
		},
		//批量删除
		del_item() {
			if (this.del_item_id.length == 0) {
				this.$message.error('请选择积分细则');
				return false;
			}
        	const h = this.$createElement;
			this.$msgbox({
				title: '提示',
				message: h('div', null, [
					h('p', null, [
						h('i', { class: "el-icon-info", style: "color: #e6a23c; "}, null),
						h('span', { style: "font-size: 16px; color: black; padding-left: 5px;" }, '删除操作可能造成以下影响')
					]),
					h('ul', { style: "list-style: disc; padding: 0 0 0 21px; color: #6d6d6d; margin: 5px 0; " },[
						h('li', {style: "margin: 5px 0;"}, '与当前积分规则关联的积分审批，以此规则作为依据的审批单只能作废'),
						h('li', {style: "margin: 5px 0;"}, '与当前积分规则关联的自定义积分排名，此规则产生的积分将不再统计'),
					]),
					h('p', { style: "font-size: 15px; color: #616161; " }, '请确保无上述审批单或排名数据影响后，再操作删除'),
				]),
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				showCancelButton: true,
				customClass: 'winClass',//弹窗样式
			}).then(() => {
				let data = {
					item_ids: JSON.stringify(this.del_item_id)
				};
				this.$axios('post', '/api/integral/rule/items/destroy', data).then(res => {
					if (res.data.code == 1) {
						this.$message.success(res.data.msg);
						this.getRuleList(this.selectId);
					}
				});
			});
		},

		editDetails(val) {
			this.rules_detail_form = JSON.parse(JSON.stringify(val));
			if (this.rules_detail_form.min_point == this.rules_detail_form.max_point) {
				this.rules_detail_form.range_type = '1';
			} else {
				this.rules_detail_form.range_type = '2';
			}
			if (this.rules_detail_form.min_point < 0) {
				this.integral_select_name1 = '2';
				let str = this.rules_detail_form.min_point;
				this.rules_detail_form.min_point = str.toString().substring(1);
			} else {
				this.integral_select_name1 = '1';
			}
			if (this.rules_detail_form.max_point < 0) {
				this.integral_select_name2 = '2';
				let str = this.rules_detail_form.max_point;
				this.rules_detail_form.max_point = str.toString().substring(1);
			} else {
				this.integral_select_name2 = '1';
			}
			this.rule_show = true;
			this.rule_type = 'edit';
		},
		handleSelectionChange() {
			this.del_item_id = [];
			this.item_list.forEach(e=>{
				if(e.checked){
					this.del_item_id.push(e.id);
				}
			})
		},

		// 规则递归 children
		getRuleTreeData(data) {
			for (var i = 0; i < data.length; i++) {
				data[i].isShowChild=false
				if (data[i].child.length < 1) {
					// children若为空数组，则将children设为undefined
					data[i].child = undefined;
				} else {
					// children若不为空数组，则继续 递归调用 本方法
					this.getRuleTreeData(data[i].child);
				}
			}
			return data;
		},
		
		handleNodeClick(e,is) {
			if(this.leftLoading||this.selectId==e.id&&!is){
				return false
			}
			this.selectId=e.id
			this.page=1;
			if(e.id){
				this.$axios('get', '/api/integral/rule/info', { rule_id: e.id }).then(res => {
					let dept_info=res.data.data.dept_info;
					let data=res.data.data;
					let dept_ids=dept_info.map(item=>{
						return item.id
					})
					this.selectItem = {
						child: e.child,
						id: data.id,
						name: data.name,
						pid: data.pid,
						dept_info:dept_info,
						dept_ids:dept_ids
					};
					console.log(this.selectItem)
				})
				this.getRuleList(e.id)
			}else{
				this.selectItem = { name: '积分规则',dept_info:[] };
			}
		},
		getData(is) {
			this.rule_loading = true;
			this.$axios('get','/api/integral/rule/trees',{cycle_type:1}).then(res => {
				var item_list = res.data.data.item_list || [];
				var list = [];
				for (let i in item_list) {
					for (let k in item_list[i]) {
						item_list[i][k].pt_Obj = this.$getTyps(item_list[i][k].pt_id);
						list.push(item_list[i][k]);
					}
				}
				this.rule_tree = this.getRuleTreeData(res.data.data.rule_tree);
				if (is) { //需要刷新分类详情
					this.handleNodeClick(this.selectItem,true);
				}
			}).finally(() => {
				this.rule_loading = false;
			});
		},
		getRuleList(id){
			let data={
				page:this.page,
				cycle_type:1,
				include_sub:1,
				keyword:this.keyword,
				page_size:100,
			}
			if(id){
				data.rule_id=id
			}
			this.checked_all=false;
			this.rightLoading=true;
			this.item_list=[];
			this.$axios('get', '/api/integral/rule/items',data).then(res => {
				let list=res.data.data.list;
				list.forEach(item=>{	
					item.checked=false;
					item.pt_Obj = this.$getTyps(item.pt_id);
				})
				// console.log(list)
				this.item_list = list;
				this.total=res.data.data.total
			}).finally(() => {
				this.rightLoading = false;
			});
		},
		//删除分组
		del_dept() {
			this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.$axios('post', '/api/integral/rule/destroy', { rule_id: this.selectItem.id }).then(res => {
					if (res.data.code == 1) {
						this.selectItem = { name: '积分规则',dept_info:[] };
						this.selectId=0;
						this.$message.success(res.data.msg);
						this.getData();
						this.getRuleList()
						this.add_dept_close('dept_formdata');
					}
				});
			});
		},
		//关闭弹窗
		add_dept_close(form) {
			this.class_show = false;
			this.$refs[form].resetFields();
		},
		//关闭提示
		tips_close() {
			this.$setCache('rule', 'true');
			this.tips_show = false;
		},
		//添加分类
		add_class() {
			this.class_show = true;
			this.class_type = 'add';
			this.dept_name=[];
			this.dept_formdata = {
				name: '',
				pid: '0',
				cycle_type: '1',
				dept_ids:[],
			};
		},
		// 页面变更
		handleCurrentChange(val) {
			this.page = val;
			this.getRuleList(this.selectId);
		},
		handleSizeChange(val) {
			this.page = 1;
			this.page_size = val;
			this.getRuleList(this.selectId);
		},
	}	
};
</script>

<style scoped lang="scss">
.moveing {
	opacity: 0.5;
}
.border_top{
	// position: relative;
	border-top: 1px solid #017FFF !important;
}
.border_bottom{
	border-bottom: 1px solid #017FFF !important;
}	
.drag-move {
	transition: transform .3s;
}	
.table-header{
	padding: 12px 0;
	border-bottom: 1px solid #EBEEF5;
}	
.table-header .flex-1{
	color: #909399;
	font-weight: 600;
	padding:0 10px ;
}
.table-content{
	position: relative;
}
.table-content .flex-1{
	padding:12px 10px;
	line-height: 23px;
	position: relative;
	color: #606266;
}
.table-content .flex-box-ce{
	border-bottom: 1px solid #EBEEF5;
}
.table-content .flex-box-ce:nth-child(2n){
	background-color: #FAFAFA;
}
.table-content .flex-box-ce:hover{
	background-color: #F5F7FA !important;
	cursor: pointer;
}
.border {
  -webkit-appearance: none;
  background-color: #fff;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  color: #c0c4cf;
  font-size: inherit;
  height: auto;
  outline: 0;
  padding: 0 15px;
  width: 400px;
  position: relative;
  cursor: pointer;
}
.border .font-flex-word {
  color: #606266;
}	
	
	
	
$red: #f56c6c;
::v-deep .el-table__row{
	cursor: pointer;
}
.select_width .el-select {
	width: 80px;
	background-color: #fff;
	border: 1px solid #f1f1f1;
	border-left: none;
	color: #222;
	border-radius: 5px;
}
.text-center {
	text-align: center;
}
.text-center p {
	padding: 10px 0;
}
.terr-right {
	.name {
		font-size: 18px;
		margin-right: 20px;
	}
	.btns button {
		font-size: 14px;
		height: 38px;
		width: 90px;
		margin-right: 5px;
	}
}
.rule_class_box {
	::v-deep .el-tree-node__content {
		padding: 10px 0;
		// border-bottom: 1px #f8f8f8 solid;
	}
	::v-deep .el-tree-node__content:hover {
		// background: #ecf5ff;
		// border-radius: 4px;
	}
	::v-deep .is-current .el-tree-node__content .el-icon-caret-right {
		color: #409eff !important;
	}
	::v-deep .is-current .el-tree-node__content .el-tree-node__label {
		color: #409eff !important;
	}
	::v-deep .is-current .el-tree-node__children .el-icon-caret-right {
		color: #c0c4cc !important;
	}
	::v-deep .is-current .el-tree-node__children .el-tree-node__label {
		color: #606266 !important;
	}
	::v-deep .el-tree-node__label {
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
}
.form-right ::v-deep .el-form-item__content {
	margin-left: 0px !important;
}
.terr-left button {
	margin: 0 auto;
	display: block;
	margin-bottom: 10px;
}

.el-dropdown-links {
	font-size: 20px;
	cursor: pointer;
	color: #686a6d;
}
.color-red {
	color: $red;
	&:hover {
		color: #f14141;
	}
}
.qrcodesave {
	text-align: center;
	margin-top: 15px;
	font-size: 18px;
	span {
		color: #606266;
		cursor: pointer;
		transition: all 0.3s;
	}
}

.qrcodesave span:hover {
	color: #2490fd;
}
.lookQrcode {
	color: #606266;
	cursor: pointer;
	transition: all 0.3s;
}
.lookQrcode:hover {
	color: #2490fd;
}
.ruleSearch ::v-deep .el-input__inner{
	height:38px;
}
</style>
<style lang="scss">
	.winClass{
		width: 500px
	}
</style>
