<template>
  <div class="approvalset-wrap">
    <div class="left-wrap">
      <div class="item" :class="typeName==='客户审批'?'active':null" @click="handleChangeType('客户审批')">客户审批</div>
      <div class="item" :class="typeName==='合同审批'?'active':null" @click="handleChangeType('合同审批')">合同审批</div>
      <div class="item" :class="typeName==='用印审批'?'active':null" @click="handleChangeType('用印审批')">用印审批</div>
    </div>
    <div class="content-wrap">
      <div class="top-type">
        <span class="item" :class="topTypeActive===item.id?'active':null" v-for="item in topTypeArr" :key="item.id" @click="handleTopTypeChange(item.id)">{{item.name}}</span>
      </div>
      
      <div class="step-wrap">
        <div>
          <div class="step-item-box" v-for="(step,stepIndex) in processList" :key="step.name">
            <div class="step-line">
              <h2>{{step.name}}</h2>
            </div>
            <div class="step-content">
              <!-- 审批人 -->
              <div>
                <block v-for="(auser,index) in step.approvalUser" :key="auser.user_type">
                  <block v-if="auser.user_type==='user'">
                    <span class="user-box" v-for="(item,index2) in auser.user" :key="item.AdminId">
                      {{item.userName}}
                      <img class="delete-icon" src="../../assets/img/icons/delete-icon.png" alt="" @click="handleDelete({type:'approve',userType:'user',stepIndex,index,index2})">
                    </span>
                  </block>
                  <block v-if="auser.user_type==='role'">
                    <!-- <span class="user-box" style="margin-right:0"> -->
                    <span class="user-box">
                      {{auser.user[0].RoleName}}：
                      <span v-for="(item,itemindex) in auser.user" :key="item.AdminId">{{item.userName}}<span v-if="itemindex<auser.user.length-1">、</span></span>
                      <img class="delete-icon" src="../../assets/img/icons/delete-icon.png" alt="" @click="handleDelete({type:'approve',userType:'role',stepIndex,index})">
                    </span>
                    <!-- ：<span class="user-name" v-for="item in auser.user" :key="item.AdminId">{{item.userName}}</span> -->
                  </block>
                </block>
                <span class="add-btn" @click="handleShowAdd('approve',stepIndex)">+添加用户</span>
              </div>
              <!-- 抄送人 -->
              <div style="margin-top:24px">
                <block v-for="(cuser,index) in step.copyUser" :key="cuser.user_type">
                  <block v-if="cuser.user_type==='user'">
                    <span class="user-box" v-for="(item,index2) in cuser.user" :key="item.AdminId">
                      {{item.userName}}
                      <img class="delete-icon" src="../../assets/img/icons/delete-icon.png" alt="" @click="handleDelete({type:'copy',userType:'user',stepIndex,index,index2})">
                    </span>
                  </block>
                  <block v-if="cuser.user_type==='role'">
                    <!-- <span class="user-box" style="margin-right:0"> -->
                    <span class="user-box">
                      {{cuser.user[0].RoleName}}：
                      <span v-for="(item,itemindex) in cuser.user" :key="item.AdminId">{{item.userName}}<span v-if="itemindex<cuser.user.length-1">、</span></span>
                      <img class="delete-icon" src="../../assets/img/icons/delete-icon.png" alt="" @click="handleDelete({type:'copy',userType:'role',stepIndex,index})">
                    </span>
                    <!-- ：<span class="user-name" v-for="item in cuser.user" :key="item.AdminId">{{item.userName}}</span> -->
                  </block>
                </block>

                <span class="add-btn" @click="handleShowAdd('copy',stepIndex)">+添加抄送人</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="bts-box">
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button type="primary" plain @click="handleCancelSave">取消</el-button>
      </div>
    </div>

    <!-- 添加审批人/抄送人 弹窗 -->
    <el-dialog width="560px" :visible.sync="show" :modal-append-to-body="false" @close="show=false">
      <div slot="title">
        <img width="15" src="../../assets/img/icons/add_icon.png" alt="" style="position:relative;top:2px;margin-right:10px">
        <span>{{addType==='approve'?'添加审批人':'添加抄送人'}}</span>
      </div>
      <div class="add-wrap">
        <el-autocomplete 
          class="search-box"
          v-model="searchVal"
          :fetch-suggestions="searchList"
          placeholder="搜索用户名称"
          @select="handleSelect"
        ></el-autocomplete>

        <div style="text-align:center;margin:70px 0 30px 0">
          <el-button type="primary" @click="handleConfirmUser">确定</el-button>
          <el-button type="primary" plain @click="show=false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {departInterence} from '@/api/api.js'
