<template>
  <!-- 添加人员信息 -->
  <div class="addWagonLoad">
    <PageTitle>返回</PageTitle>
     <div class="form-box" style="margin-right: 10rem">
        <dil-form :formId="325" v-model="form1" ref="from1"></dil-form>
      </div>

      <div class="department">
        <div class="department2">
                <span>二级部门：</span>
                <el-select v-model="value1" placeholder="请选择" @change="onchange1">
                    <el-option
                    v-for="(item,i) in options1"
                    :key="i"
                    :label="item.label"
                    :value="item.value"
                    >
                    </el-option>
                </el-select>
            </div>
            <div class="department3">
                <span>三级部门：</span>
                <el-select v-model="value2" placeholder="请选择" @change="onchange2">
                    <el-option
                        v-for="(item,i) in options2"
                        :key="i"
                        :label="item.label"
                        :value="item.value"
                    >
                    </el-option>
                </el-select>
            </div>
      </div>
      <div>
        <div class="role">
                <span>赋权角色：</span>
                <el-select v-model="value3" placeholder="请选择">
                    <el-option
                        v-for="(item,i) in options3"
                        :key="i"
                        :label="item.roleName"
                        :value="item.roleId"
                    >
                    </el-option>
                </el-select>
            </div>
      </div>

    <div class="button-box">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="makeSure">确定</el-button>
    </div>
  </div>
</template>

