<template>
  <div>
    <!-- 积分申请 -->
    <el-dialog :title="title" :modal-append-to-body="false" :visible.sync="visible" :close-on-click-modal="false" :before-close="closePopup" 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="itemIndex = index">
            <div style="overflow: hidden;">
              <span style="line-height: 36px;">申请明细({{index+1}})</span>
              <el-button type="text" class="fr" v-show="index > 0 || dialogData.items.length > 1" @click="delItem(index)">删除</el-button>
            </div>
            <el-form-item label="录入对象" :prop="'items.'+ index +'.employeeInfo.name'" :rules="[{ required: true, message: '请选择录入对象', trigger: 'change' }]">
              <div class="zindexName" @click="selectEmployee(index)">
                <WWOpenData type="userName" v-if="item.employeeInfo.id" :openid="item.employeeInfo.name"></WWOpenData></span>
                <span style="color: #DCDFE6;" v-else>请选择录入对象</span>
              </div>
            </el-form-item>

            <el-form-item label="指定规则">
              <el-switch
                v-model="item.rule_switch"
                @change="switchChange(index,item.rule_switch)"
                active-color="#13ce66">
              </el-switch>
            </el-form-item>

            <el-form-item label="选择规则" v-show="item.rule_switch" :prop="'items.'+ index +'.rule_item_list_value'" :rules="[item.rule_switch?{ required: true, message: '请选择规则', trigger: 'blur' }:{}]">
              <el-cascader
              v-model="item.rule_item_list_value"
              ref="ruleItem"
              :popper-class="'itemClass'"
              :options="rule_item_list"
              @change="ruleItemChange"
              @visible-change="visibleChange($event,index)"
              :show-all-levels="false"
              :props="{ children: 'child', label: 'name', value: 'id'}"
              ></el-cascader>
            </el-form-item>
            <el-form-item v-if="item.rule_switch && item.rule_id">
              <div v-show="item.rule_item_details.range_type == 1">{{get_point_name(item.rule_item_details.pt_id)}}  {{item.rule_item_details.min_point}}</div>
              <div v-show="item.rule_item_details.range_type == 2">{{get_point_name(item.rule_item_details.pt_id)}}  {{item.rule_item_details.min_point}} ~ {{item.rule_item_details.max_point}}</div>
              <div>{{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="6" placeholder="请输入事件内容（限300字）" 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"
                :multiple="true"
              >
                <el-button size="small" type="primary" >点击上传</el-button>(最多选择3张)
              </uploadOss>
            </el-form-item>
            <el-form-item label="审批人" :prop="'items.'+ index +'.reviewerInfo.name'" :rules="[{ required: true, message: '请选择审批人', trigger: 'blur' }]">
              <div class="zindexName" @click="selectReviewer(index)">
                <WWOpenData type="userName" v-if="item.reviewerInfo.id" :openid="item.reviewerInfo.name"></WWOpenData></span>
                <span style="color: #DCDFE6;" v-else>请选择审批人</span>
              </div>
            </el-form-item>

          </div>
          <el-form-item style="margin-bottom: 0;">
            <div>如需录入多条，请点击“增加一条”</div>
          </el-form-item>
          <el-form-item style="margin-bottom: 0;">
            <el-button type="primary" plain @click="addItem">+ 增加一条</el-button>
          </el-form-item>
          <el-form-item style="text-align: right; margin-bottom: 0;">
            <el-button  @click="closeDialog('dialogData')">取 消</el-button>
            <el-button :disabled="btn_loading" type="primary" @click="subData('dialogData')">确 认</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>

    <!-- 录入对象 -->
    <EmployeeSelector
      :isChecKedAll="false"
      :multi="false"
      isRequired
      :selected="employee_selected"
      :visible.sync="isShowEmployee"
      @confirm="employee_confirm"
    />

    <!-- 审批人 -->
    <EmployeeSelector
      :multi="false"
      :isChecKedAll="false"
      :is_filtration_creator="false"
      :user_employee_list="true"
      isRequired
      :employee_list="approval_employee_list"
      :selected="approval_selected"
      :visible.sync="isShowApproval"
      @confirm="approval_confirm"
    />

    <el-dialog
      :title="'提交结果'"
      :visible.sync="error_list_show"
      :append-to-body='true'
      :modal-append-to-body="false"
      width="700px">
      <el-table :data="error_list">
        <el-table-column prop="target" label="员工">
          <template slot-scope="scope">
            <WWOpenData type="userName" :openid="scope.row.target"></WWOpenData>
          </template>
        </el-table-column>
        <el-table-column prop="point" 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="msg" label="备注信息"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
  import moment from 'moment'
  import EmployeeSelector from '@/views/common/EmployeeSelector'
  import uploadOss from "@/views/upload_oss/upload"
  import { getToken } from '@/utils/auth'

  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) {
            return time.getTime() > Date.now();
          }
        },
        error_list:[],//错误信息数组
        error_list_show:false,//错误信息弹窗
        Xtoken: { 'X-Token': getToken() },
        loading: false,
        dialogData:{
          items: [{
            rule_switch: true,
            rule_id: '',
            item_id: '',
            remark: '',
            event_time: moment().format('YYYY-MM-DD'),
            approval_employee_list:[],
            employeeInfo:{},// 录入对象
            reviewerInfo:{},// 审批人信息
            // 附件
            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: this.$store.getters.user_info,
        point_types: JSON.parse(localStorage.getItem('SET_POINT_TYPES')),
        btn_loading: false,
        itemIndex:0,
        user_list: [],

        // 审批人
        approval_employee_list:[],
        approval_selected:{dept: [],employee:[]},
        isShowApproval:false,

        // 录入对象
        employee_selected:{dept: [],employee:[]},
        isShowEmployee:false,
      }
    },
    components: {EmployeeSelector,uploadOss},
    watch:{
      visible(val){
        if(val){
          // 初始化录入对象
          this.dialogData.items[0].employeeInfo = this.user_info;
          this.getUserInfo(this.user_info.id,(res)=>{
             this.initializesReviewer(res.employee_detail.superior_list,this.itemIndex) //设置上级列表
             this.dialogData.items[0].reviewerInfo={};
             let superior_id= res.employee_detail.superior_id //选中对象的直属上级id
             res.employee_detail.superior_list.forEach(e=>{
               if(e.id==superior_id){
                 this.dialogData.items[0].reviewerInfo=e;
               }
             })
          })
        }
      },
    },
    mounted() {
      this.getRuleItemData()
    },
    methods: {

      // 选择录入对象
      selectEmployee(index){
        const item = this.dialogData.items[index];
        if(item.employeeInfo.id){
          this.employee_selected.employee=[item.employeeInfo]
        }
        this.isShowEmployee=true;
      },
      // 选择审批人
      selectReviewer(index){
        const item = this.dialogData.items[index];
        if(!item.employeeInfo.id){
          this.$message.error("请先选择录入对象")
          return false
        }
        this.approval_employee_list=item.approval_employee_list;
        if(item.reviewerInfo.id){
          this.approval_selected.employee=[item.reviewerInfo]
        }
        this.isShowApproval=true;
      },

      // 提交数据
      save(){
        let reviewer_infoid = false
        let data = {items: []}
        this.dialogData.items.forEach(element => {
          let obj={
            rule_id: element.rule_id || 0,
            employee_id: element.employeeInfo.id || 0 ,
            item_id: element.item_id || 0,
            remark: element.remark,
            event_time: element.event_time,
            pt_id: element.pt_id,
            reviewer_id: element.reviewerInfo.id || 0,
            files: element.files
          }
          data.items.push(obj)
          if(element.reviewerInfo.id == this.user_info.id) reviewer_infoid = true
        });
        if(reviewer_infoid){
          this.btn_loading = false
          this.$message.warning('不能提交给自己审批，请直接对员工进行【积分奖扣】或更换审批人')
          return
        }
        this.$http('post','/api/integral/review/apply',data,'v2').then(res => {
            this.$refs['dialogData'].resetFields();
            this.$message.success(res.data.msg)
            this.error_list = res.data.data.list
            this.error_list_show = true
            this.dialogData.items[0].employee_id = this.user_info.id
            this.closePopup()
        }).finally(()=>{
          this.btn_loading = false
        })
      },
      // 选择审核人
      approval_confirm(data){
        const item = this.dialogData.items[this.itemIndex]
        if(data.employee.length>0){
          item.reviewerInfo = data.employee[0]
        }else{
          item.reviewerInfo={};
        }
      },
      // 选择对象
      employee_confirm(data){
        const item = this.dialogData.items[this.itemIndex]; //对应申请
        let employee=data.employee[0];
        if(employee){
          item.employeeInfo=employee;
          this.getUserInfo(employee.id,(res)=>{
             this.initializesReviewer(res.employee_detail.superior_list,this.itemIndex) //设置上级列表
             item.reviewerInfo={};
             let superior_id= res.employee_detail.superior_id //选中对象的直属上级id
             res.employee_detail.superior_list.forEach(e=>{
               if(e.id==superior_id){
                 item.reviewerInfo=e;
               }
             })
          })
        }
      },
      //获取缓存起来的审批人
      getUserInfo(id,func) {
      		this.$http('get', '/api/employee/info', {id: id }).then(res =>{
            func(res.data.data)
          })
      },
      // 获取积分名称
      get_point_name(id){
        let name = ''
        this.point_types.forEach(element => {
          if (element.id == id) {
            name = element.name
          }
        });
        return name
      },
      // 初始化审核人列表
      initializesReviewer(list,index){
        const superior = list || this.user_info.employee_detail.superior_list
        const num = index || 0
        const item = this.dialogData.items[num]
        item.approval_employee_list = [...superior]
      },
      // 当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.rule_item_details = {range_type: ''}
        }else{
          item.rule_id = ""
          item.rule_list_value = ""
        }
      },
      // 获取规则信息
      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.$http('get','/api/integral/rule/trees',data).then(res => {
          const resultData = res.data.data
          this.rule_list = this.getTreeData(resultData.rule_tree)
      	})
      },
      // 获取规则细则
      getRuleItemData(){
        let data = {cycle_type: '1'}
        this.loading = true
        this.$http('get','/api/integral/rule/trees',data,'v2').then(res => {
            const resultData = res.data.data
            this.rule_item_list = resultData.tree
        }).finally(()=>{
          this.loading = false
        })
      },
      visibleChange(val,index){
        if(val){
          this.itemIndex=index
        }
      },
      // 规则细则变化关闭down
      ruleItemChange(value){
        let item = this.dialogData.items[this.itemIndex]
        let ruleItemDetail = null
        ruleItemDetail = this.$refs["ruleItem"][this.itemIndex].getCheckedNodes()[0].data
        if(ruleItemDetail){
          item.rule_item_details = ruleItemDetail
          item.remark = ruleItemDetail.name
          item.rule_id = ruleItemDetail.pid
          item.item_id = value[value.length - 1]
        }
        this.$refs.ruleItem.dropDownVisible = false;
      },
      // 规则分类变化关闭dewn
      ruleChange(value){
        this.dialogData.items[this.itemIndex].rule_id = value[value.length - 1]
        this.$refs.rule.dropDownVisible = false;
      },
      // 递归判断列表，把最后的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;
      },
      // 附件上传
      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) {
        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)
        });
      },

      // 加一条
      addItem(){
        this.dialogData.items.push({
          rule_switch: true,
          rule_id: '',
          item_id: '',
          remark: '',
          event_time: moment().format('YYYY-MM-DD'),
          employeeInfo:{},// 录入对象
          reviewerInfo:{},// 审批人信息
          approval_employee_list:[],
          // 附件
          fileList: [],
          files: [],
          // 规则分类 与 规则细则 名称
          rule_list_value: null,
          rule_item_list_value: null,
          rule_item_details: {range_type: ''}
        })
      },
      // 删除一条
      delItem(index){
        this.$confirm('确认删除该条奖扣?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.formData.items.splice(index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })

      },
      closeDialog(formName){
        this.$refs[formName].resetFields();
        this.closePopup()
      },
      delItem(index){
        this.$confirm('你确定要删除奖扣明细'+parseInt(index+1)+'吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.dialogData.items.splice(index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {});
      },
      subData(formName){
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.btn_loading = true
            this.save()
          }
        });
      },
      // 关闭弹窗
      closePopup(){
        //关闭重置窗口状态
        this.dialogData.items = [{
            rule_switch: true,
            rule_id: '',
            item_id: '',
            remark: '',
            event_time: moment().format('YYYY-MM-DD'),
            employeeInfo:{},// 录入对象
            reviewerInfo:{},// 审批人信息
            approval_employee_list:[],
            // 附件
            fileList: [],
            files: [],
            // 规则分类 与 规则细则 名称
            rule_list_value: null,
            rule_item_list_value: null,
            rule_item_details: {range_type: ''}
          }]
          this.initializesReviewer(this.user_info.employee_detail.superior_list,0,true)
          this.$emit('update:visible', 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;
    }
  }

  .zindexName{
     position: absolute;
     top: 0;
     right: 0;
     left: 0;
     bottom: 0;
     z-index: 9;
     border:1px solid rgb(224, 224, 224);
     width:360px;
     border-radius:3px;
     padding-left:15px;
     overflow: hidden;
     cursor: pointer;
  }
</style>
