绿满眶商城微信小程序-uniapp
zxl
3 天以前 a8e2f971ecaa34570f679ec6f33c9a48cf109f82
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
<template>
    <view class="add-user-container">
        <u-navbar :is-back="true" :title="title" title-color="#333" back-icon-color="#333"></u-navbar>
        <!-- 表单区域 -->
        <view class="form-card">
            <u-form :model="form" ref="uForm1" label-width="150rpx" :rules="rules">
 
                <!-- 真实姓名 -->
                <u-form-item label="真实姓名" prop="realName" borderBottom required="true">
                    <u-input v-model="form.realName" placeholder="请输入真实姓名" border="none" />
                </u-form-item>
 
                <!-- 电话 -->
                <u-form-item label="电话" prop="mobile" borderBottom required="true">
                    <u-input v-model="form.mobile" placeholder="请输入手机号码" border="none" type="number" />
                </u-form-item>
                <!-- 密码 -->
                <u-form-item label="密码" prop="password" borderBottom required="true" v-if="!form.id">
                    <u-input v-model="form.password" placeholder="请输入密码" border="none" type="password" />
                </u-form-item>
 
                <u-form-item label="超级管理员" prop="isSuper" borderBottom required="true">
                    <view class="switch-wrapper">
                        <u-switch v-model="form.isSuper"></u-switch>
                    </view>
                </u-form-item>
                <u-form-item label="角色" prop="role" v-if="!form.isSuper">
                    <u-checkbox-group @change="checkboxGroupChange" class="checkbox-group">
                        <u-checkbox @change="checkboxChange" v-model="item.checked" v-for="(item, index) in roleList"
                            :key="index" :name="item.id" class="custom-checkbox">
                            <span class="checkbox-label">{{ item.name }}</span>
                        </u-checkbox>
                    </u-checkbox-group>
                </u-form-item>
                <u-form-item label="所属部门" prop="departmentId" borderBottom>
                </u-form-item>
                <DaTreeVue2 :data="roomTreeData" labelField="name" valueField="id" defaultExpandAll
                    :defaultCheckedKeys="defaultCheckedKeysValue" @change="handleTreeChange"
                    @expand="handleExpandChange" />
                <!-- 角色选择 -->
 
 
            </u-form>
 
            <!-- 提交按钮 -->
            <view class="submit-btn">
                <u-button type="primary" shape="circle" @click="submitForm()" :loading="loading">提交</u-button>
            </view>
        </view>
    </view>
</template>
 
