<template>
	<div>
		<!-- 奖扣ab分弹窗 -->
		<el-dialog :title="title" :visible.sync="visible" :close-on-click-modal="false" :before-close="closeDialog2" width="600px">
			<div>
				<el-form :model="dialogData" ref="dialogData" label-width="80px" v-loading="loading">
					<div v-for="(item, index) in dialogData.items" :key="index" @click="setIndex(index)">
						<div style="overflow: hidden;" class="flex-box flex-v-ce">
							<span style="line-height: 36px;" class="flex-1">申请明细({{ index + 1 }})</span>
							<el-button type="text" v-show="index > 0 || dialogData.items.length > 1" @click="delItem(index)">删除</el-button>
						</div>
						<el-form-item label="录入对象" :prop="'items.' + index + '.employeeName'" :rules="[{ required: true, message: '请选择录入对象', trigger: 'change' }]">
							<el-row>
								<el-col :span="18">
									<el-input auto-complete="off" v-model="item.employeeName" placeholder="请选择录入对象"></el-input>
									<div @click="item.show_employee_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_employee_selector" append-to-body :before-close="handleClose">
								<EmployeeSelector
									v-if="item.show_employee_selector"
									ref="employee"
									:multi="false"
									:user_no_select="false"
									:selected="item.employee_selected"
									@confirm="employee_confirm"
								/>
								<span slot="footer" class="dialog-footer">
									<el-button @click="item.show_employee_selector = false">取 消</el-button>
									<el-button type="primary" @click="submitMembers('employee')">确 定</el-button>
								</span>
							</el-dialog>
						</el-form-item>
						<el-form-item label="指定规则"><el-switch v-model="item.rule_switch" @change="switchChange(index, item.rule_switch)" :disabled="ruleOnoff"></el-switch></el-form-item>
						<el-form-item
							label="选择规则"
							v-if="item.rule_switch"
							:prop="'items.' + index + '.rule_item_list_value'"
							:rules="[{ required: true, message: '请选择规则', trigger: 'change' }]"
						>
							<el-cascader
								v-model="item.rule_item_list_value"
								ref="ruleItem"
								:popper-class="'itemClass'"
								:options="rule_item_list"
								@change="ruleItemChange"
								:show-all-levels="false"
								filterable
								@expand-change="setIndex(index)"
								clearable
								:props="{ children: 'child', label: 'name', value: 'id' }"
							></el-cascader>
						</el-form-item>

						<el-form-item v-if="item.rule_switch && item.rule_id">
							<div style="line-height: 24px;" v-show="item.rule_item_details.range_type == 1">
								{{ item.rule_item_details.min_point }}
								<span class="blue">{{ $getTypsName(item.rule_item_details.pt_id) }}</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(item.rule_item_details.pt_id) }}</span>
							</div>
							<div style="line-height: 24px;">{{ item.rule_item_details.name }}</div>
						</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: 3, max: 300, message: '长度在 3 到 300 个字符', trigger: 'blur' }]"
						>
							<el-row>
								<el-col :span="18"><el-input type="textarea" rows="5" placeholder="请输入事件内容" style="width: 100%;" v-model="item.remark"></el-input></el-col>
							</el-row>
						</el-form-item>

						<el-form-item label="图片" label-width="100px">
							<uploadOss
								: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"
								accept="image/jpeg,image/png"
								:multiple="true"
								ref="clearPicture"
							>
								<el-button size="small" type="primary">点击上传</el-button>
								（最多选择3张）
							</uploadOss>
						</el-form-item>

						<el-form-item
							v-loading.lock="fullscreenLoading"
							label="审批人"
							:prop="'items.' + index + '.approvalName'"
							:rules="[{ required: true, message: '请选择审批人', trigger: 'blur' }]"
						>
							<el-row>
								<el-col :span="18">
									<el-input auto-complete="off" v-model="item.approvalName" placeholder="请选择审批人"></el-input>
									<div @click="approval_selected_null(item)" 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
									:can_select_employee="true"
									v-if="item.show_approval_selector"
									ref="approval"
									:multi="false"
									:employee_list="item.approval_employee_list"
									:user_no_select="false"
									:isCreatorSelect="true"
									: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="submitApproval('approval')">确 定</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="closeDialog2('dialogData')">取 消</el-button>
						<el-button :disabled="btn_loading" :loading="btn_loading" type="primary" @click="subData('dialogData')">确 认</el-button>
					</el-form-item>
				</el-form>
			</div>
		</el-dialog>

		<el-dialog :title="'提交结果'" :visible.sync="error_list_show" :before-close="closeDialog2" :append-to-body="true" width="700px">
			<el-table :data="error_list">
				<el-table-column prop="target" label="员工"></el-table-column>
				<el-table-column prop="status" label="处理状态">
					<template slot-scope="scope">
						<span :style="'color:' + (scope.row.status == 0 ? '#f70000' : '#47bf47')">{{ scope.row.status == 0 ? '申请失败' : '申请成功' }}</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 class="" 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 class="orange" style="text-align: center;padding-top: 10px;" v-if="config.event_review_status&&config.event_apply_review">复核开启后，积分需管理员复核后才计入排名和统计</div>
				<div style="margin-top: 20px;border: 1px solid #f1f1f1;">
					<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.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 green" v-if="item.status == 1">{{ item.msg }}</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';