<script>
import PageTitle from "@/components/Page/Title";
import { getCookie } from "@/utils/util.js";
export default {
  components: { PageTitle },
  data() {
    return {
      form1: {
        personnelJobNumber : '',
        personnelName : '',
        personnelPost : '',
        personnelWorkshopid : '',
        shipperId : '',
        personnelShifts : '',
        personnelTeam : ''
      },
      value: undefined,
      //新增用户的SSO主键
      personnelSsoId:'',
      //token
      token: null,
      //二级部门
      options1:[],
      //选中的二级部门名称
      value1:'',
      //选中的二级部门机构ID和机构编码
      map1:{
          shipperOrgCode : '',
          shipperSsoId : ''
      },
      // 三级部门
      options2:[],
      // 选中的三级部门名称
      value2:'',
      //选中的三级部门机构ID和机构编码
      map2:{
          shipperOrgCode : '',
          shipperSsoId : ''
      },
      // 角色
      options3:[],
      // 选中的角色名称
      value3:'',
      // 选中的角色ID
      roleId:''
    };
  },
  created(){
    this.token = getCookie("accessToken");
  },
  mounted() {
    //初始化二级机构和角色
    this.initialization();
  },
  methods: {
     initialization(){
       //初始化选择二级机构
         this.axios.get('/api/v1/rms/getSecondShipper').then((res)=>{
             this.options1 = res.data.data;
         })
         //初始化角色
        const formData = new FormData();
        this.$store.dispatch('system/rolesManage/list',formData)
        .then((res)=>{
          var roleList = [];
          roleList=res.data;
          roleList.forEach((item,i)=>{
              if(item.roleId!='superadmin'){
                this.options3.push(item);
              }
          })
          // this.options3 = res.data;
        })
     },
     onchange1(val){
            //  查询选中的二级机构下的三级机构
             this.value2 = '';
             this.axios.get('/api/v1/rms/getThirdShipper?shipperId='+val).then((res)=>{
             this.options2 = res.data.data;    
         })
         //获取二级部门的机构ID和机构编码
         this.axios.post('/api/v1/rms/getShipperMap?shipperId='+val).then((res)=>{
             this.map1 = res.data.data;
         })
     },
     onchange2(val){
         //获取三级部门的机构ID和机构编码
         this.axios.post('/api/v1/rms/getShipperMap?shipperId='+val).then((res)=>{
             this.map2 = res.data.data; 
         })
     },

     //确定人员新增
     makeSure() {
      //初始化用户信息
      let userInfo = {
        orgCode : '',
        orgName : '',
        orgId : '',
      };
      //该用户没有三级部门
      if(this.options2.length==0){
      userInfo = {
        userName : this.form1.personnelName,
        userCode : this.form1.personnelJobNumber,
        orgCode : this.map1.shipperOrgCode,
        orgName : this.value1,
        orgId : this.map1.shipperSsoId,
        // mobile : '13500000011',
        // email : '123456789@qq.com',
        groupId : '506514577756917769',
        companyId : '713710108567277568'
      }
      //该用户有三级部门
      }else{
        userInfo = {
        userName : this.form1.personnelName,
        userCode : this.form1.personnelJobNumber,
        orgCode : this.map2.shipperOrgCode,
        orgName : this.value1,
        orgId : this.map2.shipperSsoId,
        // mobile : '13500000011',
        // email : '123456789@qq.com',
        groupId : '506514577756917769',
        companyId : '713710108567277568'
      }
      }
       //先新增SSO中的用户
      const formData = new FormData();
      
      Object.keys(userInfo).forEach((key) => {
      formData.append(key, userInfo[key]);
      });
      //判断数据是否都填了
      if(
            this.form1.personnelJobNumber =='' ||
            this.form1.personnelPost =='' ||
            this.form1.personnelName =='' ||
            // RmsPersonnel.personnelWorkshopid==null ||
            this.form1.shipperId=='' ||
            this.form1.personnelShifts=='' ||
            this.form1.personnelTeam=='' ||
            userInfo.orgName=='' ||
            userInfo.orgCode=='' ||
            userInfo.orgId=='' ||
            this.value3==''
          ){
              this.$message.error("存在空值！");
      }else{
      //判断RMS_PERSONNEL表中是否存在该人员信息，存在提示存在，否则开始赋权新增
      this.axios.post('/api/v1/rms/isInHere?personnelJobNumber='+this.form1.personnelJobNumber)
      .then((res)=>{
        console.log("res",res);
        if(res.data==0){
          this.$message.error("新增失败,该账号已存在！");
        }else{
          //开始赋权新增
          //新增用户表
          this.$store.dispatch('system/usersManage/addUser',formData)
          .then((res)=>{
              //console.log("role",res)
              //保存权限表中的用户主键Id
              this.personnelSsoId = res.data.userId;
              //再新增RMS_PERSONNEL表信息
              let rmsPersonnel = {
                personnelJobNumber : this.form1.personnelJobNumber,
                personnelPost : this.form1.personnelPost,
                personnelName : this.form1.personnelName,
                personnelDepartmentId : this.form1.shipperId,
                // personnelWorkshopid : this.form1.personnelWorkshopid,
                personnelShifts : this.form1.personnelShifts,
                personnelTeam : this.form1.personnelTeam,
                personnelSsoId : this.personnelSsoId
              }
              //  console.log("rmsPersonnel",rmsPersonnel)
                  this.axios.post('/api/v1/rms/addPersonnel',rmsPersonnel)
                  .then((res)=>{
                              // console.log("Personnel",res)
                        if (res.data.code == 200) {
                        this.$message({
                          type: "success",
                          message: "新增成功!",
                        });
                        // this.$refs.table.refreshData();
                        
                        //最后新增角色赋权表

                          this.axios.post('pass/v1/sysuserroles/addUserroles?userId='
                          +this.personnelSsoId+'&userCode='+this.form1.personnelJobNumber+'&roleId='+this.value3)
                          .then((res)=>{
                            // console.log("success")
                              this.$router.go(-1);
                          })

                      } else {
                        this.$message.error("新增失败,可能存在重复！");
                      }
                      // this.$refs['table'].resetField();
                  })

          });//end

        }
      });
      
      }//else
      
    },
    // 取消
    cancel() {
      this.$router.go(-1);
    },
  },
};
</script>
<style lang='scss' >
 .button-box{
    display: flex;
    justify-content: center;
    margin-top: 2rem;
    .el-button{
      width: 80px;
      margin-right: 10px;
    }
  }
.form-box{
  display: flex;
  justify-content: center;
  .el-form-item{
    display: flex;
    justify-content: center;
    .el-form-item__label{
      display: flex;
      align-items: center;
    }
    .el-form-item__content{
      .el-input{
        .el-input__inner{
          width: 250px;
        }
      }
    }
  }
}
.department{
  display: flex;
  justify-content: center;
  .department3{
    margin-left: 2rem;
  }
}
.role{
  display: flex;
  justify-content: center;
  margin-top: 2rem;
}
</style>