<script>
    import {
        add,
        update,
        getDetail,
        getStoreRoleList,
        getDeptTree,
        check
    } from "@/api/userPermissions.js"
    import '@/components/uview-components/uview-ui';
 
    import DaTreeVue2 from '@/components/da-tree-vue2/index.vue'
 
    export default {
        components: {
            DaTreeVue2,
        },
        data() {
            return {
                checking: false, // 检查状态
                lastRequest: null, // 最后一次请求的标识(用于防抖)
                
                rules: {
                    realName: {
                        required: true,
                        trigger: ['blur'],
                        message: '姓名不能为空'
 
                    },
                    mobile: [{
                            required: true,
                            trigger: ['blur'],
                            message: '电话号码不能为空'
                        },
                        {
                            pattern: /^1[3-9]\d{9}$/,
                            message: "手机号格式不正确(必须是11位中国大陆手机号)",
                            trigger: ["blur"]
                        },
                        {
                            validator: this.checkPhoneUsage,
                            trigger: ['blur']
                        }
                    ],
 
 
                    password: {
                        required: true,
                        trigger: ['blur', 'change'],
                        message: '密码不能为空'
 
                    },
                },
                defaultCheckedKeysValue: '',
                title: '',
                // 表单数据
                form: {
                    id: '',//属于店员表id
                    mobile: '',
                    realName: '',
                    password: '',
                    role: [],
                    isSuper: true,
                    departmentId: ''
                },
                memberId:'',
 
                // 加载状态
                loading: false,
                // 角色选项
                roleList: [],
                roomTreeData: [],
            };
        },
        onReady() {
            //onReady 为uni-app支持的生命周期之一
 
        },
        onLoad(options) {
            // 接收 URL 参数
            if (options.id) {
                this.form.id = options.id;
                // 可在此处发起请求,根据 ID 加载详情数据
                this.title = '修改用户';
                this.getDetail();
            } else {
                this.title = '新增用户';
            }
            this.getRole()
            this.getDeptTree()
            setTimeout(() => {
                this.$refs.uForm1.setRules(this.rules)
            }, 500)
        },
        methods: {
            // 自定义异步验证方法
            checkPhoneUsage(rule, value, callback) {
                if (!value || !/^1[3-9]\d{9}$/.test(value)) {
                    return callback() // 格式错误时跳过接口检查
                }
 
                this.checking = true
                const currentRequest = Symbol() // 生成唯一标识
                this.lastRequest = currentRequest
 
                // 调用API检查手机号(示例使用uni.request)
                const form ={
                    mobile:value,
                    memberId:this.memberId
                }
                 check(form)
                    .then(res => {
                      // 3.1 如果不是最后一次请求,忽略结果
                      if (this.lastRequest !== currentRequest) return;
                        console.log(res)
                      // 3.2 根据业务逻辑判断是否可用
                      if (res.statusCode === 200) {
                          //判断是否已存在
                        callback(); // 验证通过
                      } else {
                        callback(new Error(res.message || '该手机号已被使用'));
                      }
                    })
                    .catch(err => {
                      // 3.3 网络错误处理
                      callback(new Error('验证失败,请稍后重试'));
                    })
                    .finally(() => {
                      // 3.4 无论成功失败都取消加载状态
                      if (this.lastRequest === currentRequest) {
                        this.checking = false;
                      }
                    });
                
            },
            change(e) {
                console.log('change', e);
            },
            //转换树状结构
            renameTitleToName(treeData) {
                return treeData.map(item => {
                    const newItem = {
                        ...item,
                        name: item.title // 将title赋值给name
                    }
                    delete newItem.title // 删除原title字段
 
                    if (item.children && item.children.length > 0) {
                        newItem.children = this.renameTitleToName(item.children)
                    }
 
                    return newItem
                })
            },
 
            getDeptTree() {
                getDeptTree().then(res => {
                    if (res.statusCode === 200) {
                        console.log(res.data.data)
                        this.roomTreeData = this.renameTitleToName(res.data.data)
                    }
                })
                console.log(this.roomTreeData)
            },
            doExpandTree(keys, expand) {
                this.$refs.DaTreeRef?.setExpandedKeys(keys, expand)
 
                const gek = this.$refs.DaTreeRef?.getExpandedKeys()
                console.log('当前已展开的KEY ==>', gek)
            },
            doCheckedTree(keys, checked) {
                this.$refs.DaTreeRef?.setCheckedKeys(keys, checked)
 
                const gek = this.$refs.DaTreeRef?.getCheckedKeys()
                console.log('当前已选中的KEY ==>', gek)
            },
            handleTreeChange(allSelectedKeys, currentItem) {
                console.log('handleTreeChange ==>', allSelectedKeys, currentItem)
                this.form.departmentId = allSelectedKeys
            },
            handleExpandChange(expand, currentItem) {
                console.log('handleExpandChange ==>', expand, currentItem)
            },
            getRole() {
                getStoreRoleList().then(res => {
                    if (res.statusCode === 200) {
                        this.roleList = res.data.data
                    }
                })
            },
            //获得详情
            getDetail() {
                uni.showLoading({
                    title: '加载中'
                });
                getDetail(this.form.id).then(res => {
                    uni.hideLoading();
                    if (res.statusCode === 200) {
                        this.form.mobile = res.data.data.mobile;
                        this.form.realName = res.data.data.realName;
                        this.form.isSuper = res.data.data.isSuper;
                        this.defaultCheckedKeysValue = res.data.data.departmentId;
                        this.memberId = res.data.data.memberId
                        // 解析角色数组
                        const roles = res.data.data.roleIds.split(',');
 
                        // 更新复选框选中状态
                        this.roleList = this.roleList.map(item => {
                            return {
                                ...item,
                                checked: roles.includes(item.id)
                            };
                        });
                        this.form.role = roles;
                    }
 
                })
            },
            // 角色选择变化
            checkboxChange(e) {
                console.log(e);
            },
            checkboxGroupChange(e) {
                console.log(e)
                this.form.role = e;
            },
            // 全选
            checkedAll() {
                this.list.map(val => {
                    val.checked = true;
                })
            },
            // 提交表单
            async submitForm() {
                // 1. 手动触发表单验证
                this.$refs.uForm1.validate(valid => {
 
                    if (valid) {
                        this.loading = true;
                        // 2. 处理角色数据(将 checked=true 的项转为 role 数组)
                        const form = {
 
                            id: this.form.id,
                            mobile: this.form.mobile,
                            realName: this.form.realName,
                            password: this.form.password,
                            role: this.form.role,
                            isSuper:this.form.isSuper,
                            departmentId:this.form.departmentId,
                        }
                        
                        if (form.id) {
                            update(form).then(res => {
                                this.loading = false;
                                if (res.statusCode === 200) {
                                    uni.showToast({
                                        title: res.data.msg, // 提示文字
                                        icon: 'none', // 图标类型(success/loading/none)
                                        mask: true // 是否显示透明蒙层(防止触摸穿透)
                                    });
 
                                    setTimeout(() => uni.navigateBack(), 1500);
                                }
                            })
                        } else {
                            add(form).then(res => {
                                this.loading = false;
                                if (res.statusCode === 200) {
                                    uni.showToast({
                                        title: res.data.msg, // 提示文字
                                        icon: 'none', // 图标类型(success/loading/none)
                                        mask: true // 是否显示透明蒙层(防止触摸穿透)
                                    });
 
                                    setTimeout(() => uni.navigateBack(), 1500);
                                }
                            })
                        }
 
                    }
                });
 
 
 
            }
        }
    };
