无关风月
2025-08-05 2134c13b7b2815983281fdc819e3138ffde1bc48
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
package com.ruoyi.other.controller;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.chargingPile.api.feignClient.SiteClient;
import com.ruoyi.chargingPile.api.model.Site;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.page.PageInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.other.api.domain.IntegralPay;
import com.ruoyi.other.api.domain.IntegralRecord;
import com.ruoyi.other.api.domain.ServicePay;
import com.ruoyi.other.api.domain.TIntegralRule;
import com.ruoyi.other.query.IntegralListQuery;
import com.ruoyi.other.service.TIntegralPayService;
import com.ruoyi.other.service.TIntegralRecordService;
import com.ruoyi.other.service.TIntegralRuleService;
import com.ruoyi.other.service.TServicePayService;
import com.ruoyi.other.util.MyQrCodeUtil;
import com.ruoyi.other.util.ObsUploadUtil;
import com.ruoyi.other.util.QRCodeUtil;
import com.ruoyi.other.util.UUIDUtil;
import com.ruoyi.other.util.pay.CreateLinkStringByGet1;
import com.ruoyi.other.util.pay.HttpRequester;
import com.ruoyi.other.util.pay.HttpRespons;
import com.ruoyi.other.util.pay.Md5_Sign;
import com.ruoyi.other.util.payment.wx.WechatPayService;
import com.ruoyi.other.vo.IntegralListVO;
import com.ruoyi.other.vo.IntegralVO;
import com.ruoyi.other.vo.PayDto;
import com.ruoyi.other.vo.WorkPlatformVO;
import com.ruoyi.system.api.domain.SysConfig;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.feignClient.SysConfigClient;
import com.ruoyi.system.api.feignClient.SysUserClient;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.ByteArrayOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 无关风月
 * @since 2024-08-06
 */
@RestController
@RequestMapping("/integral")
public class TIntegralController {
 
    @Autowired
    private TIntegralRuleService integralRuleService;
    @Autowired
    private TIntegralRecordService integralRecordService;
    @Autowired
    private TIntegralPayService integralPayService;
    @Autowired
    private SysConfigClient sysConfigClient;
 
    @Autowired
    private TokenService tokenService;
    @Autowired
    private TServicePayService servicePayService;
    @Resource
    private SysUserClient sysUserClient;
    @Resource
    private SiteClient siteClient;
    @Resource
    private WechatPayService wechatPayService;
 
 
    /**
     * 充电保存积分记录
     *
     * @return
     */
    @PostMapping("/saveIntegralRecord")
    public R saveIntegralRecord(@RequestBody IntegralRecord record) {
        integralRecordService.save(record);
        return R.ok();
    }
 
    @PostMapping("/workPlatform")
    @ApiOperation(tags = {"小程序工作台"}, value = "小程序工作台")
    public R<WorkPlatformVO> workPlatform() {
        Long userid = tokenService.getLoginUser().getUserid();
        R<SysUser> data = sysUserClient.getSysUser(userid);
        SysUser user = data.getData();
        List<Site> sites = siteClient.getSiteAll().getData();
        Site site = sites.stream().filter(e -> e.getId().equals(user.getSiteId())).findFirst().orElse(null);
        if (site==null){
            return R.fail("当前登录用户未绑定站点");
        }
        WorkPlatformVO workPlatformVO = new WorkPlatformVO();
        workPlatformVO.setSiteName(site.getName());
        workPlatformVO.setHeaderName(user.getNickName());
        ServicePay one = servicePayService.lambdaQuery().eq(ServicePay::getPayStatus, 2)
                .eq(ServicePay::getUserId, userid).orderByDesc(ServicePay::getCreateTime)
                .last("limit 1").one();
        if (one!=null){
            workPlatformVO.setServiceStatus(1);
            workPlatformVO.setEndTime(one.getEndTime());
        }else{
            workPlatformVO.setServiceStatus(0);
            workPlatformVO.setEndTime(null);
        }
 
 
        return R.ok(workPlatformVO);
    }
    @PostMapping("/integralPageList")
    @ApiOperation(tags = {"2.0-积分钱包"}, value = "积分钱包")
    public R<IntegralVO> integralPageList(@RequestBody IntegralListQuery query) {
        Long userid = tokenService.getLoginUser().getUserid();
        R<SysUser> sysUser = sysUserClient.getSysUser(userid);
        query.setSiteId(sysUser.getData().getSiteId());
        Integer integral = sysUser.getData().getIntegral();
        IntegralVO integralVO = new IntegralVO();
        PageInfo<IntegralListVO> integralListVOPageInfo = integralRecordService.integralPageList(query);
        integralVO.setIntegralList(integralListVOPageInfo);
        integralVO.setIntegral(integral);
        return R.ok(integralVO);
    }
 