const config={
  '客户审批':[{id:1,name:'FICC部门'},{id:2,name:'权益部门'}],
  '合同审批':[{id:3,name:'FICC部门'},{id:4,name:'权益部门'}],
  '用印审批':[{id:5,name:'合同章/电子合同章'},{id:6,name:'公章/法人章'}]
}
export default {
  data () {
    return {
      typeName:"客户审批",

      topTypeArr:config['客户审批'],
      topTypeActive:config['客户审批'][0].id,

      processList:[
        {name:"一级审批",approvalUser:[],copyUser:[]},
        {name:'二级审批',approvalUser:[],copyUser:[]},
        {name:'三级审批',approvalUser:[],copyUser:[]}
      ],//此处写死三级 目前需求固定页面展示三级 允许只配置一个节点

      show:false,
      searchVal:'',
      addType:'',//添加人类型 approve 审批 copy 抄送
      temUser:null,
      stepIndex:null,
    }
  },
  created () {
    this.getApprovalDetail()
  },
  methods: {
    handleCancelSave(){
      this.getApprovalDetail()
    },

    // 保存配置
    async handleSave(){
      let temarr=[]
      let copyArr=JSON.parse(JSON.stringify(this.processList))
      copyArr.forEach(item=>{
        
        if(item.approvalUser.length>0){
          let obj={
            NodeType:'check',
            User:[]
          }
          let arr=[]
          arr=item.approvalUser.filter(item=> item.user.length>0)
          obj.User=arr.map(item2=>{
            item2.user=item2.user.map(item3=>{
              return item3.AdminId
            })
            return {
              user_type:item2.user_type,
              user:[...new Set(item2.user)].join(',')
            }
          })
          if(obj.User.length>0){
            temarr.push(obj)
          }

        }

        if(item.copyUser.length>0){
          let obj={
            NodeType:'cc',
            User:[]
          }
          let arr=[]
          arr=item.copyUser.filter(item=> item.user.length>0)
          obj.User=arr.map(item2=>{
            item2.user=item2.user.map(item3=>{
              return item3.AdminId
            })
            return {
              user_type:item2.user_type,
              user:[...new Set(item2.user)].join(',')
            }
          })
          if(obj.User.length>0){
            temarr.push(obj)
          }
        }
        
      })
      const res=await departInterence.approvalFlowSave({
        FlowId:Number(this.topTypeActive),
        NodeList:temarr
      })
      if(res.Ret===200){
        this.$message.success('保存成功')
        this.getApprovalDetail()
      }
    },

    /**
     * 删除用户/组织
     * type:类型 approve审批人 copy抄送人
     * userType:用户类型 role组织 user个人
     * stepIndex:当前是操作第几级审批的序号
     * index:最外层序号
     * index2:内部删除指定用户序号
     */
    handleDelete({type,userType,stepIndex,index,index2}){
      // 删除审批人
      if(type==='approve'){
        if(userType==='role'){
          this.processList[stepIndex].approvalUser.splice(index,1)
        }
        if(userType==='user'){
          this.processList[stepIndex].approvalUser[index].user.splice(index2,1)
        }
      }

      // 删除抄送人
      if(type==='copy'){
        if(userType==='role'){
          this.processList[stepIndex].copyUser.splice(index,1)
        }
        if(userType==='user'){
          this.processList[stepIndex].copyUser[index].user.splice(index2,1)
        }
      }
    },

    // 切换左侧类型
    handleChangeType(e){
      this.typeName=e
      this.topTypeArr=config[e]
      this.handleTopTypeChange(config[e][0].id)
    },

    //显示添加弹窗
    handleShowAdd(e,index){
      this.addType=e
      this.searchVal=''
      this.stepIndex=index
      this.temUser=null
      this.show=true
    },

    //切换顶部类型
    handleTopTypeChange(e){
      this.topTypeActive=e
      this.getApprovalDetail()
    },

    //搜索用户
    async searchList(queryVal,cb){
      cb([])
      if(!queryVal) return
      const res=await departInterence.approvalUserSearch({Keyword:queryVal})
      if(res.Ret===200){
        let arr1=[],arr2=[]
        if(res.Data.AdminList){
          arr1=res.Data.AdminList.map(item=>{
            return {
              value:item.RealName,
              AdminId:item.AdminId,
              RoleName:item.RoleName,
              type:'user'
            }
          })
        }
        if(res.Data.RoleList){
          arr2=res.Data.RoleList.map(item=>{
            return {
              value:item.RoleName,
              AdminId:item.RoleId,
              RoleName:item.RoleType,
              type:'role'
            }
          })
        }
        cb([...arr1,...arr2])
      }
      
    },

    handleConfirmUser(){
      // 判断是否存在该用户
      if(!this.temUser||!this.temUser.AdminId||!this.searchVal){
        let str='请添加审批人'
        if(this.addType==='copy'){
          str='请添加抄送人'
        }
        this.$message.warning(str)
        return
      }
      let temarr=[]
      if(this.addType==='approve'){
        this.processList[this.stepIndex].approvalUser.forEach(item=>{
          temarr.push(...item.user)
        })
      }else{
        this.processList[this.stepIndex].copyUser.forEach(item=>{
          temarr.push(...item.user)
        })
      }
      let flag=temarr.some(item=>item.AdminId==this.temUser.AdminId)
      if(flag){
        this.$message.warning('该用户已存在')
        return
      }

      // 添加到审批节点
      if(this.addType==='approve'){
        if(this.temUser.type==='user'){
          let tagindex=-1
          this.processList[this.stepIndex].approvalUser.forEach((item,index)=>{
            if(item.user_type==='user'){
              tagindex=index
            }
          })
          if(tagindex>-1){
            this.processList[this.stepIndex].approvalUser[tagindex].user.push({
              AdminId:this.temUser.AdminId,
              RoleName:this.temUser.RoleName,
              userName:this.temUser.value
            })
          }else{
            this.processList[this.stepIndex].approvalUser.push({
              user:[{
                AdminId:this.temUser.AdminId,
                RoleName:this.temUser.RoleName,
                userName:this.temUser.value
              }],
              user_type:"user"
            })
          }
        }else{
          let tag=false
          this.processList[this.stepIndex].approvalUser.forEach(item=>{
            if(item.user_type==='role'&&item.user[0].AdminId==this.temUser.AdminId){
              tag=true
            }
          })
          if(tag){
            this.$message.warning('该组织已存在')
            return
          }
          this.processList[this.stepIndex].approvalUser.push({
            user:this.temUser.value,
            user_type:"role"
          })
        }
      }else{
        if(this.temUser.type==='user'){
          let tagindex=-1
          this.processList[this.stepIndex].copyUser.forEach((item,index)=>{
            if(item.user_type==='user'){
              tagindex=index
            }
          })
          if(tagindex>-1){
            this.processList[this.stepIndex].copyUser[tagindex].user.push({
              AdminId:this.temUser.AdminId,
              RoleName:this.temUser.RoleName,
              userName:this.temUser.value
            })
          }else{
            this.processList[this.stepIndex].copyUser.push({
              user:[{
                AdminId:this.temUser.AdminId,
                RoleName:this.temUser.RoleName,
                userName:this.temUser.value
              }],
              user_type:"user"
            })
          }
        }else{
          let tag=false
          this.processList[this.stepIndex].copyUser.forEach(item=>{
            if(item.user_type==='role'&&item.user[0].AdminId==this.temUser.AdminId){
              tag=true
            }
          })
          if(tag){
            this.$message.warning('该组织已存在')
            return
          }
          this.processList[this.stepIndex].copyUser.push({
            user:this.temUser.value,
            user_type:"role"
          })
        }
      }


      this.show=false
      
    },

    //选择搜索到的用户
    async handleSelect(e){
      if(e.type==='user'){
        this.temUser=e
      }else{
        const res=await departInterence.getUserList({RoleId:e.AdminId,PageSize:1000})
        if(res.Ret===200){
          let arr=res.Data.List&&res.Data.List.map(item=>{
            return {
              AdminId:e.AdminId,
              RoleName:e.RoleName,
              userName:item.RealName
            }
          })
          this.temUser={
            value:arr,
            AdminId:e.AdminId,
            RoleName:e.RoleName,
            type:'role'
          }
        }
      }
    },

    // 流程详情
    async getApprovalDetail(){
      this.processList=[
        {name:"一级审批",approvalUser:[],copyUser:[]},
        {name:'二级审批',approvalUser:[],copyUser:[]},
        {name:'三级审批',approvalUser:[],copyUser:[]}
      ]
      const res=await departInterence.approvalFlowDetail({FlowId :this.topTypeActive})
      if(res.Ret===200){
        let tag=-1
        let obj={name:'',approvalUser:[],copyUser:[]}

        res.Data.NodeList.forEach(item=>{
          item.User.forEach(item2=>{
            let userarr=item2.user.split(',')
            let temarr=[]
            userarr.forEach(item3=>{
              item.UserList.forEach(item4=>{
                if(item2.user_type==='role'){
                  if(item4.RoleId==item3){
                    temarr=[...temarr,{AdminId:item3,userName:item4.Name,RoleName:item4.RoleName}]
                  }
                }else{
                  if(item4.AdminId==item3){
                    temarr=[...temarr,{AdminId:item3,userName:item4.Name,RoleName:item4.RoleName}]
                  }
                }
              })
            })
            item2.user=temarr
          })

          if(item.NodeType==='check'){
            tag++
            obj={name:`${tag}级审批`,approvalUser:[],copyUser:[]}
            obj.approvalUser=[...obj.approvalUser,...item.User]
          }else{
            obj.copyUser=[...obj.copyUser,...item.User]
          }

          // arr[tag]=obj
          this.processList[tag].approvalUser=obj.approvalUser
          this.processList[tag].copyUser=obj.copyUser
        })
        
      }
    }
  }
}
</script>

