liujie
2025-07-21 87f979fb201a82ebad5926735ed6dfa75ca004d3
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
package com.ruoyi.web.controller.system;
 
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.constant.WxConstant;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.BasePage;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.*;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.model.TbQuestion;
import com.ruoyi.system.model.TbSystemConfig;
import com.ruoyi.system.model.TbUser;
import com.ruoyi.system.service.TbQuestionService;
import com.ruoyi.system.service.TbSystemConfigService;
import com.ruoyi.system.service.TbUserService;
import com.ruoyi.system.utils.wx.WxProperties;
import com.ruoyi.system.vo.InviteUserListVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
 
import static com.ruoyi.system.utils.wx.tools.WxAppletTools.ACCESS_TOKEN_URL;
 
@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = "用户模块")
public class UserController {
 
    @Autowired
    private TbUserService userService;
 
    @Autowired
    private TokenService tokenService;
 
    @Autowired
    private TbQuestionService questionService;
 
    @Autowired
    private TbSystemConfigService systemConfigService;
 
    @Autowired
    private WxProperties wxConfig;
    @Autowired
    private RestTemplate restTemplate;
 
    @ApiOperation(value = "修改用户信息",tags = {"用户模块"})
    @PostMapping("/updateUserInfo")
    public R<?> updateUserInfo(String avatar,String username) {
        LoginUser loginUser = tokenService.getLoginUser();
        if(loginUser==null){
            return R.fail(HttpStatus.UNAUTHORIZED,"请重新登录");
        }
        Long userId = loginUser.getUserId();
 
        TbUser user = userService.getById(userId);
        if(StringUtils.isNotEmpty(username)) {
            user.setUserName(username);
        }
        if(StringUtils.isNotEmpty(avatar)){
            user.setAvatar(avatar);
        }
        userService.updateById(user);
        return R.ok();
    }
 
 
    @ApiOperation(value = "获取最新用户信息",tags = {"用户模块"})
    @GetMapping("/getUserInfo")
    public R<?> getUserInfo() {
        LoginUser loginUser = tokenService.getLoginUser();
        if(loginUser==null){
            return R.fail(HttpStatus.UNAUTHORIZED,"请重新登录");
        }
        Long userId = loginUser.getUserId();
        TbUser user = userService.getById(userId);
        return R.ok(user);
    }
 
    @ApiOperation(value = "账号注销",tags = {"用户模块"})
    @PostMapping("/accountCancellation")
    public R<?> accountCancellation() {
        LoginUser loginUser = tokenService.getLoginUser();
        if(loginUser==null){
            return R.fail(HttpStatus.UNAUTHORIZED,"请重新登录");
        }
        Long userId = loginUser.getUserId();
        TbUser user = userService.getById(userId);
        user.setStatus(3);
        userService.updateById(user);
        return R.ok(user);
    }
 
 
 
    @ApiOperation(value = "分享有礼列表",tags = {"分享有礼列表"})
    @GetMapping("/getInviteUserList")
    public R<Page<InviteUserListVo>> getInviteUserList(BasePage page) {
        LoginUser loginUser = tokenService.getLoginUser();
        if(loginUser==null){
            return R.fail(HttpStatus.UNAUTHORIZED,"请重新登录");
        }
        Long userId = loginUser.getUserId();
        Page<TbUser> page1 = userService.page(new Page<>(page.getPageNum(), page.getPageSize()), new LambdaQueryWrapper<TbUser>().eq(TbUser::getInviteId, userId).orderByDesc(TbUser::getCreateTime));
        Page<InviteUserListVo> inviteUserListVoPage = new Page<>();
        if(page1.getRecords().isEmpty()){
            return R.ok(inviteUserListVoPage);
        }
        ArrayList<InviteUserListVo> inviteUserListVos = new ArrayList<>();
        for (TbUser record : page1.getRecords()) {
            InviteUserListVo inviteUserListVo = new InviteUserListVo();
            inviteUserListVo.setUsername(record.getUserName());
            inviteUserListVo.setCreateTime(record.getCreateTime());
            inviteUserListVo.setInviteNum(record.getInviteNum());
            inviteUserListVos.add(inviteUserListVo);
        }
        BeanUtils.copyProperties(page1,inviteUserListVoPage);
        inviteUserListVoPage.setRecords(inviteUserListVos);
        return R.ok(inviteUserListVoPage);
    }
 
 
    @ApiOperation(value = "常见问题",tags = {"用户模块"})
    @GetMapping("/getQuestion")
    public R<List<TbQuestion>> getQuestion() {
        List<TbQuestion> list =  questionService.list(new LambdaQueryWrapper<TbQuestion>().eq(TbQuestion::getDelFlag,0).orderByDesc(TbQuestion::getOrderNum));
        return R.ok(list);
    }
 