    @ApiOperation(tags = {"2.0-积分钱包"}, value = "查询支付结果 true成功 false失败")
    @PostMapping(value = "/queryPayStatus")
    public R buy(@RequestParam Integer id) {
        IntegralPay integralPay = integralPayService.getById(id);
        if (integralPay.getPayStatus() == 2) {
            return R.ok(true);
        } else {
            return R.ok(false);
        }
    }
 
    @PostMapping("/nativePay")
    @ApiOperation(tags = {"2.0-积分钱包"}, value = "获取支付二维码")
    public R<PayDto> nativePay(@RequestParam("amount") String amount) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String code = sdf.format(new Date()) + UUIDUtil.getNumberRandom(5);
//        Map<String, String> res =  wechatPayService.unifiedOrder(code, amount, "积分充值", "/other/wx/integralCallback");
        Long userid = tokenService.getLoginUser().getUserid();
        R<SysUser> sysUser = sysUserClient.getSysUser(userid);
        SysUser data = sysUser.getData();
        // 生成待支付记录
        IntegralPay integralPay = new IntegralPay();
        integralPay.setUserId(data.getUserId());
//        TIntegralRule one = integralRuleService.lambdaQuery().eq(TIntegralRule::getSiteId, 0).one();
//        if (one==null){
//            return R.fail("获取支付失败,平台未设置充值积分比例");
//        }
//        String chargeCredit = one.getChargeCredit();
//        JSONObject jsonObject = JSONObject.parseObject(chargeCredit);
//        Integer num1 = jsonObject.getInteger("num1");
//        BigDecimal bigDecimal = new BigDecimal(amount);
//        // 向上取整 比如5.1 当作6 5.9也当作6
//        integralPay.setIntegralCount(bigDecimal.divide(new BigDecimal(num1), RoundingMode.UP).intValue());
//        int i = bigDecimal.multiply(new BigDecimal(num1)).intValue();
 
        BigDecimal cash = new BigDecimal(amount);
        // 获取积分兑换比例配置
        R<SysConfig> info = sysConfigClient.getInfo(8L);
        if (info == null || info.getData() == null) {
            throw new RuntimeException("获取积分兑换比例配置失败");
        }
        String configValue = info.getData().getConfigValue();
        if (StringUtils.isBlank(configValue)) {
            throw new RuntimeException("积分兑换比例配置值为空");
        }
        // 使用BigDecimal处理比例,避免精度问题
        BigDecimal ratio = new BigDecimal(configValue.trim());
        if (ratio.compareTo(BigDecimal.ZERO) <= 0) {
            throw new RuntimeException("积分兑换比例必须大于0");
        }
        // 计算积分并向下取整(Floor)
        BigDecimal points = cash.multiply(ratio);
        int i = points.setScale(0, RoundingMode.FLOOR).intValue();
        integralPay.setIntegralCount(i);
        integralPay.setUserId(userid);
        integralPay.setAmount(new BigDecimal(amount));
        integralPay.setCode(code);
        integralPay.setPayStatus(1);
        integralPay.setDelFlag(0);
        integralPay.setCreateTime(LocalDateTime.now());
        integralPayService.save(integralPay);
//        String codeUrl = res.get("code_url");
//        MyQrCodeUtil.createCodeToFile(codeUrl);
//        BufferedImage blueImage = QRCodeUtil.createImage(codeUrl);
//        MultipartFile blueFile = convert(blueImage, new Date().getTime() + UUIDUtil.getRandomCode(3) + ".PNG");
//        String s = ObsUploadUtil.obsUpload(blueFile);
//        System.err.println(s);
        String key = "ad273ceb5e1b49e68d5c565d28d1d305";/** md5密钥商户后台-商户中心-商户设置-密钥管理获取 必填!*/
        Map<String, String> map = new HashMap<String, String>();
        map.put("p0_Version", "2.5");/** 版本号 */
        map.put("p1_MerchantNo", "888122400007793");/** 商户编号 */
        map.put("p2_OrderNo", code); /**商户订单号*/
        map.put("p3_Amount", String.valueOf(amount));/**订单金额*/
        map.put("p4_Cur", "1"); /**交易币种 */
        map.put("p5_ProductName", "充值"); /** 商品名称 */
        map.put("p6_ProductDesc", "积分充值"); /** 商品名称 */
//        map.put("p7_Mp", ""); /** 如果商户请求时传递了该参数,则返回给商户时会原值传 回。 */
        map.put("p9_NotifyUrl", "http://221.182.45.100:8084/other/wx/integralCallback"); /** 服务器异步通知地址 */
        map.put("q1_FrpCode", "WEIXIN_NATIVE"); /** 微信扫码(主扫)【注:此为用户主扫,商户被扫】*/
        map.put("q4_IsShowPic", "1"); /** 是否展示二 维码图片 1表示输出*/
        map.put("q7_AppId", "wx1a4a7760be53a835"); /** 交易类型*/
        map.put("qa_TradeMerchantNo", "777165000859101"); /** 777开头的报备商户号   必填!*/
        map.put("qi_FqSellerPercen", "0"); /** 卖家承担收 费比例 目前仅支持传入 0 ,即用户承 担手续费!*/
        String Strmap = CreateLinkStringByGet1.createLinkStringByGet(map);
        // 签名
        String sign = "";
        sign = Md5_Sign.SignByMD5(Strmap, key);
        map.put("hmac", sign);/** 签名数据 */
        System.out.println("发送:" + JSON.toJSONString(map).toString());
 
