fuliqi
2024-01-24 29c1e7eb5ac16e90d8991a86c1c071bc312ec8d9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
<template>
  <div class="userAuthority-form">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" size="mini" label-width="100px"
             class="demo-ruleForm">
      <el-form-item label="手机号码:" prop="phone">
        <el-input v-model="ruleForm.phone" :disabled="userId && entryId === 'edit' ? true : false"
                  autocomplete="off" @input="changeInputPhone">
        </el-input>
      </el-form-item>
      <el-form-item label="姓名:" prop="name" ref="name">
        <el-input :disabled="userId || isBindPhone ? true : false" v-model="ruleForm.name">
        </el-input>
      </el-form-item>
      <el-form-item label="用户账号:" prop="username" ref="username">
        <el-input autocomplete="off" :disabled="userId || isBindPhone ? true : false"
                  v-model="ruleForm.username">
        </el-input>
      </el-form-item>
      <el-form-item v-if="!userId && !isBindPhone" label="初始密码:" prop="psCode" ref="psCode">
        <el-input autocomplete="new-password" type="password" v-model="ruleForm.psCode"></el-input>
      </el-form-item>
      <el-form-item v-if="!userId && !isBindPhone" label="确认密码:" prop="confirmPsCode"
                    ref="confirmPsCode">
        <el-input type="password" autocomplete="new-password" v-model="ruleForm.confirmPsCode">
        </el-input>
      </el-form-item>
      <el-form-item label="权限配置:" prop="roles" ref="rolesRef">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll"
                     @change="handleCheckAllChange">全选</el-checkbox>
        <el-checkbox-group v-model="ruleForm.roles" @change="handlecheckedRolesChange">
          <el-checkbox class="checkbox" v-for="item in roles" :label="item.id" :key="item.id">
            {{item.name}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { roleAuthorizedClientId, roleLoadingAll, userAuthorityAdd, userAuthorityUpdate } from '../../api/userAuthority'
// import config from '../../app.config.js'
import { validateUsername, validatePwd, validateMobile } from '../../utils/validator'
import ChangePwdApi from '@api/oauth/byPhoneUpdateInfo'
const sm2 = require('sm-crypto').sm2
let _this = null;
export default {
  name: 'userAuthority-form',
  props: {
    userId: {
      type: String,
      required: true
    },
    userInfo: {
      required: true
    },
    entryId: {
      type: String,
      default: 'add'
    }
  },
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.psCode) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        phone: '',
        name: '',
        username: '',
        psCode: '',
        confirmPsCode: '',
        roles: []
      },
      checkAll: false,
      roles: [],
      checkRoles: [],
      isIndeterminate: false,
      isBindPhone: false,//是否绑定过手机号
      bindInfo: {},
      rules: {
        phone: [{ required: true, validator: validateMobile, trigger: 'change' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'change' }],
        username: [{ required: true, validator: validateUsername, trigger: 'change' }],
        psCode: [{ required: true, validator: validatePwd, trigger: 'change' }],
        confirmPsCode: [{ required: true, validator: validatePass2, trigger: 'change' }],
        roles: [{ required: true, message: '请选择权限角色', trigger: 'change' }]
      }
    }
  },
  async created() {
    _this = this;
    if (this.userInfo) {
      this.ruleForm = {
        name: this.userInfo.name,
        phone: this.userInfo.phone,
        username: this.userInfo.username,
        roles: []
      }
    }
    this.isBindPhone = this.userInfo ? true : false;
    await this._roleAuthorizedClientId()
    await this.userId && this._roleAuthorizedClientId(this.userId)
  },
  methods: {
    //通过手机号获取用户信息
    changeInputPhone(value) {
      const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
      this.isBindPhone = false;
      if (!value || !reg.test(value)) {
        this.initData();
        return;
      }
      ChangePwdApi.userByPhone({ phone: value }).then(res => {
        if (res.code === '0' && res.data) {
          let { name, username, userId } = res.data;
          _this.$nextTick(() => {
            _this.ruleForm.name = name;
            _this.ruleForm.username = username;
            _this.bindInfo = res.data;
            _this.isBindPhone = true;
          });
          this._roleAuthorizedClientId(userId)
        }
      }).catch(() => { })
    },
    //除手机号码外重置表单
    initData() {
      let field = ['name', 'username', 'psCode', 'confirmPsCode', 'rolesRef'];
      _this.$nextTick(() => {
        field.forEach((item) => {
          if (_this.$refs[item]) {
            _this.$refs[item].resetField();
          }
        })
      })
      this.checkAll = false;
      this.isIndeterminate = false;
    },
    doSm3AndSm2Encrypt(sourceStr) {
      // 密码加密
      return '04' + sm2.doEncrypt(sourceStr, process.env.VUE_APP_PUBLICKEY, 1)
    },
    async _userAuthorityAdd() {
      try {
        const psCode = this.doSm3AndSm2Encrypt(this.ruleForm.psCode)
        // const confirmPsCode = this.doSm3AndSm2Encrypt(this.ruleForm.confirmPsCode)
        const res = await userAuthorityAdd(Object.assign(JSON.parse(JSON.stringify(this.ruleForm)), {
          roles: this.checkRoles
        }, { psCode }))
        if (res.code === '0') {
          this.$message({
            message: '新增成功',
            type: 'success'
          })
          return true
        } else {
          return false
        }
      } catch (error) {
        throw new Error(error)
      }
    },
    async _userAuthorityUpdate() {
      try {
        const res = await userAuthorityUpdate(Object.assign(JSON.parse(JSON.stringify(this.ruleForm)), {
          userId: this.userId ? this.userId : this.bindInfo.userId,
          roles: this.checkRoles
        }))
        if (res.code === '0') {
          this.$message({
            message: '编辑成功',
            type: 'success'
          })
          return true
        } else {
          return false
        }
      } catch (error) {
        throw new Error(error)
      }
    },
    async _roleAuthorizedClientId(userId = '') {
      const res = await roleAuthorizedClientId({
        systemId: process.env.VUE_APP_CLIENT_ID,
        userId
      })
      if (userId) {
        _this.$nextTick(() => {
          _this.ruleForm.roles = res.data.alreadyRoleList.map(v => {
            return v.id
          })
          _this.handlecheckedRolesChange(_this.ruleForm.roles)
        })
      } else {
        // 获取所有角色
        this.roles = res.data.canRoleList
      }
    },
    async _roleLoadingAll() {
      const res = await roleLoadingAll()
      if (res.code === '0') {
        this.roles = res.data
      }
    },
    handleCheckAllChange(val) {
      _this.$nextTick(() => {
        _this.ruleForm.roles = val ? _this.roles.map(v => {
          return v.id
        }) : []
        _this.formaterCheckRoles(_this.ruleForm.roles)
        _this.isIndeterminate = false
      })
    },
    handlecheckedRolesChange(value) {
      const checkedCount = JSON.parse(JSON.stringify(value)).length
      this.checkAll = checkedCount === this.roles.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.roles.length
 
      this.formaterCheckRoles(value)
    },
    formaterCheckRoles(checkRoles) {
      const arr = []
      checkRoles.forEach((v) => {
        this.roles.forEach(k => {
          if (v === k.id) {
            arr.push({
              roleId: k.id,
              roleName: k.name
            })
          }
        })
      })
      this.checkRoles = arr
    },
    async submitForm() {
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            try {
              const flag = this.userId ? await this._userAuthorityUpdate() : await this._userAuthorityAdd()
              resolve(flag)
            } catch (error) {
              resolve(false)
              throw new Error(error)
            }
          } else {
            // reject('error submit!!')
            resolve(false)
            return false
          }
        })
      })
    }
  }
}
</script>
<style scoped lang="stylus">
.userAuthority-form {
  .checkbox {
    display: block;
  }
}
</style>