    @ApiOperation(value = "客服",tags = {"用户模块"})
    @GetMapping("/customerService")
    public R<String> customerService() {
        TbSystemConfig config = systemConfigService.getOne(new LambdaQueryWrapper<TbSystemConfig>().eq(TbSystemConfig::getType, 2));
        String content = config.getContent();
        return R.ok(content);
    }
 
 
    @ApiOperation(value = "退出登录",tags = {"用户模块"})
    @PostMapping("/quit")
    public R<String> quit(HttpServletRequest request) {
        tokenService.quitLogin(request);
        return R.ok();
    }
 
 
    @Autowired
    private OSSUtil ossUtil;
    @ApiOperation(value = "个人的小程序码(分享码)生成")
    @GetMapping("/person-code")
    public R<String> createQRcode() {
        LoginUser loginUser = tokenService.getLoginUser();
        if(loginUser==null){
            return R.fail(HttpStatus.UNAUTHORIZED,"请重新登录");
        }
        Long userId = loginUser.getUserId();
        // 获取调用凭证accessToken
        String accessToken = getAccessToken();
        RestTemplate rest = new RestTemplate();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        String imgUrl = "";
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="+accessToken;
            log.info("url: "+url);
            Map<String,Object> param = new HashMap<>();
            param.put("path","pages/shoppingMall/shoppingMall?userId="+userId);
            param.put("width", 430); //二维码尺寸
            log.info("调用生成微信URL接口传参:" + param);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            log.info("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
            byte[] result = entity.getBody();
            inputStream = new ByteArrayInputStream(result);
 
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            // 最后上传生成的文件名
            String finalFileName = System.currentTimeMillis() + "" + new SecureRandom().nextInt(0x0400) + ".jpg";
            // oss中的文件夹名
            String objectName = sdf.format(new Date()) + "/" + finalFileName;
            // 上传oss
            ossUtil.uploadFile2OSS(inputStream, objectName);
            //获取文件的URl地址
            imgUrl = ossUtil.getImgUrl(objectName);
            log.info("imgUrl: "+imgUrl);
            return R.ok(imgUrl);
 
        } catch (Exception e) {
            log.error("调用小程序生成微信永久小程序码URL接口异常",e);
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return R.fail();
    }
    @ApiOperation(value = "获取微信小程序二维码",tags = {"获取微信小程序二维码"})
    @PostMapping("/getQRCode")
    public AjaxResult getQRCode() {
        LoginUser loginUser = tokenService.getLoginUser();
        if(loginUser==null){
            return AjaxResult.error(HttpStatus.UNAUTHORIZED,"请重新登录");
        }
        Long userId = loginUser.getUserId();
        String accessToken = getAccessToken();
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token="+accessToken;
            Map<String, Object> param = new HashMap<>();
            param.put("path", "pages/shoppingMall/shoppingMall?userId="+userId);
            param.put("width", 240); //二维码尺寸
            HttpRequest post = HttpUtil.createPost(url);
            post.body(JSON.toJSONString(param));
            HttpResponse execute = post.execute();
            String body = execute.body();
            System.out.println(body);
            byte[] bytes = body.getBytes();
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            return AjaxResult.success(body);
        } catch (Exception e) {
            System.err.println("调用小程序生成微信永久小程序码URL接口异常" + e);
        }
        return AjaxResult.success();
    }
 
    public  String getAccessToken() {
        String requestUrl = MessageFormat.format(ACCESS_TOKEN_URL, wxConfig.getMemberAppId(), wxConfig.getMemberAppSecret());
        String respBody = restTemplate.getForEntity(requestUrl, String.class).getBody();
        JSONObject jsonObject = JSONObject.parseObject(respBody);
        return jsonObject.getString("access_token");
    }
}