<template>
	<div>
		<!-- 奖扣ab分弹窗 -->
		<el-dialog :title="title" :visible.sync="visible" top="3%" :close-on-click-modal="false" :before-close="closePopup" width="600px">
			<div>
				<el-form :model="dialogData" ref="dialogData" label-width="80px" v-loading="loading">
					<el-form-item label="录入对象" prop="members" :rules="[{ required: true, message: '请选择录入对象', trigger: 'change' }]">
						<el-row>
							<el-col :span="18">
								<el-input auto-complete="off" v-model="employeeName" placeholder="请选择录入对象"></el-input>
								<div @click="noPersonnelListTips" style=" position: absolute; top: 0; right: 0; left: 0; bottom: 0; z-index: 9;"></div>
								<slot></slot>
							</el-col>
						</el-row>
					</el-form-item>
					<div v-for="(item, index) in dialogData.items" :key="index" @click.stop="itemIndex = index">
						<div style="overflow: hidden;">
							<span style="line-height: 36px;">录入明细({{ index + 1 }})</span>
							<el-button type="text" class="fr" v-show="index > 0 || dialogData.items.length > 1" @click="delItem(index)">删除</el-button>
						</div>
						<el-form-item label="指定规则">
							<el-switch :disabled="ruleOnoff" @change="switchChange(index, item.rule_switch)" v-model="item.rule_switch"></el-switch>
						</el-form-item>
						<el-form-item
							class="test_cascader_id"
							label="选择分类"
							v-if="!item.rule_switch"
							:prop="'items.' + index + '.rule_list_value'"
							:rules="[{ required: true, message: '请选择规则分类', trigger: 'blur' }]"
						>
							<el-cascader
								v-model="item.rule_list_value"
								:ref="'ruleCascader'+index"
								:popper-class="'ruleClass'"
								filterable
								clearable
								:options="rule_list"
								@change="ruleChange"
								:props="{ children: 'child', label: 'name', value: 'id', checkStrictly: true }"
							></el-cascader>
						</el-form-item>

						<el-form-item
							label="选择规则"
							v-if="item.rule_switch"
							:prop="'items.' + index + '.rule_item_list_value'"
							:rules="[{ required: true, message: '请选择规则', trigger: 'blur' }]"
						>
							<el-cascader
								v-model="item.rule_item_list_value"
								ref="ruleItem"
								:popper-class="'itemClass'"
								filterable
								clearable
								:options="rule_item_list"
								@change="ruleItemChange"
								:show-all-levels="false"
								:props="{ children: 'child', label: 'name', value: 'id' }"
							></el-cascader>
						</el-form-item>

						<el-form-item>
							<div style="line-height: 24px;" v-show="item.rule_item_details.range_type == 1">
								{{ item.rule_item_details.min_point }}
								<span class="blue">{{ $getTypsName(ptid) }}</span>
							</div>
							<div style="line-height: 24px;" v-show="item.rule_item_details.range_type == 2">
								{{ item.rule_item_details.min_point }} ~ {{ item.rule_item_details.max_point }}
								<span class="blue">{{ $getTypsName(ptid) }}</span>
							</div>
							<div style="line-height: 24px;">{{ item.rule_item_details.name }}</div>
						</el-form-item>
						<el-form-item label="积分" :prop="'items.' + index + '.point'" :rules="[{ required: true, message: '请输入分值', trigger: 'blur' }]">
							<el-input-number v-if="item.rule_item_details.range_type == 2" :min="item.min" :max="item.max" v-model.number="item.point"></el-input-number>
							<el-input-number v-else :disabled="item.rule_item_details.range_type == 1" v-model.number="item.point"></el-input-number>
						</el-form-item>

						<el-form-item label="发生时间" :prop="'items.' + index + '.event_time'" :rules="[{ required: true, message: '请选择时间', trigger: 'blur' }]">
							<el-row>
								<el-col :span="18">
									<el-date-picker
										v-model="item.event_time"
										:picker-options="pickerBeginDateBefore"
										type="date"
										placeholder="请选择时间"
										value-format="yyyy-MM-dd"
									></el-date-picker>
								</el-col>
							</el-row>
						</el-form-item>

						<el-form-item
							label="事件内容"
							:prop="'items.' + index + '.remark'"
							:rules="[{ required: true, message: '请输入事件内容', trigger: 'blur' }, { min: 2, max: 100, message: '长度在 3 到 100 个字符', trigger: 'blur' }]"
						>
							<el-row>
								<el-col :span="18"><el-input type="textarea" rows="3" placeholder="请输入事件内容" style="width: 100%;" v-model="item.remark"></el-input></el-col>
							</el-row>
						</el-form-item>

						<el-form-item label="图片">
							<upload
								:headers="Xtoken"
								class="avatar-uploader"
								:action="'https://' + 'integralsys.oss-cn-shenzhen.aliyuncs.com'"
								:show-file-list="true"
								:file-list="item.fileList"
								:on-success="handleFilesSuccess"
								:on-preview="onFilePreView"
								:before-upload="beforeUpload"
								:on-remove="onFileRemove"
								:limit="3"
								:multiple="true"
								ref="clearPicture"
							>
								<el-button size="small" type="primary">点击上传</el-button>
								（最多选择3张）
							</upload>
						</el-form-item>
						<el-form-item label="递交审批" v-if="$getUserData().is_creator == 0">
							<el-row>
								<el-col :span="18">
									<el-input auto-complete="off" v-model="item.approvalName" placeholder="请选择审批人"></el-input>
									<div @click="item.show_approval_selector = true" style=" position: absolute; top: 0; right: 0; left: 0; bottom: 0; z-index: 9;"></div>
								</el-col>
							</el-row>
							<el-dialog title="选择人员" width="640px" :visible.sync="item.show_approval_selector" append-to-body :before-close="handleClose">
								<EmployeeSelector
									v-if="item.show_approval_selector"
									ref="superior"
									:multi="false"
									:isCreatorSelect="true"
									:user_no_select="false"
									:employee_list="superior_list"
									:selected="item.approval_selected"
									@confirm="approval_confirm"
								/>
								<span slot="footer" class="dialog-footer">
									<el-button @click="item.show_approval_selector = false">取 消</el-button>
									<el-button type="primary" @click="submitEmployee('superior')">确 定</el-button>
								</span>
							</el-dialog>
						</el-form-item>
					</div>
					<el-form-item style="margin-bottom: 0;"><div>如需录入多条，请点击“增加一条”</div></el-form-item>
					<el-form-item style="margin-bottom: 0;"><el-button type="primary" plain @click="addItem">+ 增加一条</el-button></el-form-item>
					<el-form-item style="text-align: right; margin-bottom: 0;">
						<el-button @click="closeDialog('dialogData')" :disabled="btn_loading">取 消</el-button>
						<el-button type="primary" @click="subData('dialogData')" :disabled="btn_loading" :loading="btn_loading">确 认</el-button>
					</el-form-item>
				</el-form>
			</div>
			<el-dialog title="选择人员" width="640px" :visible.sync="show_employee_selector" append-to-body :before-close="handleClose">
				<EmployeeSelector
					v-if="show_employee_selector"
					ref="members"
					:isChecKedAll="false"
					:isCreatorSelect="true"
					:user_no_select="false"
					:max="30"
					:employee_list="manage_scope"
					:selected="employee_selected"
					@confirm="move_employee_confirm"
				/>
				<span slot="footer" class="dialog-footer">
					<el-button @click="show_employee_selector = false">取 消</el-button>
					<el-button type="primary" @click="submitMembers()">确 定</el-button>
				</span>
			</el-dialog>
		</el-dialog>

		<el-dialog :title="'提交结果'" :visible.sync="error_list_show" :append-to-body="true" width="700px">
			<el-table :data="error_list">
				<el-table-column prop="target" label="员工"></el-table-column>
				<el-table-column prop="point" label="积分">
					<template slot-scope="scope">
						<span>
							{{ scope.row.point }}
							<span>{{ integralType == 2 ? 'A分' : 'B分' }}</span>
						</span>
					</template>
				</el-table-column>
				<el-table-column prop="status" label="处理状态">
					<template slot-scope="scope">
						<span :style="'color:' + (scope.row.status == 0 ? '#f70000' : '#47bf47')">{{ scope.row.msg }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="remark" label="备注信息"></el-table-column>
			</el-table>
		</el-dialog>
	
		<el-dialog title="提交结果" :visible.sync="isResult"  width="800" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
			<div v-if="!isShowError">
				<div style="text-align: center;margin-bottom: 10px;" class="red" v-if="isShowError2">{{errorMsg}}</div>
				<el-progress :text-inside="true" :stroke-width="24" :percentage="percentage"></el-progress>
				<div style="margin-top: 20px;border: 1px solid #f1f1f1;max-height: 500px;overflow-y: auto;" class="scroll-bar">
					<div class="flex-box-ce results" style="font-weight: 600;">
						<div style="border-right: 1px solid #f1f1f1;width: 50px;">序号</div>
						<div class="flex-1" style="border-right: 1px solid #f1f1f1;">奖扣对象</div>
						<div class="flex-2" style="border-right: 1px solid #f1f1f1;">事件内容</div>
						<div class="flex-1" style="border-right: 1px solid #f1f1f1;">积分</div>
						<div class="flex-2" >处理结果</div>
					</div>
					<div class="flex-box-ce results" v-for="(item, index) in results" :key="index">
						<div style="border-right: 1px solid #f1f1f1;width: 50px;">{{results.length-index}}</div>
						<div class="flex-1" style="border-right: 1px solid #f1f1f1;">{{ item.target }}</div>
						<div class="flex-2" style="border-right: 1px solid #f1f1f1;">{{ item.task.msg.remark }}</div>
						<div class="flex-1" style="border-right: 1px solid #f1f1f1;">
							{{ item.point>0? '+'+item.point:item.point }} 
							<span>{{ item.task.msg.pt_id==3? 'B分':'A分' }}</span>
						</div>
						<div class="flex-2" v-if="item.status == 1">
							<span v-if="item.msg=='奖扣成功'" class="green">{{ item.msg }}</span>
							<span v-else class="blue">{{ item.msg }}</span>	
						</div>
						<div class="flex-2 red" v-else>{{ item.msg }}</div>
					</div>
				</div>
				<span slot="footer">
					<div class="flex-box-end" style="margin-top: 20px;" v-show="isShowError2&&results.length!=resultList.length"><el-button type="primary" @click="isResult = false" size="small">确 定</el-button></div>
					<div class="flex-box-end" style="margin-top: 20px;" v-show="results.length==resultList.length"><el-button type="primary" @click="isResult = false" size="small">确 定</el-button></div>
				</span>
			</div>
			<div v-else>
				<div style="text-align: center;" class="red">{{errorMsg}}</div>
				<span slot="footer">
					<div class="flex-box-end" style="margin-top: 20px;"><el-button type="primary" @click="isResult = false" size="small">确 定</el-button></div>
				</span>
			</div>
		</el-dialog>
		<!-- 缓存的奖扣 -->
		<el-dialog title="网络中断奖扣列表" :visible.sync="isShowBreak"  width="800" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
			<div>
				<div style="margin-top: 20px;border: 1px solid #f1f1f1;max-height: 500px;overflow-y: auto;" class="scroll-bar">
					<div class="flex-box-ce results" style="font-weight: 600;">
						<div class="flex-1" style="border-right: 1px solid #f1f1f1;">奖扣对象</div>
						<div class="flex-1" style="border-right: 1px solid #f1f1f1;">分类</div>
						<div class="flex-1" style="border-right: 1px solid #f1f1f1;">规则</div>
						<div class="flex-2" style="border-right: 1px solid #f1f1f1;">事件内容</div>
						<div class="flex-1" style="border-right: 1px solid #f1f1f1;">积分</div>
						<div class="flex-1" style="border-right: 1px solid #f1f1f1;">递交人员</div>
					</div>
					<div class="flex-box-ce results" v-for="(item, index) in breakList" :key="index">
						<div class="flex-1" style="border-right: 1px solid #f1f1f1;">{{ item.name }}</div>
						<div class="flex-1" style="border-right: 1px solid #f1f1f1;">
							<span v-if="item.rule_name">{{ item.rule_name }}</span>
							<span v-else>--</span>
						</div>
						<div class="flex-1" style="border-right: 1px solid #f1f1f1;">
							<span v-if="item.item_name">{{ item.item_name }}</span>
							<span v-else>--</span>
						</div>
						<div class="flex-2" style="border-right: 1px solid #f1f1f1;">{{ item.remark }}</div>
						<div class="flex-1" style="border-right: 1px solid #f1f1f1;">{{ item.point }} 
							<span>{{ item.pt_id==3? 'B分':'A分' }}</span>
						</div>
						<div class="flex-1" style="border-right: 1px solid #f1f1f1;">{{ item.reviewer_name }}</div>
					</div>
				</div>
				<span slot="footer">
					<div class="flex-box-end" style="margin-top: 20px;">
						<el-button type="primary" @click="colseBreak()" size="small">取 消</el-button>
						<el-button type="primary" @click="submitBreak()" size="small">再次提交</el-button>
					</div>
				</span>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import moment from 'moment';
import EmployeeSelector from '@/components/EmployeeSelector.vue';
import upload from '@/components/upload';
export default {
	name: 'bonusPointsForm',
	// 数据
	model: {
		prop: 'list',
		event: 'value'
	},
	props: {
		title: {
			type: String,
			default: ''
		},
		visible: {
			type: Boolean,
			default: false
		},
		isBreak: { //是否打开缓存的未完成奖扣
			type: Boolean,
			default: false
		},
		refresh: {
			type: String,
			default: ''
		},
		integralType: {
			type: Number,
			default: 0
			// 1 是绩效分 ， 2 是A分 , 3 是B分
		},
		ruleOnoff: {
			type: Boolean,
			default: false
			//true：选择规则； false：选择分类
		}
	},
	data() {
		return {
			pickerBeginDateBefore: {
				disabledDate(time) {
					return time.getTime() > Date.now();
				}
			},
			Xtoken: { 'X-Token': this.$getToken() },
			btn_loading: false,
			loading: false,
			dialogData: {
				members: [],
				items: [
					{
						rule_switch: true,
						rule_id: '',
						item_id: '',
						point: '0',
						remark: '',
						event_time: moment().format('YYYY-MM-DD'),
						approval: '',
						approval_not_select: [],
						pt_id: this.integralType,
						// 积分填写限制
						pointShow: 1,
						max: 0,
						min: 0,

						// 审批人信息
						reviewer_id: '',
						approvalName: '',
						approval_not_select: [],
						approval_selected: { dept: [], employee: [] },
						show_approval_selector: false,

						// 附件
						fileList: [],
						files: [],
						// 规则分类 与 规则细则 名称
						rule_list_value: null,
						rule_item_list_value: null,
						// 规则细则详情
						rule_item_details: { range_type: '' }
					}
				]
			},
			// 录入对象名称
			employeeName: '',
			employee_not_select: [],
			employee_selected: { dept: [], employee: [] },
			manage_scope: [], //下属人员
			superior_list: [], //上级人员
			show_employee_selector: false,
			// 规则分类
			rule_list: [],
			// 规则细则
			rule_item_list: [],
			flatteningIntegralRules: null,
			ptid: 0,
			itemIndex: 0,

			// 错误提示
			error_list: [], //错误信息数组
			error_list_show: false ,//错误信息弹窗
			
			// 长连接结果
			results: [], //提交的返回结果集合
			isResult: false,
			percentage: 0,
			resultList:[],//要发送数据的集合
			resultIndex:0,
			isShowError:false,
			isShowError2:false,
			errorMsg:'服务器繁忙，请稍后再试',
			breakList:[],
			isShowBreak:false,
		};
	},
	components: { EmployeeSelector, upload },
	watch: {
		isBreak(){
			let data=this.$getCache('award_punish').obj;
			data.forEach(item=>{
				item.name=this.$getCache('userList')[item.employee_id]?this.$getCache('userList')[item.employee_id].name:'--';
				item.reviewer_name=this.$getCache('userList')[item.reviewer_id]?this.$getCache('userList')[item.reviewer_id].name:'--';
			})
			this.breakList=data;
			this.isShowBreak=true;
		},
		integralType(val) {
			this.dialogData.items[0].pt_id = val;
			this.ptid = val;
			this.getRuleData();
			this.getRuleItemData();
		},
		'dialogData.members'(val) {
			if (val.length == 0) {
				this.employeeName = '';
				this.employee_selected = { dept: [], employee: [] };
			}
		},
		isResult(val){
			if(!val){
				this.isShowError = false;
				this.isShowBreak = false;
				this.$refs['dialogData'].resetFields();
				this.$emit('update:refresh',this.$moment().format().valueOf());
				this.closePopup();
				this.errorMsg='服务器繁忙，请稍后再试';
				this.$socketApi.closewebsocket();
			}
		},
	},
	mounted() {
		var that = this;
		this.getUserDetail(function(data) {
			that.manage_scope = data.manage_scope;
			that.superior_list = data.superior_list;
		});
	},
	methods: {
		// 关闭缓存弹窗
		colseBreak(){
			this.isShowBreak = false;
			this.breakList=[];
			this.$removeCache('award_punish');
			this.$emit('update:refresh',this.$moment().format().valueOf());
			this.closePopup();
		},
		// 提交缓存奖扣
		submitBreak(){
			this.$removeCache('award_punish');
			this.resultList=JSON.parse(JSON.stringify(this.breakList));
			this.resultIndex=0;
			this.percentage=0;
			this.results=[];
			this.isResult=true;
			this.opneWebSocket()
		},
		getUserDetail(func) {
			this.$axios('get', '/api/employee/detail').then(res => {
				this.$setUserData(res.data.data.user);
				func(res.data.data.user.employee_detail);
			});
		},
		submitEmployee(name) {
			this.$refs[name][0].confirm(); //调用组件的confirm（）；
		},
		submitMembers() {
			this.$refs.members.confirm(); //调用组件的confirm（）；
		},
		//关闭
		handleClose(done) {
			done();
		},
		// 附件上传
		beforeUpload(file) {
			const isJPG = /^image\/(jpeg|png|jpg)$/.test(file.type);
			const isLt2M = file.size / 1024 / 1024 < 1;
			if (!isJPG) {
				this.$message.error('上传头像图片只能是 JPEG,PNG,JPG 格式!');
			}
			if (!isLt2M) {
				this.$message.error('上传头像图片大小不能超过 2MB!');
			}
			return isJPG && isLt2M;
		},
		onFilePreView(file) {
			if (file.response) {
				window.open(file.response.url, '_blank');
			}
		},
		onFileRemove(file, fileList) {
			this.dialogData.items[this.itemIndex].fileList = fileList;
			this.dialogData.items[this.itemIndex].files = [];
			fileList.forEach((element, index) => {
				this.dialogData.items[this.itemIndex].files.push(element.url);
			});
		},
		handleFilesSuccess(response, file, fileList) {
			this.dialogData.items[this.itemIndex].fileList = fileList;
			this.dialogData.items[this.itemIndex].files = [];
			fileList.forEach((element, index) => {
				this.dialogData.items[this.itemIndex].files.push(element.url);
			});
		},

		// 没有人员提示
		noPersonnelListTips() {
			this.show_employee_selector = true;
		},
		// 当switch 改变了
		switchChange(index, value) {
			this.itemIndex = index;
			const item = this.dialogData.items[this.itemIndex];
			if (!value) {
				item.remark = '';
				item.rule_id = '';
				item.item_id = '';
				item.rule_item_list_value = '';
				item.rule_item_details = { range_type: '' };
				item.max = 0;
				item.min = 0;
				item.point = '0';
			} else {
				item.rule_id = '';
				item.rule_list_value = '';
			}
		},
		// 选择录入对象
		move_employee_confirm(data) {
			this.employee_selected = { dept: [], employee: [] };
			this.employeeName = '';
			this.dialogData.members = [];
			if (data.employee !== null && data.employee.length != 0) {
				let nameArr = [];
				data.employee.forEach(element => {
					this.employeeName += element.name + ',';
					this.employee_selected = data;
					this.dialogData.members.push(element.id);
				});
			}
			this.show_employee_selector = false;
		},
		// 获取规则类型
		getRuleData() {
			let data = { cycle_type: '1', pt_id: this.integralType };
			this.$axios('get', '/api/integral/rule/trees', data).then(res => {
				if (res.data.code == 1) {
					this.rule_list = this.getTreeData(res.data.data.rule_tree);
				}
			});
		},

		// 获取规则细则
		getRuleItemData() {
			let data = { cycle_type: '1', pt_id: this.integralType };
			this.$axios('get', '/api/integral/rule/trees', data, 'v2').then(res => {
				if (res.data.code == 1) {
					const resultData = res.data.data;
					this.rule_item_list = resultData.tree;
					this.flatteningIntegralRules = this.getItemDetail(this.rule_item_list);
					this.loading = false;
				}
			});
		},

		// 规则细则变化关闭down
		ruleItemChange(value) {
			const item = this.dialogData.items[this.itemIndex];
			if (value.length > 0) {
				let ruleItemDetails = null;
				this.flatteningIntegralRules.forEach(element => {
					if (element.id == value[value.length - 1]) {
						ruleItemDetails = { ...element };
					}
				});
				item.rule_item_details = ruleItemDetails;
				item.remark = ruleItemDetails.name;
				item.rule_id = ruleItemDetails.pid;
				item.item_id = value[value.length - 1];
				item.max = ruleItemDetails.max_point * 1;
				item.min = ruleItemDetails.min_point * 1;
				item.point = ruleItemDetails.min_point;
			} else {
				item.remark = '';
				item.rule_id = '';
				item.item_id = '';
				item.rule_item_list_value = '';
				item.rule_item_details = { range_type: '' };
				item.max = 0;
				item.min = 0;
				item.point = '0';
			}
		},
		// 规则分类变化关闭dewn
		ruleChange(value) {
			const item = this.dialogData.items[this.itemIndex];
			if (value.length > 0) {
				const user_info = this.$getUserData();
				let ruleCascader='ruleCascader'+this.itemIndex;
				user_info.point_config.point_limit.forEach(element => {
					if (this.ptid == this.integralType) {
						item.max = element.point * 1;
						item.min = element.point * -1;
					}
				});
				this.$refs.[ruleCascader][0].dropDownVisible = false;
				item.rule_id = value[value.length - 1];
				item.rule_name = this.$refs.[ruleCascader][0].getCheckedNodes()[0].label;
			} else {
				item.rule_id = '';
				item.rule_list_value = '';
				item.rule_name='';
			}
		},
		// 递归判断列表，把最后的child设为undefined
		getTreeData(data) {
			for (var i = 0; i < data.length; i++) {
				if (data[i].child.length < 1) {
					// child若为空数组，则将child设为undefined
					data[i].child = undefined;
				} else {
					// child若不为空数组，则继续 递归调用 本方法
					this.getTreeData(data[i].child);
				}
			}
			return data;
		},

		getItemDetail(arr) {
			let result = [];
			for (const item of arr) {
				var res = JSON.parse(JSON.stringify(item)); // 先克隆一份数据作为第一层级的填充
				delete res['child'];
				result.push(res);
				if (item.child instanceof Array && item.child.length > 0) {
					// 如果当前child为数组并且长度大于0，才可进入getItemDetail()方法
					result = result.concat(this.getItemDetail(item.child));
				}
			}
			return result;
		},
		// 加一条
		addItem() {
			if (this.dialogData.items.length == 10) {
				this.$message({
					type: 'warning',
					message: '一次只能添加10条奖扣'
				});
				return false;
			}
			this.dialogData.items.push({
				rule_switch: true,
				rule_id: '',
				item_id: '',
				point: '0',
				remark: '',
				event_time: moment().format('YYYY-MM-DD'),
				approval: '',
				approval_not_select: [],
				pt_id: this.integralType,

				// 积分填写限制
				pointShow: 1,
				max: 0,
				min: 0,

				// 审批人信息
				reviewer_id: '',
				approvalName: '',
				approval_not_select: [],
				approval_selected: { dept: [], employee: [] },
				show_approval_selector: false,

				// 附件
				fileList: [],
				files: [],

				// 规则分类 与 规则细则 名称
				rule_list_value: null,
				rule_item_list_value: null,

				// 规则细则详情
				rule_item_details: { range_type: '' }
			});
		},
		closeDialog(formName) {
			this.dialogData.items.forEach(element => {
				element.rule_item_details = { range_type: '' };
			});
			this.$refs[formName].resetFields();
			this.closePopup();
		},
		delItem(index) {
			this.$confirm('你确定要删除奖扣明细' + parseInt(index + 1) + '吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				this.dialogData.items.splice(index, 1);
				this.$message({
					type: 'success',
					message: '删除成功!'
				});
			});
		},
		subData(formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
					this.save();
				}
			});
		},
		// 提交数据
		save() {
			let data = {
				members: this.dialogData.members,
				items: []
			};
			const user_info = this.$getUserData();
			const index = user_info.point_config.point_limit.findIndex(o => o.pt_id === this.integralType);
			let employeePointLimitMin = null;
			let employeePointLimitMax = null;
			user_info.point_config.point_limit.forEach(element => {
				if (this.ptid == this.integralType) {
					employeePointLimitMax = element.point * 1;
					employeePointLimitMin = element.point * 1;
				}
			});
			const ruleLimitCheck = user_info.site_config.rule_limit_check;
			let maxPointPermission = 0;
			let creator = user_info.employee_detail.role_list.findIndex(item => item.name == 'creator') >= 0;
			if (user_info.point_config.point_limit.length > 0) {
				maxPointPermission = parseInt(user_info.point_config.point_limit[index].point);
			} else {
				if (creator) {
					maxPointPermission = -1;
				}
			}
			try {
				if (index < 0 || user_info.is_creator === 1) {
					this.dialogData.items.forEach((element, i) => {
						data.items.push({
							rule_id: element.rule_id || 0,
							item_id: element.item_id || 0,
							point: element.point,
							remark: element.remark,
							event_time: element.event_time,
							pt_id: this.ptid,
							rule_name:element.rule_name,
							item_name:element.rule_item_details.name,
							reviewer_id: element.reviewer_id || 0,
							files: element.files
						});
					});
				} else {
					this.dialogData.items.forEach((element, index) => {
						!element.reviewer_id ? (element.reviewer_id = 0) : '';
						!element.item_id ? (element.item_id = 0) : '';
						if (
							(element.reviewer_id && element.point !== 0 && element.rule_id > 0) ||
							(element.reviewer_id <= 0 &&
								element.item_id > 0 &&
								ruleLimitCheck &&
								element.point !== 0 &&
								element.point <= maxPointPermission &&
								Math.abs(element.point) <= maxPointPermission) ||
							(element.reviewer_id <= 0 && !ruleLimitCheck && this.integralType == 3 && element.rule_id > 0) ||
							(element.reviewer_id <= 0 &&
								element.item_id >= 0 &&
								element.point !== 0 &&
								element.point <= maxPointPermission &&
								Math.abs(element.point) <= maxPointPermission &&
								element.rule_id > 0)
						) {
							data.items.push({
								rule_id: element.rule_id || 0,
								item_id: element.item_id || 0,
								point: element.point,
								remark: element.remark,
								event_time: element.event_time,
								pt_id: this.ptid,
								reviewer_id: element.reviewer_id || 0,
								files: element.files,
								rule_name:element.rule_name,
								item_name:element.rule_item_details.name,
							});
						} else {
							this.$message.error('第' + (index + 1) + '条输入积分分值超出权限，请选择审批人递交');
							throw new Error();
						}
					});
				}
			} catch (e) {
				this.btn_loading = false;
				return false;
			}
			this.webSocket(data);
			// 走长连接处理
			return false
			this.btn_loading = true;
			this.$axios('post', this.integralType === 1 ? '' : this.integralType === 2 ? '/api/integral/review/a/entry' : '/api/integral/point/entry', data)
				.then(res => {
					if (res.data.code == 1) {
						var is = true,msg;
						if (this.integralType == '3') {
							res.data.data.list.forEach(item => {
								if (item.status != 1) {
									is = false;
									msg = item.msg;
								}
							});
						} else {
							res.data.data.list.forEach(item => {
								if (item.status != 1) {
									is = false;
									msg = item.rule_item;
								}
							});
						}
						if (is) {
							this.dialogData.items.forEach(element => {
								element.rule_item_details = { range_type: '' };
							});
							this.$refs['dialogData'].resetFields();
							this.$emit('update:visible', false);
							this.$emit('update:refresh',this.$moment().format().valueOf());
							this.closePopup();
							this.error_list = res.data.data.list;
							this.error_list_show = true;
						}
					}
				})
				.finally(e => {
					this.btn_loading = false;
				});
		},
		webSocket(data){
			let {members,items}=data;
			let arr=[];
			members.forEach(item=>{
				items.forEach(item2=>{
					item2.type = this.integralType === 2?'pea':'peb';
					item2.employee_id=item;
					arr.push(JSON.parse(JSON.stringify(item2)))
				})
			})
			this.resultList=arr;
			this.resultIndex=0;
			this.percentage=0;
			this.results=[];
			this.isResult=true;
			this.opneWebSocket()
		},
		opneWebSocket() {
			let wsData=this.resultList;
			if(wsData[this.resultIndex]&&!this.isShowError){
				this.$socketApi.sendData(wsData[this.resultIndex],this.onmessageWS)
			}
		},
		onmessageWS(e){
			if(e.type=='peb'||e.type=='pea'){
				this.results.unshift(e.result);
				this.resultIndex++;
				this.opneWebSocket();
				// 进度条
				let lng = this.resultList.length;
				this.percentage += Math.floor(100 / lng);
				if (lng == this.results.length) {
					this.percentage = 100;
				}
			}
			// 中途断开
			if(e.type=='break'){
				let wsData=this.resultList;
				this.errorMsg=e.msg
				let data={
					type:this.integralType,
					obj:wsData.slice(this.resultIndex,wsData.length)
				}
				this.$setCache('award_punish',data);
				this.isShowError2 = true;
			}
			// 连接不上
			if(e.type=='error'){
				this.errorMsg=e.msg
				this.isShowError = true;
			}
			
		},
		// 选择审核人
		approval_confirm(data) {
			const item = this.dialogData.items[this.itemIndex];
			item.approvalName = '';
			item.approval_selected.employee = { dept: [], employee: [] };
			item.reviewer_id = '';
			if (data.employee !== null && data.employee.length != 0) {
				item.approvalName = data.employee[0].name;
				item.approval_selected.employee = [{ name: data.employee[0].name, id: data.employee[0].id, img_url: data.employee[0].img_url }];
				item.reviewer_id = data.employee[0].id;
			}
			item.reviewer_id ? (item.pointShow = 3) : '';
			item.show_approval_selector = false;
		},
		// 关闭弹窗
		closePopup() {
			//关闭重置窗口状态
			this.dialogData.items = [
				{
					rule_switch: true,
					rule_id: '',
					item_id: '',
					point: '0',
					remark: '',
					event_time: moment().format('YYYY-MM-DD'),
					approval: '',
					approval_not_select: [],
					pt_id: this.integralType,
					// 积分填写限制
					pointShow: 1,
					max: 0,
					min: 0,
					// 审批人信息
					reviewer_id: '',
					approvalName: '',
					approval_not_select: [],
					approval_selected: { dept: [], employee: [] },
					show_approval_selector: false,
					// 附件
					fileList: [],
					files: [],
					// 规则分类 与 规则细则 名称
					rule_list_value: null,
					rule_item_list_value: null,
					// 规则细则详情
					rule_item_details: { range_type: '' }
				}
			];
			this.$nextTick(() => {
				this.$emit('update:visible', false);
			});
		}
	}
};
</script>
<style lang="scss">
.itemClass .el-cascader-menu .el-cascader-menu__wrap .el-scrollbar__view li.el-cascader-node {
	height: auto;
	max-width: 500px;
	.el-cascader-node__label {
		white-space: initial;
		overflow: initial;
		text-overflow: initial;
	}
}
.results {
	border-bottom: 1px solid #f1f1f1;
	text-align: center;
}
.results div {
	padding: 10px;
}
</style>