        // post请求参数内容
        HttpRequester hr = new HttpRequester();
        HttpRespons HP = hr.sendPost("https://trade.joinpay.com/tradeRt/uniPay", map);
        System.out.println("接收返回参数:" + HP.getContent());
        JSONObject resPay = JSONObject.parseObject(HP.getContent());
        String rcResult = resPay.getString("rd_Pic");
        Map<String, Object> map2 = new HashMap<>();
        map2.put("rcResult", rcResult);
        PayDto payDto = new PayDto();
        payDto.setId(integralPay.getId());
        payDto.setQrCode(rcResult);
        return R.ok(payDto);
    }
    @PostMapping("/integralPayApplet")
    @ApiOperation(tags = {"2.0-积分钱包"},value = "小程序积分充值")
    public R servicePayApplet() throws Exception {
        Long userid = tokenService.getLoginUser().getUserid();
        R<SysUser> sysUser = sysUserClient.getSysUser(userid);
        SysUser data = sysUser.getData();
        List<Site> sites = siteClient.getSiteAll().getData();
        Site site = sites.stream().filter(e -> e.getId().equals(data.getSiteId())).findFirst().orElse(null);
        if (site==null){
            return R.fail("当前登录用户未绑定站点");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String code = sdf.format(new Date()) + UUIDUtil.getNumberRandom(5);
        ServicePay servicePay = new ServicePay();
        servicePay.setUserId(data.getUserId());
        servicePay.setAmount(site.getAnnualServiceFee());
        servicePay.setCode(code);
        servicePay.setPayStatus(1);
        servicePay.setPayType(1);
        servicePay.setDelFlag(0);
        servicePay.setCreateTime(LocalDateTime.now());
        servicePayService.save(servicePay);
 
 
        return wechatPayService.unifiedOrderApplet(servicePay.getId()+"",code, site.getAnnualServiceFee()+"", "服务费缴纳",data.getOpenId(), "/other/wx/serviceCallback");
    }
    public static void main(String[] args) throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String code = sdf.format(new Date()) + UUIDUtil.getNumberRandom(5);
//        Map<String, String> res =  wechatPayService.unifiedOrder(code, amount, "积分充值", "/other/wx/integralCallback");
 
//        TIntegralRule one = integralRuleService.lambdaQuery().eq(TIntegralRule::getSiteId, 0).one();
//        if (one==null){
//            return R.fail("获取支付失败,平台未设置充值积分比例");
//        }
//        String chargeCredit = one.getChargeCredit();
//        JSONObject jsonObject = JSONObject.parseObject(chargeCredit);
//        Integer num1 = jsonObject.getInteger("num1");
//        BigDecimal bigDecimal = new BigDecimal(amount);
//        // 向上取整 比如5.1 当作6 5.9也当作6
//        integralPay.setIntegralCount(bigDecimal.divide(new BigDecimal(num1), RoundingMode.UP).intValue());
//        int i = bigDecimal.multiply(new BigDecimal(num1)).intValue();
 
 
//        String codeUrl = res.get("code_url");
//        MyQrCodeUtil.createCodeToFile(codeUrl);
//        BufferedImage blueImage = QRCodeUtil.createImage(codeUrl);
//        MultipartFile blueFile = convert(blueImage, new Date().getTime() + UUIDUtil.getRandomCode(3) + ".PNG");
//        String s = ObsUploadUtil.obsUpload(blueFile);
//        System.err.println(s);
        String key = "ad273ceb5e1b49e68d5c565d28d1d305";/** md5密钥商户后台-商户中心-商户设置-密钥管理获取 必填!*/
        Map<String, String> map = new HashMap<String, String>();
        map.put("p0_Version", "2.5");/** 版本号 */
        map.put("p1_MerchantNo", "888122400007793");/** 商户编号 */
        map.put("p2_OrderNo", code); /**商户订单号*/
        map.put("p3_Amount", String.valueOf(0.01));/**订单金额*/
        map.put("p4_Cur", "1"); /**交易币种 */
        map.put("p5_ProductName", "充值"); /** 商品名称 */
        map.put("p6_ProductDesc", "积分充值"); /** 商品名称 */
//        map.put("p7_Mp", ""); /** 如果商户请求时传递了该参数,则返回给商户时会原值传 回。 */
        map.put("p9_NotifyUrl", "http://221.182.45.100:8084/other/wx/integralCallback"); /** 服务器异步通知地址 */
        map.put("q1_FrpCode", "WEIXIN_NATIVE"); /** 微信扫码(主扫)【注:此为用户主扫,商户被扫】*/
        map.put("q4_IsShowPic", "1"); /** 是否展示二 维码图片 1表示输出*/
        map.put("q7_AppId", "wx1a4a7760be53a835"); /** 交易类型*/
        map.put("qa_TradeMerchantNo", "777165000859101"); /** 777开头的报备商户号   必填!*/
        map.put("qi_FqSellerPercen", "0"); /** 卖家承担收 费比例 目前仅支持传入 0 ,即用户承 担手续费!*/
        String Strmap = CreateLinkStringByGet1.createLinkStringByGet(map);
        // 签名
        String sign = "";
        sign = Md5_Sign.SignByMD5(Strmap, key);
        map.put("hmac", sign);/** 签名数据 */
        System.out.println("发送:" + JSON.toJSONString(map).toString());
 
        // post请求参数内容
        HttpRequester hr = new HttpRequester();
        HttpRespons HP = hr.sendPost("https://trade.joinpay.com/tradeRt/uniPay", map);
        System.out.println("接收返回参数:" + HP.getContent());
        JSONObject resPay = JSONObject.parseObject(HP.getContent());
        String rcResult = resPay.getString("rd_Pic");
        Map<String, Object> map2 = new HashMap<>();
        map2.put("rcResult", rcResult);
        PayDto payDto = new PayDto();
        payDto.setQrCode(rcResult);
        System.err.println(payDto);
    }
 
    public static MultipartFile convert(BufferedImage bufferedImage, String fileName) throws IOException {
        // 将 BufferedImage 转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "png", baos);
        byte[] bytes = baos.toByteArray();
 
        // 创建 ByteArrayResource
        ByteArrayResource resource = new ByteArrayResource(bytes);
 
        // 创建 MockMultipartFile
        MockMultipartFile multipartFile = new MockMultipartFile(
                "file",
                fileName,
                "image/png",
                resource.getInputStream()
        );
 
        return multipartFile;
    }
 
    @GetMapping("/getSet")
    @ApiOperation(tags = {"2.0-积分管理"}, value = "获取积分设置")
    public R<TIntegralRule> getSet() {
        Long userid = tokenService.getLoginUser().getUserid();
        SysUser data = sysUserClient.getSysUser(userid).getData();
 
        if (data != null && data.getSiteId() != null) {
            if (data.getRoleType() == 1) {
                // 平台
                TIntegralRule res = integralRuleService.lambdaQuery().eq(TIntegralRule::getSiteId, 0).one();
                return R.ok(res);
            } else if (data.getRoleType() == 3){
                TIntegralRule res = integralRuleService.lambdaQuery().eq(TIntegralRule::getSiteId, data.getSiteId()).one();
                return R.ok(res);
            }else{
                return R.ok(new TIntegralRule());
            }
        } else {
            return R.ok(new TIntegralRule());
        }
    }
 
    @GetMapping("/getSetBySiteId")
    @ApiOperation(tags = {"2.0-积分管理"}, value = "获取积分设置")
    public R<TIntegralRule> getSetBySiteId(@RequestParam("siteId") Integer siteId) {
        TIntegralRule res = integralRuleService.lambdaQuery().eq(TIntegralRule::getSiteId, siteId).last("limit 1").one();
        return R.ok(res);
    }
 
    @PostMapping("/saveSet")
    @ApiOperation(tags = {"2.0-积分管理"}, value = "保存积分设置")
    @Log(title = "【积分管理】保存积分设置", businessType = BusinessType.INSERT)
    public R saveSet(@RequestBody TIntegralRule dto) {
        Long userid = tokenService.getLoginUser().getUserid();
        SysUser data = sysUserClient.getSysUser(userid).getData();
        TIntegralRule one;
 
        if (data.getRoleType() == 1) {
            one = integralRuleService.lambdaQuery().eq(TIntegralRule::getSiteId, 0).one();
        } else {
            one = integralRuleService.lambdaQuery().eq(TIntegralRule::getSiteId, data.getSiteId()).one();
        }
        if (one != null) {
            dto.setId(one.getId());
            dto.setSiteId(data.getSiteId());
            integralRuleService.saveOrUpdate(dto);
        } else {
            dto.setSiteId(data.getSiteId());
            integralRuleService.saveOrUpdate(dto);
        }
        return R.ok();
    }
 
}