import uploadOss from '@/components/upload';
export default {
	name: 'applicationIntegration',
	// 数据
	model: {
		prop: 'list',
		event: 'value'
	},
	props: {
		title: {
			type: String,
			default: ''
		},
		visible: {
			type: Boolean,
			default: false
		},
		isBreak: { //是否打开缓存的未完成奖扣
			type: Boolean,
			default: false
		},
		integralType: {
			type: Number,
			default: 0
		},
		ruleOnoff: {
			type: Boolean,
			default: false
			//true：选择规则； false：选择分类
		}
	},
	data() {
		var getUserData = this.$getUserData();
		return {
			pickerBeginDateBefore: {
				disabledDate(time) {
					return time.getTime() > Date.now();
				}
			},
			error_list: [], //错误信息数组
			error_list_show: false, //错误信息弹窗
			Xtoken: { 'X-Token': this.$getToken() },
			loading: false,
			dialogData: {
				items: [
					{
						rule_switch: true,
						rule_id: '',
						item_id: '',
						remark: '',
						event_time: moment().format('YYYY-MM-DD'),

						// 录入对象
						employee_id: getUserData.id,
						employeeName: getUserData.name,
						employee_selected: { dept: [], employee: [{ id: getUserData.id, name: getUserData.name }] },
						show_employee_selector: false,

						// 审批人信息
						reviewer_id: '',
						approvalName: '',
						approval_selected: { dept: [], employee: [] },
						approval_employee_list: [], //当前选中人的 上级
						show_approval_selector: false,

						// 附件
						fileList: [],
						files: [],
						// 规则分类 与 规则细则 名称
						rule_list_value: null,
						rule_item_list_value: null,
						rule_item_details: { range_type: '' }
					}
				]
			},
			// 规则分类
			rule_list: [],
			// 规则细则
			rule_item_list: [],
			flatteningIntegralRules: null,
			user_info: null,
			btn_loading: false,
			itemIndex: 0,
			fullscreenLoading: false, //选择审批人时需要，获取录入对象的上级
			LocalValObj: { id: '', name: '' } ,//当前录入的审批人缓存
			
			// 长连接结果
			results: [], //提交的返回结果集合
			isResult: false,
			percentage: 0,
			resultList:[],//要发送数据的集合
			resultIndex:0,
			isShowError:false,
			isShowError2:false,
			errorMsg:'服务器繁忙，请稍后再试',
			breakList:[],
			isShowBreak:false,
			config:{},
		};
	},
	components: { EmployeeSelector, uploadOss },
	async mounted() {
		this.config=this.$store.state.config;
		this.user_info = this.$getUserData();
		var reviewerObj = await this.getLocalVal(this.user_info.id);
		var res = reviewerObj ? reviewerObj : { id: '', name: '' };
		this.LocalValObj = res;
		this.getRuleItemData();
		// 初始化审批人
		if (this.LocalValObj.id) {
			this.dialogData.items[0].approval_selected.employee = [this.LocalValObj];
			this.dialogData.items[0].reviewer_id = this.LocalValObj.id;
			this.dialogData.items[0].approvalName = this.LocalValObj.name;
		}
		if(this.isBreak){
			let data=this.$getCache('apply_list');
			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;
		}
	},
	watch:{
		isResult(val){
			if(!val){
				this.isShowError=false;
				this.isShowBreak = false;
				this.errorMsg='服务器繁忙，请稍后再试';
				this.$refs['dialogData'].resetFields();
				this.closeDialog();
				this.closeDialog2();
				this.$socketApi.closewebsocket();
			}
		}
	},
	methods: {
		setIndex(index){
		  if(index==this.itemIndex){
		    return false
		  }
		  this.itemIndex = index;
		},
		// 关闭缓存弹窗
		colseBreak(){
			this.isShowBreak = false;
			this.breakList=[];
			this.$removeCache('apply_list');
			this.closeDialog();
			this.closeDialog2();
		},
		// 提交缓存申请
		submitBreak(){
			this.$removeCache('apply_list');
			this.resultList=JSON.parse(JSON.stringify(this.breakList));
			this.resultIndex=0;
			this.percentage=0;
			this.results=[];
			this.isResult=true;
			this.opneWebSocket()
		},
		
		//获取缓存起来的审批人
		getLocalVal(id) {
			return new Promise((resolve, reject) =>{
				let obj;
				this.$axios('get', '/api/employee/info', { id: id }).then(res =>{
					if(res.data.code == 1){
						let data = res.data.data;
						if(data.employee_detail.superior_list && data.employee_detail.superior_id != 0){
							obj = data.employee_detail.superior_list.filter(x => x.id == data.employee_detail.superior_id)[0];
							if(obj.id == this.user_info.id){
								obj = this.$getCache(id)
							}
						}else{
							obj = this.$getCache(id);
						}
					}
				}).finally(_ =>{
					resolve(obj)
				})
			})
		},
		submitMembers(name) {
			this.$refs[name][0].confirm(); //调用组件的confirm（）；
		},
		submitApproval(name) {
			this.$refs[name][0].confirm(); //调用组件的confirm（）；
		},
		//关闭
		handleClose(done) {
			done();
		},
		// 附件上传
		beforeUpload(file) {
			const isJPG = /^image\/(jpeg|png|jpg)$/.test(file.type);
			const isLt2M = file.size / 1024 / 1024 < 5;
			if (!isJPG) {
				this.$message.error('上传图片只能是 JPEG,PNG,JPG 格式!');
			}
			if (!isLt2M) {
				this.$message.error('上传图片大小不能超过 5MB!');
			}
			return isJPG && isLt2M;
		},
		onFilePreView(file) {
			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) {
			let fileListData=fileList.filter(e=>{
			  return e.url
			})
			this.dialogData.items[this.itemIndex].fileList = fileListData;
			this.dialogData.items[this.itemIndex].files = [];
			fileListData.forEach((element, index) => {
				this.dialogData.items[this.itemIndex].files.push(element.url);
			});
		},

		// 选择审批人前提
		approval_selected_null(item) {
			if (!item.employee_id) {
				this.$message.error('请先选择录入对象');
			} else {
				this.fullscreenLoading = true;
				this.getEmployeeList(item.employee_id, function(res) {
					if (res.length > 0) {
						item.approval_employee_list = res;
						item.show_approval_selector = true;
					} else {
						this.$message.error('您没有审批人，请联系管理员');
					}
				});
			}
		},
		//获取人员（上级人员）
		getEmployeeList(userIdArr, callBack) {
			this.$axios('get', 'api/employee/superior', { employee_id: userIdArr, filter_applyor: 1 })
				.then(res => {
					callBack(res.data.data.list);
				})
				.finally(() => {
					this.fullscreenLoading = false;
				});
		},
		// 获取规则信息
		getRuleData() {
			let data = {
				cycle_type: '1'
			};
			this.integralType === 1 ? (data.pt_id = '1') : this.integralType === 2 ? (data.pt_id = '2') : (data.pt_id = '3');
			this.$axios('get', '/api/integral/rule/trees', data).then(res => {
				if (res.data.code == 1) {
					const resultData = res.data.data;
					this.rule_list = resultData.rule_tree;
				}
				this.rule_list = this.getTreeData(this.rule_list);
			});
		},
		// 获取规则细则
		getRuleItemData() {
			let data = { cycle_type: '1' };
			this.loading = true;
			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 ruleItemDetail = null;
				this.flatteningIntegralRules.forEach(element => {
					if (element.id == value[value.length - 1]) {
						ruleItemDetail = { ...element };
					}
				});
				item.rule_item_details = ruleItemDetail;
				item.remark = ruleItemDetail.name;
				item.rule_id = ruleItemDetail.pid;
				item.pt_id = ruleItemDetail.pt_id;
				item.item_id = value[value.length - 1];
				item.item_name = ruleItemDetail.name;
				this.$refs.ruleItem.dropDownVisible = false;
			}else{
				item.rule_id = '';
				item.pt_id="";
				item.item_id = '';
				item.remark =  '';
				item.item_name =  '';
				item.rule_item_list_value = '';
				item.rule_item_details = { range_type: '' };
			}	
		},
		// 递归判断列表，把最后的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;
		},
		// 选择对象
		async employee_confirm(data) {
			const item = this.dialogData.items[this.itemIndex];
			item.employeeName = '';
			item.employee_selected = { dept: [], employee: [] };
			item.employee_id = '';

			if (data.employee !== null && data.employee.length != 0) {
				item.employeeName = data.employee[0].name;
				item.employee_selected.employee = [{ name: data.employee[0].name, id: data.employee[0].id, img_url: data.employee[0].img_url }];
				item.employee_id = data.employee[0].id;

				var reviewerObj = await this.getLocalVal(data.employee[0].id);
				var revieObj = reviewerObj ? reviewerObj : { id: '', name: '' };
				// 清空审批人数据
				if (revieObj.id) {
					item.approval_selected = { dept: [], employee: [revieObj] };
				} else {
					item.approval_selected = { dept: [], employee: [] };
				}
				item.reviewer_id = revieObj.id;
				item.approvalName = revieObj.name;
				item.approval_employee_list = []; //当前选中人的 上级
			}
			item.show_employee_selector = false;
		},

		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: '',
				remark: '',
				event_time: moment().format('YYYY-MM-DD'),

				// 录入对象
				employee_id: this.user_info.id,
				employeeName: this.user_info.name,
				employee_selected: { dept: [], employee: [{ id: this.user_info.id, img_url: this.user_info.img_url, name: this.user_info.name }] },
				show_employee_selector: false,

				// 审批人信息
				reviewer_id: this.LocalValObj.id,
				approvalName: this.LocalValObj.name,
				approval_selected: { dept: [], employee: this.LocalValObj.id ? [this.LocalValObj] : [] },
				approval_employee_list: [], //当前选中人的 上级
				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 = [
				{
					rule_switch: true,
					rule_id: '',
					item_id: '',
					remark: '',
					event_time: moment().format('YYYY-MM-DD'),

					// 录入对象
					employee_id: this.user_info.id,
					employeeName: this.user_info.name,
					employee_selected: { dept: [], employee: [{ id: this.user_info.id, img_url: this.user_info.img_url, name: this.user_info.name }] },
					show_employee_selector: false,

					// 审批人信息
					reviewer_id: '',
					approvalName: '',
					approval_employee_list: [], //当前选中人的 上级
					approval_selected: { dept: [], employee: [] },
					show_approval_selector: false,

					// 附件
					fileList: [],
					files: [],
					// 规则分类 与 规则细则 名称
					rule_list_value: null,
					rule_item_list_value: null,
					rule_item_details: { range_type: '' }
				}
			];
		},
		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();
				}
			});
		},
		closeDialog2(){
			this.$emit('update:visible', false);
		},
		// 提交数据
		save() {
			let data = { items: [] };
			this.dialogData.items.forEach(element => {
				data.items.push({
					rule_id: element.rule_id || 0,
					employee_id: element.employee_id,
					item_id: element.item_id || 0,
					item_name: element.item_name,
					remark: element.remark,
					event_time: element.event_time,
					pt_id: element.pt_id,
					reviewer_id: element.reviewer_id || 0,
					approvalName: element.approvalName,
					files: element.files
				});
			});
			this.webSocket(data);
			// 走长连接处理
			return false;
			this.btn_loading = true;
			this.$axios('post', '/api/integral/review/apply', data)
				.then(res => {
					if (res.data.code == 1) {
						this.closeDialog();
						this.error_list = res.data.data.list;
						this.error_list_show = true;
					}
				})
				.finally(() => {
					this.btn_loading = false;
					data.items.forEach(element => {
						this.$setCache(element.employee_id,{ id: element.reviewer_id, name: element.approvalName });
					});
				});
		},
		webSocket(data){
			data.items.forEach(item=>{
				item.type='point_apply';
				this.$setCache(item.employee_id,{ id: item.reviewer_id, name: item.approvalName });
			})
			this.resultList=data.items;
			this.resultIndex=0;
			this.percentage=0;
			this.results=[];
			this.isResult=true;
			this.opneWebSocket()
		},
		opneWebSocket() {
			let wsData=this.resultList;
			if(wsData[this.resultIndex]){
				this.$socketApi.sendData(wsData[this.resultIndex],this.onmessageWS)
			}else{
				console.log(this.results)
			}
			
		},
		onmessageWS(e){
			if(e.type=='point_apply'){
				this.results.push(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
				this.$setCache('apply_list',wsData.slice(this.resultIndex,wsData.length));
				this.isShowError2 = true;
			}
			// 连接不上
			if(e.type=='error'){
				this.errorMsg=e.msg
				this.isShowError = true;
			}
		},
		// 当switch 改变了
		switchChange(index, value) {
			this.itemIndex = index;
			const item = this.dialogData.items[this.itemIndex];
			if (!value) {
				item.rule_id = '';
				item.item_id = '';
				item.rule_item_list_value = '';
				item.remark =  '';
				item.rule_item_details = { range_type: '' };
			} else {
				item.rule_id = '';
				item.rule_list_value = '';
			}
		},
		// 选择审核人
		approval_confirm(data) {
			const item = this.dialogData.items[this.itemIndex];
			item.approvalName = '';
			item.approval_selected = { 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.show_approval_selector = false;
		}
	}
};
</script>
<style lang="scss">
.itemClass .el-cascader-menu .el-cascader-menu__wrap 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>
