<template>
  <div>
    <van-nav-bar :title="ptId==2?'奖扣A分':'奖扣B分'" left-text="返回" @click-left="$route_back" left-arrow></van-nav-bar>
    <div class="body_com" :class="{ isIos: isIos }">
      <scroller :isNeed="isNeed">
        <van-cell-group>
          <EmployeeSelectorCell  is_employee_list  required bar_title="选择录入对象" title="录入对象" :employee_list="manage_scope"
            v-model="employee_list" :multi="true" iconType="friends-o"  :max="10"
          ></EmployeeSelectorCell>
          <van-cell title="指定规则">
            <template slot="title">
              <span @click="openText">指定规则<van-icon name="question" class="fontColorC" style="position: relative;top: 2px;left: 3px;color:#969799;"/></span>
            </template>
            <template slot="right-icon">
              <van-switch :disabled="specified_rule_item" v-model="rule_switch" size="24"/>
            </template>
          </van-cell>
          <!--选择规则  -->
          <van-cell
            v-if="rule_switch"
            title="选择规则"
            @click="showRuleSelector = true"
            required
            :value="itemRule.length <= 0 ? '' : `已选${itemRule.length}条`"
          />

<!--          <RuleCategorySelectorCell v-if="rule_switch" required  ref="rule_selector" name="选择规则"  title="选择规则" v-model="itemRule" :ptId="ptId" scope></RuleCategorySelectorCell>-->
          <!--选择分类  -->
          <CategorySelectorCell v-if="!rule_switch" title="选择分类" ref="rule_selector2" v-model="ruleCate" required :ptId="ptId" scope></CategorySelectorCell>
        </van-cell-group>

        <div v-for="(item, index) in items" :key="index">
          <van-cell-group>
            <div class="flex-box-ce" style="padding: 0.24rem 0.32rem;font-size: 0.32rem;padding-bottom: 0rem;">
              <div class="flex-1 item-title">{{rule_switch?'已选规则':'已选分类'}}({{index+1}})</div>
              <div @click="diy_item_del(item,index)" class="red" style="font-size: 0.28rem">删除</div>
            </div>

            <div style="background-color: #f5f7fa;border-radius: 5px;padding:0.2rem;margin: 0.24rem 0.32rem;font-size: 0.28rem;">
                <div style="word-break:break-all">{{ item.name }}</div>
                <div v-if="item.range_type == 1">
                  <span :class="item.min_point > 0 ? 'red' : 'green'">{{ item.min_point }}</span>
                  {{ $getTypesName(ptId) }}
                </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 }}</span>
                  {{ $getTypesName(ptId) }}
                </div>
            </div>
            <!--申请事由  -->
            <van-cell required >
              <div class="flex-box-ce" style="font-size: 0.32rem;">
                <div class="flex-1">事件内容及描述</div>
                <div class="blue" @click="item.remark=''" style="font-size: 0.28rem">清空</div>
              </div>
              <Mtextarea v-model="item.remark"  placeholder="请输入事件内容" name="申请事由" v-validate="'required|max:300'"
              :text_max="300" :imgs_max="3" images :imgs.sync="item.files"
              ></Mtextarea>
            </van-cell>

            <!--积分  -->
            <NumberInput v-model="item.point" :min.sync="item.min_point" :max.sync="item.max_point" name="积分" title="积分" required :border="item.point_remark == ''"></NumberInput>
            <!--选择规则  -->
            <div v-if="item.point_remark != ''" class="point-remark-box">{{item.point_remark}}</div>
            <!--发生时间  -->
            <DateCell required  title="发生时间"  name="日期"  :maxDate="maxDate" v-model="item.event_time"></DateCell>
            <!--选择递交审批人  -->
            <div v-if="!isCreator">
              <EmployeeSelectorCell
                is_employee_list
                bar_title="选择递交审批人"
                title="递交审批"
                v-model="item.reviewer_list"
                :multi="false"
                 iconType="records"
                :max="1"
                :employee_list="superior_list"
              ></EmployeeSelectorCell>
            </div>

          </van-cell-group>
        </div>
        <div style="height: 5rem;"></div>
      </scroller>
    </div>
    <div v-isKeyboard>
      <div class="flex-box-ce footer">
        <van-button size="large" plain type="info" style="margin-right: 0.2rem;width: 2rem;" @click="openSelect">已选{{items.length}}条</van-button>
