Administrator
2025-05-09 320e9165ac6cc6d90978fbef3074a8ed9add1790
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
package com.taoke.autopay.controller;
 
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.taoke.autopay.dao.credit.CreditExchangeRecordMapper;
import com.taoke.autopay.dao.credit.UserCreditRecordMapper;
import com.taoke.autopay.dto.admin.CreditInfoDto;
import com.taoke.autopay.entity.SystemConfigKeyEnum;
import com.taoke.autopay.entity.WxUserInfo;
import com.taoke.autopay.entity.credit.CreditExchangeRecord;
import com.taoke.autopay.entity.credit.UserAlipayBinding;
import com.taoke.autopay.entity.credit.UserCreditBalance;
import com.taoke.autopay.entity.credit.UserCreditRecord;
import com.taoke.autopay.exception.UserCreditExchangeException;
import com.taoke.autopay.manager.UserCreditExchangeManager;
import com.taoke.autopay.service.SystemConfigService;
import com.taoke.autopay.service.credit.CreditExchangeRecordService;
import com.taoke.autopay.service.credit.UserAlipayBindingService;
import com.taoke.autopay.service.credit.UserCreditBalanceService;
import com.taoke.autopay.service.credit.UserCreditRecordService;
import com.taoke.autopay.utils.Constant;
import com.taoke.autopay.utils.JsonUtil;
import com.taoke.autopay.utils.StringUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
 
import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;
 
@RestController
@RequestMapping("/credit/api")
public class CreditController {
 
    private static final Logger logger = LoggerFactory.getLogger(CreditController.class);
 
    @Resource
    private UserCreditBalanceService userCreditBalanceService;
 
    @Resource
    private UserCreditExchangeManager userCreditExchangeManager;
 
    @Resource
    private CreditExchangeRecordService creditExchangeRecordService;
 
    @Resource
    private UserAlipayBindingService userAlipayBindingService;
 
    @Resource
    private UserCreditRecordService userCreditRecordService;
 
    @Resource
    private CreditExchangeRecordService userCreditExchangeRecordService;
 
    @Resource
    private SystemConfigService systemConfigService;
 
    private final Gson gson = new GsonBuilder().registerTypeAdapter(BigDecimal.class, new TypeAdapter<BigDecimal>() {
        @Override
        public void write(JsonWriter out, BigDecimal value) throws IOException {
            String desc = "";
            if (value != null) {
                out.value(value.setScale(2, RoundingMode.HALF_UP).toString());
            } else {
                out.value("");
            }
        }
 
        @Override
        public BigDecimal read(JsonReader in) throws IOException {
            return new BigDecimal("0");
        }
    }).create();
 
    private Long getUserId(HttpSession session) {
        WxUserInfo user = (WxUserInfo) session.getAttribute(Constant.SESSION_KEY_USER);
        if (user != null) {
            return user.getId();
        }
        return null;
    }
 
    private String getLoginLinkContent() {
        String redictLink = systemConfigService.getValueCache(SystemConfigKeyEnum.WX_REDIRECT_LINK);
        redictLink = redictLink.replace("snsapi_base", "snsapi_userinfo");
        // 没有登录,返回登录链接
        JSONObject root = new JSONObject();
        root.put("link", redictLink);
        return JsonUtil.loadTrueResult(Constant.RESULT_CODE_NEED_LOGIN, root);
    }
 
    /**
     * 获取积分信息接口
     * 返回积分余额,剩余积分可兑换的红包,正在兑换中的积分数量
     */
    @RequestMapping("/info")
    public String getCreditInfo(HttpSession session) {
        Long userId = getUserId(session);
        if (userId == null) {
            return getLoginLinkContent();
        }
        int balanceAmount = 0;
        UserCreditBalance balance = userCreditBalanceService.getCreditBalanceByUserId(userId);
        if (balance != null) {
            balanceAmount = balance.getCreditBalance();
        }
 
        BigDecimal money = new BigDecimal(0);
        try {
            money = userCreditExchangeManager.calculateExchangeAmount(userId, balanceAmount, false);
        } catch (UserCreditExchangeException e) {
            throw new RuntimeException(e);
        }
 
        List<CreditExchangeRecord> recordList = creditExchangeRecordService.listExchangeRecords(CreditExchangeRecordMapper.DaoQuery.builder()
                .uid(userId)
                .exchangeStatus(CreditExchangeRecord.STATUS_NOT_VERIFY)
                .count(100)
                .build());
        int exchaningCredits = 0;
        if (recordList != null) {
            for (CreditExchangeRecord record : recordList) {
                exchaningCredits += record.getConsumedCredits();
            }
        }
 
 
        try {
            return JsonUtil.loadTrueResult(gson.toJson(CreditInfoDto.builder()
                    .balance(balanceAmount)
                    .exchangeMoney(money)
                    .exchangingCredits(exchaningCredits)
                    .build()));
        } catch (Exception e) {
            logger.error("获取积分信息失败", e);
            return JsonUtil.loadFalseResult("获取积分信息失败");
        }
    }
 
