<template>
  <div>
    <van-nav-bar title="积分申请" left-text="返回" @click-left="$route_back" left-arrow></van-nav-bar>
    <div class="body_com">
      <scroller :isNeed="isNeed">
        <van-cell-group>
          <EmployeeSelectorCell  required bar_title="选择录入对象" title="录入对象"
           v-model="employee_list"
            iconType="friends-o"
           :multi="false"
           :is_filtration_creator="true"
          ></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}条`"
          />
          <RuleScopeSelector :visible.sync = showRuleSelector :selected="itemRule" multi @confirm="selected => itemRule = selected" />
<!--          <RuleCategorySelectorCell v-if="rule_switch" required  ref="rule_selector" name="选择规则"  title="选择规则" v-model="itemRule" scope/>-->
        </van-cell-group>

        <div v-for="(item, index) in items" :key="index">
          <van-cell-group>
            <template v-if="item.item_id">
              <div class="flex-box-ce" style="padding: 0.24rem 0.32rem;font-size: 0.32rem;padding-bottom: 0rem;">
                <div class="flex-1 item-title">已选规则({{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.ruleData.remark }}</div>
                  <div v-if="item.ruleData.range_type == 1">
                    <span :class="item.ruleData.min_point > 0 ? 'red' : 'green'">{{ item.ruleData.min_point }}</span>
                    {{ $getTypesName(item.pt_id) }}
                  </div>
                  <div v-if="item.ruleData.range_type == 2">
                    <span :class="item.ruleData.min_point > 0 ? 'red' : 'green'">{{ item.ruleData.min_point }}</span>
                    至
                    <span :class="item.ruleData.max_point > 0 ? 'red' : 'green'">{{ item.ruleData.max_point }}</span>
                    {{ $getTypesName(item.pt_id) }}
                  </div>
              </div>
            </template>


            <!--申请事由  -->
            <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>

            <!--发生时间  -->
            <DateCell required  title="发生时间"  name="日期" :maxDate="maxDate"  v-model="item.event_time"></DateCell>
            <!--选择递交审批人  -->
            <div>
              <van-cell v-if="change_reviewer" is-link required title="审批人" class="noInput" :value="userName" ></van-cell>
              <EmployeeSelectorCell
                v-else
                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: 1rem;"></div>
      </scroller>
    </div>
    <div style="padding:0.32rem;" class="flex-box-ce">
      <van-button size="large" plain type="info" style="margin-right: 0.2rem;width: 2rem;" @click="openSelect" v-if="rule_switch">已选{{items.length}}条</van-button>
      <van-button size="large" @click="data_verify" :disabled="subloading" type="info">提交</van-button>
    </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" >处理结果</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 font-flex-word" v-if="item.status == 1">
    					<span class="green">提交成功</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>
  </div>
</template>
<script>
import Mtextarea from '@/components/Mtextarea'
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 {Switch,Progress,Icon  } from 'vant'
import RuleScopeSelector from "../../../components/RuleScopeSelector.vue";

Vue.use(Switch).use(Progress).use(Icon)

export default {
  name: 'integral_application',
  components: {
    RuleScopeSelector,
    DateCell,
    Mtextarea,
    EmployeeSelectorCell,
    // RuleCategorySelectorCell,
    CategorySelectorCell,
  },
  data () {
    let date = moment().format('YYYY-MM-DD')
    return {
      showRuleSelector:false,
      specified_rule_item:this.$userInfo().site_config.specified_rule_item? true:false,//奖扣时是否必选规则
      isNeed:!this.$getCache('isAndroid'),
      close_buttom: false,
      superior_list:this.$userInfo().employee_detail.superior_list,
      employee_list: [this.$userInfo()],
      employeeid:this.$userInfo().id,
      ptId:3,
      change_reviewer:Number(this.$userInfo().site_config.change_reviewer),//是否允许员工修改审批人
      userName:'',
      items: [],
      item:{
            rule_id: '',
            item_id: '',
            remark: '',
            ruleData:{},
            event_time: moment().format('YYYY-MM-DD'),

            // 审批人信息
            reviewer_id: '',
            reviewer_list:[],

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

      subloading: false,

      itemRule:[],//规则数组
      rule_switch:true,
      maxDate: new Date(),

      // 长连接结果
      results: [], //提交的返回结果集合
      isResult: false,
      percentage: 0,
      resultList:[],//要发送数据的集合
      resultIndex:0,
      isShowError:false,
      errorMsg:'服务器繁忙，请稍后再试',
    }
  },
  watch: {
    rule_switch(){
      if(this.rule_switch){
        this.items=[];
      }else{
        this.items=[JSON.parse(JSON.stringify(this.item))];
      }
    },
    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.ruleData = e;
            item.rule_id = e.rule_id;
            item.item_id = e.id;
            item.pt_id = e.pt_id;
            items.push(item);
          }
        });
        this.items = items;
      } else {
        this.items = [];
      }
    },
    employee_list(val) {
      if (val.length > 0) {
        this.employeeid=val[0].id;
        this.initializesReviewer(val[0].id);
      } else {
        this.employeeid = ''
        this.items.forEach(item=>{
          item.reviewer_id='';
          item.reviewer_list=[];
        })
      }
    },
    isResult(val){
    	if(!val){
    		this.isShowError = false;
    		this.errorMsg='服务器繁忙，请稍后再试';
        this.itemRule=[];//规则数组
        this.rule_switch=true;
        this.items=[];
        // this.employee_list= [];
    		this.$socketApi.closewebsocket();
    	}
    },
  },
  mounted() {
    this.initializesReviewer(this.employeeid);
    if (window.plus) { //针对IOS 11的优化
      var str = window.plus.device.model;
       if (str.indexOf('11') >= 0) {
         this.maxDate=new Date(2050,12,30);
       }
    }
  },
  methods: {
    openText(){
       this.$dialog.alert({
        message: '指定规则：根据公司已经制定好的积分规则标准事由来进行奖扣或申请积分\n不指定规则：可以自由填写事由（即积分规则标准以外的内容）进行奖扣或申请积分',
      }).then(() => {
        // on close
      });
    },
    diy_item_del (item,index) {
      this.$dialog.confirm({
          message:'你确定要删除该奖扣规则吗'
      }).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.items.splice(index, 1)
          }
      }).catch(() => {});
    },
    //判断是否已经存在
    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
    },
    // 初始化审核人
    initializesReviewer(id) {
      var superiorList=this.$getEmployeeMapItem(id).employee_detail.superior_list;//选择录入对象的上级集合
      this.superior_list=superiorList;//当前选中人的 上级
      let obj = this.item;
      this.$axiosUser('get','/api/pro/employee/superior',{employee_id:id,manage_scope: '1',platform:'1'}).then(res => {
         var list=res.data.data.list;
         var users= [...list].filter(x => [...superiorList].some(y => y.id === x.id));//获取录入对象的上级与直属上级的交集
         if(users.length>0){
           obj.reviewer_id = users[0].id;
           obj.reviewer_list=[users[0]];
           this.userName=users[0].name
         }else{
           obj.reviewer_id = list[0].id;
           obj.reviewer_list=[list[0]];
           this.userName=list[0].name
         }
         this.items.forEach(item=>{
           if(users.length>0){
             item.reviewer_id = users[0].id;
             item.reviewer_list=[users[0]];
           }else{
             item.reviewer_id = list[0].id;
             item.reviewer_list=[list[0]];
           }
         })

      });
    },
    openSelect(){
      if(this.rule_switch){
          this.$refs.rule_selector.show_dept_selector=true;
      }
    },
    showMessage(str){
      this.$notify({type: 'danger', message: str})
    },
    data_verify () {
      let self = this
      if(!this.employeeid){
        this.showMessage('请选择录入对象')
        return false
      }
      if(this.items.length==0){
        this.showMessage('请选择规则')
        return false
      }
      let str='';
      let isError=false
      this.items.some((item,i)=>{
        if(!item.remark){
          isError=true;
          str='第' + (i + 1) + '条申请，请输入事件内容及描述';
          return true;
        }
        if(item.reviewer_list.length==0){
          isError=true;
          str='第' + (i + 1) + '条申请，请选择审批人';
          return true;
        }
        if(item.event_time>moment().format('YYYY-MM-DD')){
          isError=true;
          str='第' + (i + 1) + '条申请，发生时间不能大于今天';
          return true;
        }

      })
      if(isError){
        this.showMessage(str)
        return false;
      }
      let data = [];
      this.items.forEach(element => {
        let obj={
          rule_id: element.rule_id || 0,
          employee_id: this.employeeid || 0,
          item_id: element.item_id || 0,
          remark: element.remark,
          event_time: element.event_time,
          files: element.files,
          type:'point_apply'
        }
        if(element.reviewer_list[0]){
          obj.reviewer_id=element.reviewer_list[0].id;
        }
        data.push(obj);
      });
      if(data[0].item_id){
        this.webSocket(data);
        return false;
      }
      this.subloading=true;
      let obj={items:data}
      this.$axiosUser('post', '/api/pro/integral/review/apply', obj, 'v2').then(res => {
          let item=res.data.data.list[0]
          if(item.status===0){
            this.showMessage(item.msg)
          }else{
            this.$toast('提交成功')
            this.itemRule=[];//规则数组
            this.rule_switch=true;
            this.items=[];
          }
      }).finally(() => {
        this.subloading = false;
      })
    },
    webSocket(data){
    	this.resultList=data;
    	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=='point_apply'){
    		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;
    	}
    },
  }
}
</script>
<style scoped>
  /deep/ .van-dialog__message{
    text-align: left;
  }
  .noInput{
        background-color: #F5F7FA;
        border-color: #E4E7ED;
        color: #C0C4CC;
        cursor: not-allowed;
  }
  .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% - 2.6rem);
    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;
  }

  .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;
}
.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>