<!--        <van-button size="large" @click="data_verify" type="info" :disabled="!rwsHasAuth" >提交</van-button>-->
        <van-button size="large" @click="rwsBusinessVerify" type="info" :disabled="!rwsHasAuth" >提交</van-button>
      </div>
    </div>

    <!-- 提交结果 -->
<!--    <van-popup v-model="isResult" style="width: 90%;border-radius: 5px;">-->
<!--    	<div v-if="!isShowError" style="padding: 0.24rem;">-->
<!--        <van-progress :percentage="percentage" />-->
<!--    		<div style="margin-top: 10px;border: 1px solid #f1f1f1;max-height: 7rem;overflow-y: auto;" class="scroll-bar">-->
<!--    			<div class="flex-box-ce results" style="font-weight: 600;">-->
<!--    				<div style="border-right: 1px solid #f1f1f1;width: 40px;">序号</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-1" >处理结果</div>-->
<!--    			</div>-->
<!--    			<div class="flex-box-ce results" v-for="(item, index) in results" :key="index">-->
<!--    				<div style="border-right: 1px solid #f1f1f1;width: 40px;">{{results.length-index}}</div>-->
<!--    				<div class="flex-1" style="border-right: 1px solid #f1f1f1;">{{ item.target }}</div>-->
<!--    				<div class="flex-1" style="border-right: 1px solid #f1f1f1;">{{ item.point>0? '+'+item.point:item.point }}<span> {{ $getTypesName(ptId) }}</span></div>-->
<!--    				<div class="flex-1" v-if="item.status == 1">-->
<!--    					<span v-if="item.msg=='奖扣成功'" class="green">{{ item.msg }}</span>-->
<!--    					<span class="blue" v-else>{{ item.msg }}</span>-->
<!--    				</div>-->
<!--    				<div class="flex-1 red" v-else>{{ item.msg }}</div>-->
<!--    			</div>-->
<!--    		</div>-->
<!--        <div class="flex-box-end" style="margin-top: 20px;" v-show="results.length==resultList.length">-->
<!--          <van-button type="info" @click="isResult = false" size="small">确 定</van-button>-->
<!--        </div>-->
<!--    	</div>-->
<!--    	<div v-else>-->
<!--    		<div style="text-align: center;" class="red">{{errorMsg}}</div>-->
<!--    		<div>-->
<!--    			<div class="flex-box-end" style="margin-top: 10px;">-->
<!--            <van-button type="info" @click="isResult = false" size="small">确 定</van-button>-->
<!--          </div>-->
<!--    		</div>-->
<!--    	</div>-->
<!--    </van-popup>-->
    <RuleScopeSelector :visible.sync = showRuleSelector :selected="itemRule" multi @confirm="selected => itemRule = selected" :pt-id="ptId" />

<!--  rws提交结果  -->
    <van-popup v-model="rwsBusinessData.showBusiness" :close-on-click-overlay="false" style="width: 90%; border-radius: 5px;">
      <div style="padding: 0.24rem;">
        <van-progress :percentage="rwsBusinessProgress" />
        <div style="margin-top: 10px;border: 1px solid #f1f1f1;max-height: 7rem;overflow-y: auto;" class="scroll-bar">
          <div class="flex-box-ce results" style="font-weight: 600;">
            <div style="border-right: 1px solid #f1f1f1;width: 40px;">序号</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-1" >处理结果</div>
          </div>
          <div class="flex-box-ce results" v-for="(item,index) in rwsBusinessData.dataList" :key="index">
            <div style="border-right: 1px solid #f1f1f1;width: 40px;">{{`${index + 1}`}}</div>
            <div class="flex-1" style="border-right: 1px solid #f1f1f1;">{{ item.employee_name }}</div>
            <div class="flex-1" style="border-right: 1px solid #f1f1f1;">{{ item.point>0? '+'+item.point:item.point }}<span> {{ $getTypesName(ptId) }}</span></div>
            <div class="flex-1">
              <span :class="{'cyan':item.status === -2,'origin':item.status === -1,'green':item.status === 1,'red':item.status === 0}" >{{item.msg}}</span>
            </div>
          </div>
        </div>
