<template>
  <el-dialog class="user-data-dialog" title="设置角色" :visible.sync="visible" :before-close="handleClose">
    <el-form :model="ruleForm" ref="ruleForm" label-width="80px" class="demo-ruleForm">
      <el-form-item label="登录名:">
        <el-col :span="18">{{ user.loginName }}</el-col>
      </el-form-item>
    </el-form>
    <h2 style="text-align: center; margin: 50px 0 50px">给 {{ user.userName }} 设置角色</h2>
    <div style="text-align: center">
      <el-transfer
          style="text-align: left; display: inline-block"
          v-model="value3"
          filterable
          :render-content="renderFunc"
          :titles="['所有角色', '用户现有角色']"
          :button-texts="['删除角色', '添加角色']"
          :format="{
        noChecked: '${total}',
        hasChecked: '${checked}/${total}'
        }"
          @change="handleChange"
          :data="data"
      >
      </el-transfer>
    </div>
    <div slot="footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="submitClick()" :loading="ui.submitLoading">设置角色</el-button>
    </div>
  </el-dialog>
</template>

<script type="text/ecmascript-6">

export default {
  name: 'UserSetRoleManagementDialog',
  props: {
    dialogVisible: {
      type: Boolean,
      required: true
    },
    user: {
      type: Object,
      required: true
    }
  },

  data() {
    return {
      userArrInfo: [],//初始人员列表数据
      data: [],//转化后人员列表数据
      value3: [],//右侧默认人员列表数据
      ids: [],//送到后台 -> 勾选的数据code数组
      renderFunc(h, option) {
        return <span>{option.key} - {option.label}</span>;
      },
      ui: {
        submitLoading: false
      },
      visible: this.$props.dialogVisible,
      ruleForm: {
        loginName: '',
      },
    };
  },

  created() {
    this.ruleForm = {
      loginName: this.user.loginName,
    };
    this.selectUserRole();
    this.selectRoleByLoginName();
  },


  methods: {
    handleChange(value, direction, movedKeys) {
      // console.log('change事件数据');
      this.dc(movedKeys, this.userArrInfo, this.ids)
    },
    //转换为要传送到后台的数据数组
    dc(movedKeys, userArrInfo, selectArr) {
      // console.log('数据转换');
      let roleCode = [];
      movedKeys.map((item) => {
        userArrInfo.map((items, index) => {
          if (item == index) {
            selectArr.push(items.roleCode);
          }
        })
      })
    },
    /*查找所有用户角色*/
     selectUserRole() {
      this.$$get(`/role/select/`)
          .then(res => {
            console.log(res.data.result)
            this.userArrInfo = res.data.result;
            let userArr = [];
            // console.log(res)
            res.data.result.map((item, index) => {
              userArr.push({key: index, label: item.name, code: item.code});
            });
            this.data = userArr;
          })
    },

    /*查找该用户角色*/
    selectRoleByLoginName() {
      this.$$get(`/user/selectUserRole/${this.user.loginName}`, {
        loginName: this.user.loginName,
      })
          .then(res => {
            if (res.data.code != 200) {
              throw  res.data.message;
            }
            // 加延时
            setTimeout(() => {
              let userHaveArr = [];
              for (var i = 0; i < this.data.length; i++) {
                for (var j = 0; j < res.data.result.length; j++) {
                  if (this.data[i].code == res.data.result[j]) {
                    userHaveArr[userHaveArr.length] = this.data[i].key
                  }
                }
              }
              this.value3 = userHaveArr;
            }, 200);
          })


    },

    /** 提交点击 */
    async submitClick() {
      // console.log(this.value3)
      let userRole = [];

      for (let i = 0; i < this.data.length; i++) {
        for (let j = 0; j < this.value3.length; j++) {
          if (this.data[i].key == this.value3[j]) {
            userRole[userRole.length] = this.data[i].code
          }
        }
      }
      this.$$post('/user/userRole', {
        loginName: this.user.loginName,
        userRole: userRole,
      })
          .then(res => {
            if (res.data.code != 200) {
              this.$message.error(res.data.message);
              return
            }
            this.$message({message: '设置成功', type: 'success'});
            setTimeout(function () {
              this.visible = false;
              window.location.reload();
            }, 500)
          }).catch(err => this.$$msg.err(err))
    },

    /** 关闭处理 */
    handleClose() {
      this.visible = false;
      setTimeout(() => {
        this.$emit('update:dialogVisible', false)
      }, 300);
    }
  }
}
</script>