<style lang="scss">
.add-wrap{
  .el-input{
    width: 100%;
  }
}
</style>

<style lang="scss" scoped>
div{
  box-sizing: border-box;
}
.approvalset-wrap{
    display: flex;
}
.left-wrap{
    width: 210px;
    background: #fff;
    // border: 1px solid #ececec;
    border-radius: 4px;
    // box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
    padding: 30px 0 30px 30px;
    margin-right: 20px;
    .item{
      line-height: 53px;
      color: #409EFF;
      font-size: 14px;
      padding-left: 48px;
      font-weight: bold;
      cursor: pointer;
    }
    .active{
      background-color: #409EFF;
      border-radius: 27px 0px 0px 27px;
      color: #fff;
      position: relative;
      &::before{
        content: '';
        display: block;
        width: 10px;
        height: 10px;
        border-radius: 50%;
        position: absolute;
        left: 20px;
        top: 50%;
        transform: translateY(-50%);
        background-color: #fff;
      }
    }
}

.content-wrap{
  flex: 1;
  .top-type{
    .item{
      display: inline-block;
      font-size: 16px;
      font-weight: bold;
      width: 216px;
      text-align: center;
      line-height: 60px;
      cursor: pointer;
    }
    .active{
      color: #409EFF;
      background-color: #fff;
    }
  }
  .step-wrap{
    background-color: #fff;
    padding: 60px 70px;
    min-height: calc(100vh - 350px);
    .step-item-box{
      display: flex;
      .step-line{
        font-size: 16px;
        padding-left: 30px;
        margin-right: 120px;
        position: relative;
        &::before{
          position: absolute;
          left: 0;
          top: 5px;
          content: '';
          display: inline-block;
          width: 16px;
          height: 16px;
          background-color: #E1E1E1;
          border-radius: 50%;
        }
        &::after{
          content: '';
          display: inline-block;
          width: 1px;
          height: 100%;
          background-color: #E1E1E1;
          position: absolute;
          left: 8px;
          top: 5px;
        }
      }
      .step-content{
        font-size: 14px;
        margin-bottom: 60px;
        .user-box{
          display: inline-block;
          padding: 9px 24px;
          background-color: #E0EEFD;
          border-radius: 4px;
          color: #2D8CF0;
          margin-right: 24px;
          margin-bottom: 24px;
          position: relative;
          .delete-icon{
            position: absolute;
            top: -7px;
            right: -7px;
            width: 14px;
            height: 14px;
            cursor: pointer;
          }
        }
        .user-name{
          font-size: 14px;
          &::after{
            content: '、';
          }
        }
        .user-name:last-child::after{
          content: '';
          margin-right: 20px;
        }
        .add-btn{
          color: #409EFF;
          font-size: 16px;
          cursor: pointer;
          // margin-left: 20px;
        }
      }
    }

    .step-item-box:last-child{
      .step-line::after{
        width: 0;
      }
    }
    
  }
  .bts-box{
    background-color: #fff;
    text-align: center;
    padding: 50px 0;
  }
}

.add-wrap{
  /deep/ .el-input{
    width: 100% !important;
  }
  .search-box{
    width: 500px;
  }
}
</style>