<!--        <div class="flex-box-end" style="margin-top: 20px;" v-show="rwsBusinessProgress >= 100">-->
<!--          <van-button type="info" @click="rwsBusinessData.showBusiness = false" size="small">确 定</van-button>-->
<!--        </div>-->
        <div class="flex-box-end" style="margin-top: 20px;">
          <van-button type="info" :disabled="rwsBusinessProgress < 100" @click="rwsBusinessData.showBusiness = false" size="small" >确 定</van-button>
          <van-tag style="margin-left: 0.2rem;" @click.prevent.stop="rwsClipResult">{{rwsBusinessData.result.length}} / {{rwsBusinessData.dataList.length}}</van-tag>
        </div>
      </div>
    </van-popup>

  </div>
</template>
<script>
import Mtextarea from '@/components/Mtextarea'
import NumberInput from '@/components/NumberInput'
import EmployeeSelectorCell from '@/components/EmployeeSelectorCell'
// import RuleCategorySelectorCell from '@/components/RuleCategorySelectorCell1'
import CategorySelectorCell from '@/components/CategorySelectorCell'
import DateCell from '@/components/DateCell'
import moment from 'moment'
import Vue from 'vue'
import ImageCamera from '@/attendance/components/image-camera';
import {Switch,Progress} from 'vant'
import RuleScopeSelector from "../../../components/RuleScopeSelector.vue";
import ReconnectingWebSocket from "reconnecting-websocket";
import {generateUUID, getToken} from "../../../utils/auth";
import Clipboard from "clipboard";

