<template>
  <div>
    <el-dialog :title="title" top="60px" :visible.sync="visible" :close-on-click-modal="false" :before-close="closePopup" @open="openDialog" width="800px"  >
      <div>
        <el-form :model="dialogData" style="max-height: 600px;overflow-y: scroll;padding-right: 20px;" ref="dialogData" label-width="100px" v-loading="loading" class="form">
          <el-form-item label="录入对象" :rules="[{ required: true, message: '请选择录入对象'}]">
            <el-input class="w250" auto-complete="off" v-model="employeeName" placeholder="请选择录入对象"></el-input>
            <div @click="show_employee_selector = true" style=" position: absolute; top: 0; right: 0; left: 0; bottom: 0; z-index: 9;"></div>
            <EmployeeSelector
              :isChecKedAll="false"
              :multi="false"
              :selected="employee_selected"
              :visible.sync="show_employee_selector"
              @confirm="employee_confirm"
            />
          </el-form-item>

          <el-form-item label="指定规则">
            <template slot="label">
              <span>指定规则</span>
              <el-tooltip placement="top">
                <div slot="content" style="width: 450px;">指定规则：根据公司已经制定好的积分规则标准事由来进行奖扣或申请积分<br/>不指定规则：可以自由填写事由（即积分规则标准以外的内容）进行奖扣或申请积分</div>
                <span class="tips">?</span>
              </el-tooltip>
            </template>
            <el-switch :disabled="specified_rule_item" @change="switchChange(dialogData.rule_switch)" v-model="dialogData.rule_switch" active-color="#13ce66"></el-switch>
          </el-form-item>

          <el-form-item label="选择规则" v-show="dialogData.rule_switch">
            <div class="inputBox" @click="isShowRule = true">
              <span v-if="dialogData.items.length > 0">已选择了{{dialogData.items.length}}条</span>
              <span v-else style="color: #909399;">请选择</span>
            </div>
          </el-form-item>
          <div v-for="(item, index) in dialogData.items" :key="index" @click.stop="setIndex(index)" style="margin-bottom: 10px;">
            <div class="title flex-box-ce" style="margin-bottom: 16px;" v-if="item.item_id">
              <span style="line-height: 36px; width: 100px;text-align: right;padding-right: 12px;font-weight: 700;">已选规则({{ index + 1 }})</span>
              <div class="flex-1"></div>
              <el-link type="danger"  v-show="(index > 0 || dialogData.items.length > 1) && dialogData.rule_switch" @click="delItem(item.item_id,index)">删除</el-link>
            </div>
            <el-form-item label="积分规则" v-if="item.item_id">
              <div style="line-height: 24px;background-color: #E4F0FC;border-radius: 3px;padding:8px 10px;">
                <div>{{ 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>
                  {{ $getTypsName(item.ruleData.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>
                  {{ $getTypsName(item.ruleData.pt_id) }}
                </div>
              </div>
            </el-form-item>

            <el-form-item
              label="事件内容"
              :prop="'items.' + index + '.remark'"
              :rules="[{ required: true, message: '请输入事件内容'}, { min: 2, max: 300, message: '长度在 2 到 300 个字符'}]"
            >
              <el-input type="textarea" clearable maxlength="300" show-word-limit rows="4" placeholder="请输入事件内容" v-model="item.remark" @input="onRemarkInput(item)"></el-input>
              <el-button @click="item.remark=''" type="danger" plain size="mini" style="position: absolute;right: 0px;bottom: -30px;z-index: 99999;">清空</el-button>
            </el-form-item>

            <el-form-item label="图片" style="margin-top: 30px;">
              <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"
                list_type="picture-card"
                :accept="$acceptImg"
                :multiple="true"
                ref="clearPicture"
              >
                <i class="el-icon-plus"></i>
              </uploadOss>
            </el-form-item>

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

            <el-form-item label="递交审批" v-if="!isCreator">
              <el-input class="w250" auto-complete="off" :disabled="change_reviewer" v-model="item.approvalName" placeholder="请选择审批人"></el-input>
              <div v-if="!change_reviewer" @click="item.show_approval_selector = true" style=" position: absolute; top: 0; right: 0; left: 0; bottom: 0; z-index: 9;"></div>
              <EmployeeSelector
                :multi="false"
                :user_employee_list="true"
                :isChecKedAll="false"
                :is_filtration_creator="false"
                :employee_list="superiorList"
                :selected="item.approval_selected"
                :visible.sync="item.show_approval_selector"
                @confirm="approval_confirm"
              />
            </el-form-item>
          </div>
        </el-form>
        <div class="flex-box-end">
          <el-button @click="closeDialog('dialogData')" :disabled="btn_loading">取 消</el-button>
          <el-button type="primary" @click="subData('dialogData')" :disabled="btn_loading">确 认</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" :title="'提交结果'" :visible.sync="error_list_show" :append-to-body="true" width="600px">
      <el-table :data="error_list">
        <el-table-column prop="target" label="员工"></el-table-column>
        <el-table-column prop="point" label="积分"></el-table-column>
        <el-table-column prop="msg" 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>
    </el-dialog>

    <SelectRule
      :visible.sync="isShowRule"
      :ptId="0"
      :selectItems="selectItem"
      :is-scope="true"
      @confirm="ruleConfirm"
    />

    <el-dialog title="提交结果" :visible.sync="isResult"  width="1000" :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-3" 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-3 content" style="border-right: 1px solid #f1f1f1;">
              <el-tooltip class="item" effect="dark" :content="item.task.msg.remark" placement="bottom">
                <div class="content">{{ item.task.msg.remark }}</div>
              </el-tooltip>
            </div>
    				<div class="flex-2" v-if="item.status == 1">
    					<span class="green">{{ 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>
  </div>
</template>

<script>
import moment from 'moment';
import EmployeeSelector from '@/components/EmployeeSelector';
import uploadOss from '@/components/upload';
import SelectRule from '@/components/SelectRule';
import {specialFilter} from "../../../utils";

export default {
  name: 'applicationIntegration',
  // 数据
  model: {
    prop: 'list',
    event: 'value'
  },
  props: {
    title: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    },
    integralType: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      pickerBeginDateBefore: {
        disabledDate(time) {
           // 获取60天前得日期
           var date = new Date()
           var lastDate = new Date(date - 1000 * 60 * 60 * 24 * 60)// 最后60天可以更改，意义：是获取多少天前的时间
           var lastY = lastDate.getFullYear()
           var lastM = lastDate.getMonth()
           var lastD = lastDate.getDate()
           let oneYear = new Date(lastY, (lastM < 10 ? '0' + lastM : lastM), (lastD < 10 ? '0' + lastD : lastD))
           return time.getTime() > Date.now() || time.getTime() < oneYear;
        }
      },
      error_list: [], //错误信息数组
      error_list_show: false, //错误信息弹窗
      loading: false,
      isShowRule: false,
      selectItem: [],
      dialogData: {
        items: [],
        rule_switch: true,
      },
      item:{
            rule_id: '',
            item_id: '',
            remark: '',
            ruleData:{},
            event_time: moment().format('YYYY-MM-DD'),

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

            // 附件
            fileList: [],
            files: [],
      },
      // 录入对象
      employee_id: '',
      employeeName: '',
      employee_list: [],
      superiorList: [],//当前录入对象上级
      employee_selected: { dept: [], employee: [] },
      show_employee_selector: false,

      // 规则分类
      user_info: this.$store.getters.user_info,
      btn_loading: false,
      itemIndex:0,

      change_reviewer:Number(this.$store.getters.user_info.site_config.change_reviewer)==1? true:false,//是否允许员工修改审批人
      isCreator:this.$supremeAuthority('creator'),

      // 长连接结果
      results: [], //提交的返回结果集合
      isResult: false,
      percentage: 0,
      resultList:[],//要发送数据的集合
      resultIndex:0,
      isShowError:false,
      isShowError2:false,
      errorMsg:'服务器繁忙，请稍后再试',
      breakList:[],
      config:{},
      specified_rule_item:this.$userInfo().site_config.specified_rule_item? true:false,//奖扣时是否必选规则
    };
  },
  components: { EmployeeSelector, uploadOss,SelectRule },
  watch:{
    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();
    	}
    },
  },
  methods: {
    //判断是否已经存在
    isItemId(id){
      let item='';
      this.dialogData.items.some((x)=> {
          if(x.item_id==id){
            item=x
            return true;
          }
      });
      return item
    },
    //选择规则
    ruleConfirm(rules) {
      if (rules.length > 0) {
        let items = []
        rules.forEach(e => {
          if(this.isItemId(e.id)){
            items.push(this.isItemId(e.id))
          }else{
            let item = JSON.parse(JSON.stringify(this.item));
            item.remark = specialFilter(e.remark);
            item.rule_id = e.rule_id;
            item.item_id = e.id;
            item.ruleData= e;
            items.push(item);
          }
        });
        this.dialogData.items = items;
      } else {
        this.dialogData.items = [];
      }
      this.selectItem = rules;
    },
    setIndex(index){
      if(index==this.itemIndex){
        return false
      }
      this.itemIndex = index;
    },
    openDialog(){
      // 初始化录入对象
      this.employee_selected.employee = [{ id: this.user_info.id, img_url: this.user_info.img_url, name: this.user_info.name }];
      this.employee_id = this.user_info.id;
      this.employeeName = this.user_info.name;
      this.initializesReviewer(this.user_info.id);
    },
    // 附件上传
    beforeUpload(file) {
      const isJPG = /^image\/(jpeg|png|jpg)$/.test(file.type);
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG,PNG,JPEG 格式!');
      }
      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);
      });
    },
    delItem(id,index) {
      this.$confirm('你确定要删除奖扣明细' + parseInt(index + 1) + '吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          this.dialogData.items.splice(index, 1);
          this.selectItem.some((e,index2)=>{
            if(id==e.id){
              this.selectItem.splice(index2, 1);
              return true;
            }
          })
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
     .catch(() => {});
    },
    closeDialog(formName) {
      this.$refs[formName].resetFields();
      this.closePopup();
    },
    subData(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.save();
        }
      });
    },
    // 提交数据
    save() {
      let self = this;
      let data = [];
      let isError=false;
      let str='';
      self.dialogData.items.some((element,index) => {
        data.push({
          rule_id: element.rule_id || 0,
          employee_id: this.employee_id || 0,
          item_id: element.item_id || 0,
          remark: element.remark,
          event_time: element.event_time,
          pt_id: element.ruleData.pt_id,
          reviewer_id: element.reviewer_id || 0,
          files: element.files,
          type:'point_apply'
        });
        if(!element.reviewer_id){
          isError=true;
          str="第"+(index+1)+'条申请，审批人不能为空'
        }
      });
      if(!this.employee_id){
          this.$message.error('请选择录入对象');
         return false;
      }
      if(!data[0]){
        this.$message.error('请选择规则');
        return false;
      }
      if(isError){
        this.$message.error(str);
         return false;
      }
      // if(data[0]&&data[0].item_id){
      this.webSocket(data);
      return false;
      // }
      this.btn_loading = true;
      let obj={items:data}
      this.$axiosUser('post', '/api/pro/integral/review/apply', obj, 'v2').then(res => {
        if (res.data.code == 1) {
          self.$refs['dialogData'].resetFields();
          self.$message.success(res.data.msg);
          this.error_list = res.data.data.list;
          this.error_list_show = true;
          this.closePopup();
        } else {
          self.$message.error(res.data.msg);
        }
        self.btn_loading = 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=='break'){
    		let wsData=this.resultList;
    		this.errorMsg=e.msg
    		let data={
    			type:this.ptId,
    			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;
    	}
    },
    // 当switch 改变了
    switchChange(is) {
      this.selectItem=[];
      if(is){
        this.dialogData.items=[];
      }else{
        this.dialogData.items=[JSON.parse(JSON.stringify(this.item))];
      }
    },
    // 初始化审核人
    initializesReviewer(id) {
      var superiorList=this.$getEmployeeMapItem(id).employee_detail.superior_list;//选择录入对象的上级集合
      this.superiorList=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.approvalName = users[0].name;
           obj.approval_selected.employee = [{ name:users[0].name, id:users[0].id, img_url: users[0].img_url }];
           obj.reviewer_id = users[0].id;
         }else{
           obj.approvalName = list[0].name;
           obj.approval_selected.employee = [{ name:list[0].name, id:list[0].id, img_url:'' }];
           obj.reviewer_id = list[0].id;
         }
         this.dialogData.items.forEach(item=>{
           if(users.length>0){
             item.approvalName = users[0].name;
             item.approval_selected.employee = [{ name:users[0].name, id:users[0].id, img_url: users[0].img_url }];
             item.reviewer_id = users[0].id;
           }else{
             item.approvalName = list[0].name;
             item.approval_selected.employee = [{ name:list[0].name, id:list[0].id, img_url:'' }];
             item.reviewer_id = list[0].id;
           }
         })

      });
    },
    // 选择审核人
    approval_confirm(data) {
      const item = this.dialogData.items[this.itemIndex];
      item.approvalName = '';
      item.approval_selected.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;
      }
    },
    // 选择对象
    employee_confirm(data) {
      if (data.employee !== null && data.employee.length != 0) {
        let user=data.employee[0];
        this.employeeName = user.name;
        this.employee_selected.employee = [{ name: user.name, id: user.id, img_url: user.img_url }];
        this.employee_id = user.id;
        this.initializesReviewer(user.id);
      }else{
        this.employeeName = '';
        this.employee_selected.employee = [];
        this.employee_id = '';
      }
    },
    // 关闭弹窗
    closePopup() {
      //关闭重置窗口状态
      this.itemIndex=0;
      this.$nextTick(()=>{
        this.selectItem=[];
        this.dialogData={
          items: [],
          rule_switch: true,
        };
        this.item={
              rule_id: '',
              item_id: '',
              remark: '',
              ruleData:{},
              event_time: moment().format('YYYY-MM-DD'),

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

              // 附件
              fileList: [],
              files: [],
        };
      })
      this.$emit('update:visible', false);
    },
    onRemarkInput(item){
      item.remark = specialFilter(item.remark)
    }
  }
};
</script>
<style lang="scss" scoped="scoped">
  .tips {
    background: #606266;
    border-radius: 50%;
    width: 14px;
    height: 14px;
    color: #fff;
    display: inline-block;
    font-size: 12px;
    line-height: 14px;
    text-align: center;
  }
  .title{
    background-color: #F4F9FD;
    border: 1px solid #E4F0FC;
    padding-right: 10px;
  }
  .content {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
    padding: 0 10px !important;
    line-height: 1.5rem;
  }
  .results {
  	border-bottom: 1px solid #f1f1f1;
  	text-align: center;
  }
  .results div {
  	padding: 10px;
  }
.w250{
  width: 400px;
}
.inputBox {
  height: 36px;
  line-height: 36px;
  padding-right: 30px;
  -webkit-appearance: none;
  background-color: #fff;
  background-image: none;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  color: #606266;
  display: inline-block;
  font-size: inherit;
  width: 400px;
  outline: 0;
  padding: 0 15px;
  cursor: pointer;
  -webkit-transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}
.form {
  /deep/ .el-form-item {
    margin-bottom: 15px;
  }
}
/deep/ .el-dialog__body {
    padding:20px;
    color: #606266;
    font-size: 14px;
    word-break: break-all;
}
.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;
  }
}
/deep/ .el-dialog__body {
  padding: 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}
/deep/ .el-input__count{
  right: 70px;
  bottom: -26px;
}
</style>