</script>
 
<style lang="scss" scoped>
    .checkbox-group {
        gap: 16px;
 
    }
 
    .switch-wrapper {
        display: flex;
        justify-content: flex-start;
        width: 100%;
    }
 
    /* 单个复选框样式 */
    .custom-checkbox {
        /deep/ .u-checkbox__icon-wrap {
            border-radius: 4px;
            /* 圆角 */
            border: 1px solid #dcdfe6;
            /* 边框 */
        }
 
        /deep/ .u-checkbox__icon--checked {
            background-color: #2979ff;
            /* 选中背景色 */
            border-color: #2979ff;
        }
    }
 
    /* 复选框文字样式 */
    .checkbox-label {
        margin-left: 8px;
        /* 文字与图标的间距 */
        font-size: 14px;
        color: #606266;
    }
 
    /* 全选按钮样式 */
    .select-all-btn {
        width: 40rpx;
        margin-top: 8px;
    }
 
    .add-user-container {
        padding: 30rpx;
        min-height: 100vh;
        background-color: #f5f7fa;
 
        .form-card {
            background-color: #fff;
            border-radius: 16rpx;
            padding: 30rpx;
            box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
        }
 
        .submit-btn {
            margin-top: 60rpx;
            padding: 0 30rpx;
        }
 
        // 调整uView表单样式
        ::v-deep .u-form-item {
            padding: 24rpx 0;
 
            &__body {
                padding: 0;
            }
        }
 
        // 复选框样式调整
        ::v-deep .u-checkbox-group {
            width: 100%;
            padding: 16rpx 0;
        }
    }
</style>