Vue.use(Switch).use(Progress)
export default {
  name: 'integral_entry_n',
  components: {
    RuleScopeSelector,
    DateCell,
    Mtextarea,
    EmployeeSelectorCell,
    // RuleCategorySelectorCell,
    CategorySelectorCell,
    NumberInput,
    ImageCamera
  },
  data () {
    return {
      showRuleSelector:false,
      isNeed:!this.$getCache('isAndroid'),
      manage_scope: this.$userInfo().employee_detail.manage_scope,
      superior_list:this.$userInfo().employee_detail.superior_list,
      specified_rule_item:this.$userInfo().site_config.specified_rule_item? true:false,//奖扣时是否必选规则
      isIos: this.$getCache('iPhone'),
      ptId: 3,
      dialogData: {
        members: [],
        items: []
      },
      itemRule:[],//规则数组
      ruleCate:[],//分类数据
      rule_switch:'',
      items: [],
      item: {//模板数据
        rule_id: '',
        item_id: '',
        point: 0,
        remark: '',
        name:'',
        event_time: moment().format('YYYY-MM-DD'),
        pt_id: 3,
        // 积分填写限制
        max: 0,
        min: 0,

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

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

      employee_list: [],
      isCreator: this.$userInfo().is_creator,
      maxDate: new Date(2050, 12, 30),

      // 长连接结果
      results: [], //提交的返回结果集合
      // results:[{target: "碧玉", status: 1, point: 50, rule_item: "录入成功", msg:'奖扣成功',task: {employee_id: 1976, site_id: 389}}],
      isResult: false,
      percentage: 0,
      resultList:[],//要发送数据的集合
      resultIndex:0,
      isShowError:false,
      errorMsg:'服务器繁忙，请稍后再试',
      rws:null,
      rwsHasAuth:false,
      rwsBusinessData:{
        showBusiness:false,
        dataList:[],
        msgQueue:[],
        result:[],
        employees:[],
        items:[],
      }
    }
  },
  watch: {
    rule_switch(){
      this.itemRule=[];
      this.ruleCate=[];
      this.items=[];
    },
    ruleCate(val){
      let items = []
      val.forEach((e,index) => {
        if(this.isItemId(e.id,2)){
          let item=this.isItemId(e.id,2)
          if(item){
            item.max_point = 100000;
            item.min_point = -100000;
          }
          items.push(item)
        }else{
          let item = JSON.parse(JSON.stringify(this.item));
          item.rule_id = e.id;
          item.name=e.name
          item.max_point = 100000;
          item.min_point = -100000;
          items.push(item);
        }
      });
      this.items = items;
    },
    itemRule(rules){
      if (rules.length > 0) {
        let items = []
        rules.forEach(e => {
          if(this.isItemId(e.id,1)){
            items.push(this.isItemId(e.id,1))
          }else{
            let item = JSON.parse(JSON.stringify(this.item));
            item.remark = e.remark;
            item.name = e.remark;
            item.rule_id = e.rule_id;
            item.item_id = e.id;
            item.max = e.max_point * 1;
            item.min = e.min_point * 1;
            item.max_point = e.max_point * 1;
            item.min_point = e.min_point * 1;
            item.point = e.min_point;
            item.range_type = e.range_type;
            if (e.range_type == 1) {
              item.point_remark = '固定：' + e.min_point + this.$getTypesName(this.ptId)
            } else {
              item.point_remark = '范围(可修改)：' + e.min_point + '至' + e.max_point + this.$getTypesName(this.ptId)
            }
            items.push(item);
          }
        });
        this.items = items;
      } else {
        this.items = [];
      }
    },
    employee_list(val) {
      // if (val.length > 0) {
      //   this.dialogData.members = []
      //   this.dialogData.members=val.map(element => {
      //     return element.id
      //   })
      // } else {
      //   this.dialogData.members = []
      // }
      //
      // console.log(val);
      this.rwsBusinessData.employees = val && val.length > 0 ? val : [];
    },
    isResult(val){
    	if(!val){
    		this.isShowError = false;
    		this.errorMsg='服务器繁忙，请稍后再试';
        this.dialogData={
          members: [],
          items: []
        };
        this.itemRule=[];//规则数组
        this.ruleCate=[];//分类数据
        this.rule_switch=true;
        this.items=[];
        this.employee_list= [];
    		this.$socketApi.closewebsocket();
    	}
    },
    'rwsBusinessData.showBusiness'(v){
      if (!v){
        this.initRwsBusinessData();
        this.dialogData = {
          members: [],
          items: []
        };
        this.itemRule = [];
        this.ruleCate = [];
        this.rule_switch = true;
        this.items = [];
        this.employee_list = [];
      }
    }
  },
  computed:{
    rwsBusinessProgress(){
      return this.rwsBusinessData.dataList.length === 0 ? 0 : Math.floor(this.rwsBusinessData.dataList.filter(item => item.status >= 0).length / this.rwsBusinessData.dataList.length * 100);
    }
  },
  methods: {
    openText(){
       this.$dialog.alert({
        message: '指定规则：根据公司已经制定好的积分规则标准事由来进行奖扣或申请积分\n不指定规则：可以自由填写事由（即积分规则标准以外的内容）进行奖扣或申请积分',
      }).then(() => {
        // on close
      });
    },
    openSelect(){
      if(this.rule_switch){
          this.$refs.rule_selector.show_dept_selector=true;
      }else{
          this.$refs.rule_selector2.show_dept_selector=true;
      }
    },
    showMessage(str){
      this.$notify({type: 'danger', message: str})
    },
    data_verify () {
      // console.log(this.dialogData,this.items);return ;
      let dialogData=this.dialogData
      dialogData.items=this.items.map(e=>{
        if(e.reviewer_list.length>0){
          e.reviewer_id=e.reviewer_list[0].id
        }else{
          e.reviewer_id=''
        }
        return e
      })
      if(dialogData.members.length==0){
        this.showMessage('请选择录入对象')
        return false
      }
      if(dialogData.items.length==0){
        this.showMessage('请选择规则或者分类')
        return false
      }
      let str='';
      let isError=false
      let user_info =this.$userInfo();
      // 规则内积分是否需要检验权限分 0-不需要 1-需要
      let ruleLimitCheck = user_info.site_config.rule_limit_check;//是否现有验证权限分 0-不需要 1-需要
      let userMaxPoint = null;//当前用户权限分（正分）
      let userMinPoint = null;//当前用户权限分（负分）
      user_info.point_config.point_limit.forEach(element => {
        if (this.ptId == element.pt_id) {
          userMaxPoint = element.point * 1;
          userMinPoint = element.point * -1;
        }
      });
      if(!this.isCreator){//创始人不需要验证
          if(this.ptId==2||ruleLimitCheck||!this.rule_switch){ // 1.A分一定要验证，2.B分受配置影响，3.分类要验证
            this.dialogData.items.some((element, i) => {
              if(!element.reviewer_id){
                if(element.point>0){
                  if(element.point>userMaxPoint){ //正分判断
                    isError=true;
                    str='第' + (i + 1) + '条奖扣输入积分分值超出权限分，请选择审批人递交';
                    return true;
                  }
                }else{
                  if(element.point<userMinPoint){//负分判断
                    isError=true;
                    str='第' + (i + 1) + '条奖扣输入积分分值超出权限分，请选择审批人递交';
                    return true;
                  }
                }
              }
            })
          }
      }

      this.dialogData.items.some((element, i) => {
        if(element.point==0){
          isError=true;
          str='第' + (i + 1) + '条奖扣输入积分分值不能为0';
          return true;
        }
        if(!element.remark){
          isError=true;
          str='第' + (i + 1) + '条奖扣请输入事件内容及描述';
          return true;
        }
      })
      if(isError){
        this.$notify({type: 'danger', message: str})
        return false;
      }
      let data = {
        members: this.dialogData.members,
        items: []
      };
      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,
            reviewer_id: element.reviewer_id || 0,
            files: element.files
          });
      });
      // console.log(data,this.dialogData);this.isResult = true; return ;
      this.rwsBusinessSubmit(data.members,data.items);
      // this.webSocket(data);
    },
    webSocket(data){
    	let {members,items}=data;
    	let arr=[];
    	members.forEach(item=>{
    		items.forEach(item2=>{
    			item2.type = this.ptId === 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=='error'){
    		this.errorMsg=e.msg
    		this.isShowError = true;
    	}
    },
    //判断是否已经存在
    isItemId(id,index){
      let item='';
      this.items.some((x)=> {
        if(index==1){
          if(x.item_id==id){
            item=x
            return true;
          }
        }else{
          if(x.rule_id==id){
            item=x
            return true;
          }
        }
      });
      return item
    },
    diy_item_del (item,index) {
      this.$dialog.confirm({
          message:this.rule_switch?'你确定要删除该奖扣规则吗':'你确定要删除该奖扣分类吗'
      }).then(() => {
          if(this.rule_switch){
            this.itemRule.some((e,index2)=>{
              if(item.item_id==e.id){
                this.itemRule.splice(index2, 1);
                this.items.splice(index, 1)
                return true;
              }
            })
          }else{
            this.ruleCate.some((e,index2)=>{
               if(item.rule_id==e.id){
                this.ruleCate.splice(index2, 1);
                return true;
              }
            })
          }

      }).catch(() => {});
    },
    initRws(){
      if (this.rws){
        this.rws.close();
        this.rws = null;
        this.rwsHasAuth = false;
      }
      this.rws = new ReconnectingWebSocket(process.env.VUE_APP_WEBSCOKET);
      this.rws.onopen = this.onWsOpen;
      this.rws.onmessage = this.onWsMessage;
      this.rws.onerror = this.onWsError;
      this.rws.onclose = this.onWsClose;
    },
    initRwsBusinessData(){
      this.rwsBusinessData.dataList = [];
      this.rwsBusinessData.msgQueue = [];
      this.rwsBusinessData.result = [];
      this.rwsBusinessData.items = [];
    },
    onWsOpen(){
      let params = {
        type:'auth',
        token: getToken(),
        machine: generateUUID(),
      }
      this.rws.send(JSON.stringify(params));
    },
    onWsMessage(event){
      let msg = event.data ?  JSON.parse(event.data) : null;
      if (!msg) return;
      let type = msg.type || 'none';
      switch (type){
        case 'ping':
          this.rws.send('point entry keep connecting');
          break;
        case 'auth':
          this.rwsHasAuth = msg.code === 1;
          break;
        case 'pea':
        case 'peb':
          this.rwsBusinessData.result.push(msg);
          let businessId = msg.result.task.msg.businessId;
          this.rwsBusinessData.dataList.forEach(item => {
            if (item.businessId !== businessId) return;
            item.status = msg.result.status;
            item.msg = msg.result.msg;
          })
          this.rwsPointEntry();
          break;
      }
    },
    onWsError(event){
      console.log('on ws error',event);
      this.rwsHasAuth = false;
    },
    onWsClose(event){
      console.log('on ws close',event)
      this.rwsHasAuth = false;
    },
    clearRws(){
      if (this.rws) this.rws.close();
      this.rws = null;
      this.rwsHasAuth = false;
      this.initRwsBusinessData();
    },
    rwsPointEntry(){
      let msg = this.rwsBusinessData.msgQueue.shift();
      if (!msg) return;
      this.rwsBusinessData.dataList.forEach(item => {
        if (item.businessId !== msg.businessId) return;
        item.status = -1;
        item.msg = '处理中';
      })

      this.rws.send(JSON.stringify(msg));
    },
    rwsBusinessSubmit(members,items){
      if (!members || members.length <= 0 || !items || items.length <= 0) {
        this.showMessage('规则/分类以及录入对象必须选择');
        return;
      }

      let employeeMap = {}
      this.rwsBusinessData.employees.forEach(employee => {
        employeeMap[employee.id] = employee;
      });
      let businessId = 1;
      this.initRwsBusinessData();   //清空提交业务数据
      members.forEach(memberId => {
        items.forEach(item => {
          item.type = this.ptId === 2 ? 'pea' : 'peb';
          item.employee_id = memberId;
          item.employee_name = employeeMap[memberId] ? employeeMap[memberId].name : '';
          item.status = -2;
          item.msg = '待处理';
          item.businessId = businessId;
          this.rwsBusinessData.dataList.push(JSON.parse(JSON.stringify(item)))
          businessId++;

          /*队列数据*/
          let msg = {
            type:item.type,
            employee_id:item.employee_id,
            event_time:item.event_time,
            files:item.files,
            item_id:item.item_id,
            point:item.point,
            pt_id:item.pt_id,
            remark:item.remark,
            reviewer_id:item.reviewer_id,
            rule_id:item.rule_id,
            businessId:item.businessId,
          }
          this.rwsBusinessData.msgQueue.push(JSON.parse(JSON.stringify(msg)))
        })
      })
      this.rwsBusinessData.showBusiness = true;


      /*开始提交*/
      this.rwsPointEntry();
    },
    rwsBusinessVerify(){
      if (this.items.length === 0) {
        this.showMessage("请选择规则或者分类");
        return false;
      }

      if (this.rwsBusinessData.employees.length === 0) {
        this.showMessage("请选择录入对象");
        return false;
      }

      this.rwsBusinessData.items = this.items.map(item => {
        item.reviewer_id = item.reviewer_list.length > 0 ? item.reviewer_list[0].id : '';
        return item;
      })


      let userMaxPoint = null;
      let userMinPoint = null;

      this.$userInfo().point_config.point_limit.forEach(point => {
        if (this.ptId !== point.pt_id) return;
        userMaxPoint = Math.abs(point.point);
        userMinPoint = userMaxPoint * -1;
      });


      let members = this.rwsBusinessData.employees.map(employee => employee.id);
      let items = [];

      // for ([item,index] of this.rwsBusinessData.items){
      for (var i = 0; i < this.rwsBusinessData.items.length; i++){
        let item = this.rwsBusinessData.items[i];
        items.push({
          rule_id: item.rule_id || 0,
          item_id: item.item_id || 0,
          point: item.point,
          remark: item.remark,
          event_time: item.event_time,
          pt_id: this.ptId,
          reviewer_id: item.reviewer_id || 0,
          files: item.files
        })

        if (item.point === 0){
          this.showMessage(`第${i + 1}条奖扣输入积分分值不能为0`);
          return false;
        }
        if (!item.remark){
          this.showMessage(`第${i + 1}条奖扣请输入事件内容及描述`);
          return false;
        }

        /*非创始人并且奖扣A分/指定分类/企业配置规则内要验证权限分时,验证权限分*/
        if (!this.isCreator && (this.ptId === 2 || !this.rule_switch || this.$userInfo().site_config.rule_limit_check > 0) && userMaxPoint !== null && userMinPoint !== null){
          if (item.reviewer_id > 0) continue;

          if (item.point > 0 && item.point > userMaxPoint){
            this.showMessage(`第${i + 1}条奖扣输入积分分值超出权限分，请选择审批人递交`);
            return false;
          }else if (item.point <= 0 && item.point < userMinPoint){
            this.showMessage(`第${i + 1}`);
            return false;
          }
        }
      }

      this.rwsBusinessSubmit(members,items);
    },
    rwsClipResult(event){
      const clipboard = new Clipboard(event.target,{
        text: () => JSON.stringify(this.rwsBusinessData.result)
      });
      clipboard.on('success',() => {
        this.$notify({type: 'info', message: '复制成功'});
        clipboard.destroy();
      });
      clipboard.on('error', () => {
        this.$notify({type: 'info', message: '复制失败,请联系系统管理员'});
        clipboard.destroy();
      });
      clipboard.onClick(event);
      // navigator.clipboard.writeText(JSON.stringify(this.rwsBusinessData.result));
      // this.$notify({type: 'info', message: '结果已经复制到剪切板'})
    }
  },
  created () {
    this.itemRule=[];
    this.ruleCate=[];
    this.items=[];
    this.ptId = Number(this.$route.query.type=='1'? '2':'3')
    this.$nextTick(()=>{
      this.rule_switch=true;
    })
  },
  activated () {
    this.itemRule=[];
    this.ruleCate=[];
    this.items=[];
    this.ptId = Number(this.$route.query.type=='1'? '2':'3')
    this.$nextTick(()=>{
      this.rule_switch=true;
    })
    this.initRws();
  },
  beforeDestroy() {
    this.clearRws();
  }
}
</script>
<style scoped>
  .footer{
    padding: 0.24rem;
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 2;
    background: #fff;
    border-top: 1px solid #f1f1f1;
  }
  .results{
    font-size: 0.28rem;
    text-align: center;
    border-bottom: 1px solid #f1f1f1;
  }
  .results div {
  	padding: 3px;
  }
  .item-title{
    font-size: 0.28rem;

  }
    .search-icon {
      font-size: 16px;
      line-height: inherit;
    }
  .body_com {
    height: calc(100% - 0.92rem);
    position: relative;
    overflow-y: scroll;
  }
  .result{
    height: calc(100vh - 6.6rem);
    position: relative;
  }
  .add_item_cell .van-icon {
    color: #1989fa;
  }

  .add_item_cell .van-cell__title span {
    color: #1989fa;
  }
  .item-del-btn {
    float: right;
  }

  .point-remark-box {
    color: #969799;
    padding: 0.16rem 0.32rem;
    position: relative;
    padding-top: 0;
    padding-left: 2.1rem;
    font-size: 0.24rem;
  }
  /deep/ .van-dialog__message{
    text-align: left;
  }
  .point-remark-box:after {
    position: absolute;
    box-sizing: border-box;
    content: ' ';
    pointer-events: none;
    right: 0;
    bottom: 0;
    left: 0.32rem;
    border-bottom: 0.02rem solid #ebedf0;
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
  }
  .rentrun {
  width:100vw;
  background: #fff;
}
.isIos {
  height: calc(100% - 2.6rem);
}
.successful_alert{
  padding-top:0.5rem;
}
.successful_alert /deep/ .head_icon .sucessful_icon{
  width:1.28rem;
  height:1.28rem;
  color:#26A2FF;
  padding-top:0.5rem;
}
.successful_alert /deep/ .head_icon .overdue_deduction{
  width:1.28rem;
  height:1.28rem;
  color:#F56C6C;
  padding-top:0.5rem;
}
.row_line_bg{
  background: #f1f1f1;
  font-size: 0.32rem;
  padding: 0.1rem 0.32rem;
}

.buttom_btn{
  line-height: 0.83rem;
  text-align: center;
  font-size: 0.32rem;
  position: relative;
  /* color: #909399 */
}
.buttom_btn.one::after{
  content: '';
  width: 1px;
  height: 0.85rem;
  background: #f1f1f1;
  display: block;
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
}
</style>