    /**
     * 获取支付宝绑定信息
     */
    @RequestMapping("/getAlipayBinding")
    public String getAlipayBinding(HttpSession session) {
        Long uid = getUserId(session);
        if (uid == null) {
            return getLoginLinkContent();
        }
 
        List<UserAlipayBinding> alipayBindings = userAlipayBindingService.getBindingsByUid(uid);
        if (alipayBindings == null || alipayBindings.isEmpty()) {
            return JsonUtil.loadFalseResult("用户未绑定支付宝账户");
        }
        try {
            return JsonUtil.loadTrueResult(alipayBindings.get(0));
        } catch (Exception e) {
            logger.error("获取支付宝绑定信息失败", e);
            return JsonUtil.loadFalseResult("获取支付宝绑定信息失败");
        }
    }
 
    /**
     * 修改支付宝绑定信息
     */
    @PostMapping("/updateAlipayBinding")
    public String updateAlipayBinding(String alipayName, String alipayAccount, HttpSession session) {
        Long userId = getUserId(session);
        if (userId == null) {
            return getLoginLinkContent();
        }
 
        List<UserAlipayBinding> alipayBindings = userAlipayBindingService.getBindingsByUid(userId);
        if (alipayBindings != null && !alipayBindings.isEmpty()) {
            userAlipayBindingService.updateBinding(UserAlipayBinding.builder()
                    .id(alipayBindings.get(0).getId())
                    .alipayName(alipayName)
                    .alipayAccount(alipayAccount)
                    .updateTime(new Date())
                    .build());
        } else {
            userAlipayBindingService.addBinding(UserAlipayBinding.builder()
                    .uid(userId)
                    .alipayName(alipayName)
                    .alipayAccount(alipayAccount)
                    .createTime(new Date())
                    .build());
        }
        return JsonUtil.loadTrueResult("修改成功");
 
    }
 
    /**
     * 获取积分记录接口(可分页)
     */
    @RequestMapping("/records")
    public String getCreditRecords(@RequestParam(defaultValue = "1") int page,
                                   @RequestParam(defaultValue = "10") int pageSize,
                                   HttpSession session) {
        Long userId = getUserId(session);
        if (userId == null) {
            return getLoginLinkContent();
        }
        UserCreditRecordMapper.DaoQuery query = UserCreditRecordMapper.DaoQuery.builder()
                .uid(userId)
                .start((long) (page - 1) * pageSize)
                .count(pageSize)
                .build();
        List<UserCreditRecord> recordList = userCreditRecordService.listCreditRecords(query);
        long count = userCreditRecordService.countCreditRecords(query);
        JSONObject root = new JSONObject();
        root.put("list", gson.toJson(recordList));
        root.put("count", count);
        return JsonUtil.loadTrueResult(root);
    }
 
    /**
     * 积分兑换接口
     */
    @PostMapping("/exchange")
    public String exchangeCredits(@RequestParam int credits, HttpSession session) {
        Long userId = getUserId(session);
        if (userId == null) {
            return getLoginLinkContent();
        }
 
        try {
            userCreditExchangeManager.exchangeCredit(CreditExchangeRecord.builder()
                    .consumedCredits(credits)
                    .uid(userId)
                    .exchangeType(CreditExchangeRecord.ExchangeType.FUND_EXCHANGE)
                    .createTime(new Date())
                    .build());
            return JsonUtil.loadTrueResult("兑换成功");
        } catch (UserCreditExchangeException e) {
            logger.error("积分兑换失败", e);
            return JsonUtil.loadFalseResult(e.getMessage());
        } catch (Exception e) {
            logger.error("积分兑换失败", e);
            return JsonUtil.loadFalseResult("兑换失败,请稍后重试");
        }
    }
 
    /**
     * 积分兑换接口(可分页)
     */
    @PostMapping("/exchange_records")
    public String exchangeCredits(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpSession session) {
        Long userId = getUserId(session);
        if (userId == null) {
            return getLoginLinkContent();
        }
        CreditExchangeRecordMapper.DaoQuery query = CreditExchangeRecordMapper.DaoQuery.builder()
                .uid(userId)
                .start((long) (page - 1) * pageSize)
                .count(pageSize)
                .build();
        List<CreditExchangeRecord> recordList = userCreditExchangeRecordService.listExchangeRecords(query);
        long count = userCreditExchangeRecordService.countExchangeRecords(query);
        JSONObject root = new JSONObject();
        root.put("list", gson.toJson(recordList));
        root.put("count", count);
        return JsonUtil.loadTrueResult(root);
    }
}