移动系统liao
2024-10-15 94da0698c01915b1e340415e080aa03050700d97
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
/***********************************************************************
 *            Project: baifenBinfa
 *        ProjectName: 百分兵法管理系统                               
 *                Web: http://chuanyin.com                     
 *             Author:                                        
 *              Email:                               
 *         CreateTime: 202403/02   
 *        Description: 暂无
 ***********************************************************************/
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using CoreCms.Net.Configuration;
using CoreCms.Net.IRepository;
using CoreCms.Net.IRepository.UnitOfWork;
using CoreCms.Net.IServices;
using CoreCms.Net.Loging;
using CoreCms.Net.Model.Entities;
using CoreCms.Net.Model.ViewModels.Basics;
using CoreCms.Net.Model.ViewModels.UI;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
 
 
namespace CoreCms.Net.Services
{
    /// <summary>
    /// 优惠券表 接口实现
    /// </summary>
    public class CoreCmsCouponServices : BaseServices<CoreCmsCoupon>, ICoreCmsCouponServices
    {
        private readonly ICoreCmsCouponRepository _dal;
        private readonly IUnitOfWork _unitOfWork;
        private readonly IServiceProvider _serviceProvider;
 
        public CoreCmsCouponServices(IUnitOfWork unitOfWork, ICoreCmsCouponRepository dal, IServiceProvider serviceProvider)
        {
            this._dal = dal;
            _serviceProvider = serviceProvider;
            base.BaseDal = dal;
            _unitOfWork = unitOfWork;
        }
 
 
        /// <summary>
        /// 根据优惠券编码取优惠券的信息,并判断是否可用
        /// </summary>
        /// <param name="code"></param>
        /// <param name="check"></param>
        public async Task<WebApiCallBack> CodeToInfo(string[] code, bool check = false)
        {
            return await _dal.ToInfo(code, check);
        }
 
        /// <summary>
        /// 删除核销多个优惠券
        /// </summary>
        /// <param name="couponCode">优惠券码</param>
        /// <param name="orderId">使用序列</param>
        /// <returns></returns>
        public async Task<WebApiCallBack> UsedMultipleCoupon(string[] couponCode, string orderId)
        {
            var res = new WebApiCallBack() { methodDescription = "删除核销多个优惠券" };
            //判断优惠券码能否有效
            var resCodeToInfo = await CodeToInfo(couponCode, true);
            if (resCodeToInfo.status == false)
            {
                return resCodeToInfo;
            }
            var dt = DateTime.Now;
            var doHasChange = await _dal.UpdateAsync(p => new CoreCmsCoupon() { isUsed = true, usedId = orderId, updateTime = dt },
                p => p.isUsed == false && couponCode.Contains(p.couponCode));
            if (doHasChange)
            {
                res.status = true;
                res.msg = "核销使用优惠券成功";
                res.data = couponCode;
            }
            else
            {
                res.status = false;
                res.msg = "核销使用优惠券失败";
                res.data = couponCode;
            }
            return res;
        }
 
        /// <summary>
        /// 获取 我的优惠券
        /// </summary>
        /// <param name="userId">用户序列</param>
        /// <param name="promotionId">促销序列</param>
        /// <param name="display">优惠券状态编码</param>
        /// <param name="page">页码</param>
        /// <param name="limit">数量</param>
        public async Task<WebApiCallBack> GetMyCoupon(int userId, int promotionId = 0, string display = "all", int page = 1, int limit = 10)
        {
 
            return await _dal.GetMyCoupon(userId, promotionId, display, page, limit);
        }
 
        /// <summary>
        /// 用户领取优惠券 插入数据
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="promotionId"></param>
        /// <param name="promotion"></param>
        /// <param name="number">数量</param>
        /// <param name="remark">说明</param>
        /// <returns></returns>
        public async Task<WebApiCallBack> AddData(int userId, int promotionId, CoreCmsPromotion promotion, int number = 1, string remark = "接口领取")
        {
            var jm = new WebApiCallBack();
 
            var dtTime = DateTime.Now;
            var eTime = DateTime.Now;
 
            if (promotion.effectiveDays > 0)
            {
                eTime = eTime.AddDays(promotion.effectiveDays);
            }
            if (promotion.effectiveHours > 0)
            {
                eTime = eTime.AddHours(promotion.effectiveHours);
            }
 
            bool bl;
            if (number > 1)
            {
                var list = new List<CoreCmsCoupon>();
                for (var i = 0; i < number; i++)
                {
                    list.Add(new CoreCmsCoupon
                    {
                        couponCode = GeneratePromotionCode()[0],
                        promotionId = promotion.id,
                        isUsed = false,
                        userId = userId,
                        createTime = dtTime,
                        startTime = dtTime,
                        endTime = eTime,
                        remark = remark
                    });
                }
                bl = await _dal.InsertAsync(list) > 0;
            }
            else
            {
                var coupon = new CoreCmsCoupon
                {
                    couponCode = GeneratePromotionCode()[0],
                    promotionId = promotion.id,
                    isUsed = false,
                    userId = userId,
                    createTime = dtTime,
                    startTime = dtTime,
                    endTime = eTime,
                    remark = remark
                };
                bl = await _dal.InsertAsync(coupon) > 0;
            }
 
            jm.status = bl;
            jm.msg = bl ? "领取成功" : "领取失败";
 
            return jm;
        }
 
 
        /// <summary>
        /// 通过优惠券号领取优惠券
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="couponCode"></param>
        /// <returns></returns>
        public async Task<WebApiCallBack> ReceiveCoupon(int userId, string couponCode)
        {
            using var container = _serviceProvider.CreateScope();
            var promotionServices = container.ServiceProvider.GetService<ICoreCmsPromotionServices>();
 
            var jm = new WebApiCallBack();
 
            var coupon = await _dal.QueryByClauseAsync(p => p.couponCode == couponCode);
            if (coupon == null)
            {
                jm.msg = "该优惠券不存在";
                return jm;
            }
            if (!string.IsNullOrEmpty(coupon.usedId))
            {
                jm.msg = "该优惠券已被使用";
                return jm;
            }
            if (coupon.userId > 0)
            {
                jm.msg = "该优惠券已被其他人领取";
                return jm;
            }
 
            coupon.userId = userId;
            var bl = await _dal.UpdateAsync(p => new CoreCmsCoupon() { userId = userId }, p => p.id == coupon.id);
            if (bl)
            {
                var promotion = await promotionServices.QueryByIdAsync(coupon.promotionId);
                if (promotion != null)
                {
                    coupon.couponName = promotion.name;
                }
            }
            jm.status = bl;
            jm.msg = bl ? "领取成功" : "领取失败";
            jm.data = coupon;
 
            return jm;
        }
 
 
        /// <summary>
        /// 生成优惠券code 方法
        /// </summary>
        /// <param name="noOfCodes">定义一个int类型的参数 用来确定生成多少个优惠码</param>
        /// <param name="excludeCodesArray">定义一个exclude_codes_array类型的数组</param>
        /// <param name="codeLength">定义一个code_length的参数来确定优惠码的长度</param>
        /// <returns></returns>
        public List<string> GeneratePromotionCode(int noOfCodes = 1, List<string> excludeCodesArray = null, int codeLength = 10)
        {
            char[] constant =
            {
                '0','1','2','3','4','5','6','7','8','9',
                'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
                'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'
            };
            var promotionCodes = new List<string>();  //这个数组用来接收生成的优惠码
            Random rd = new Random();
            for (int i = 0; i < noOfCodes; i++)
            {
                var code = "";
                for (int j = 0; j < codeLength; j++)
                {
                    code += constant[rd.Next(62)];
                }
                //如果生成的6位随机数不再我们定义的$promotion_codes函数里面
                if (!promotionCodes.Contains(code))
                {
                    if (excludeCodesArray != null && excludeCodesArray.Any())
                    {
                        if (!excludeCodesArray.Contains(code))
                        {
                            promotionCodes.Add(code);//将优惠码赋值给数组
                        }
                        else
                        {
                            i--;
                        }
                    }
                    else
                    {
                        promotionCodes.Add(code);//将优惠码赋值给数组
                    }
                }
                else
                {
                    i--;
                }
            }
            return promotionCodes;
        }
 
        /// <summary>
        ///     根据条件查询分页数据及导航数据
        /// </summary>
        /// <param name="predicate">判断集合</param>
        /// <param name="orderByType">排序方式</param>
        /// <param name="isToPage">是否分页</param>
        /// <param name="pageIndex">当前页面索引</param>
        /// <param name="pageSize">分布大小</param>
        /// <param name="orderByExpression"></param>
        /// <returns></returns>
        public async Task<IPageList<CoreCmsCoupon>> QueryPageMapperAsync(Expression<Func<CoreCmsCoupon, bool>> predicate,
            Expression<Func<CoreCmsCoupon, object>> orderByExpression, OrderByType orderByType, bool isToPage = false, int pageIndex = 1,
            int pageSize = 20)
        {
 
            return await _dal.QueryPageMapperAsync(predicate, orderByExpression, orderByType, isToPage, pageIndex, pageSize);
        }
 
        /// <summary>
        ///     重写数据并获取相关
        /// </summary>
        /// <param name="predicate">判断集合</param>
        /// <returns></returns>
        public async Task<List<CoreCmsCoupon>> QueryWithAboutAsync(Expression<Func<CoreCmsCoupon, bool>> predicate)
        {
            return await _dal.QueryWithAboutAsync(predicate);
        }
 
        /// <summary>
        ///     重写根据条件查询分页数据
        /// </summary>
        /// <param name="predicate">判断集合</param>
        /// <param name="orderByType">排序方式</param>
        /// <param name="pageIndex">当前页面索引</param>
        /// <param name="pageSize">分布大小</param>
        /// <param name="orderByExpression"></param>
        /// <param name="blUseNoLock">是否使用WITH(NOLOCK)</param>
        /// <returns></returns>
        public async Task<IPageList<CoreCmsCoupon>> QueryPageAsync(Expression<Func<CoreCmsCoupon, bool>> predicate,
            Expression<Func<CoreCmsCoupon, object>> orderByExpression, OrderByType orderByType, int pageIndex = 1,
            int pageSize = 20, bool blUseNoLock = false)
        {
            return await _dal.QueryPageAsync(predicate, orderByExpression, orderByType, pageIndex, pageSize, blUseNoLock);
        }
 
        /// <summary>
        /// 获取 我的优惠券可用数量
        /// </summary>
        /// <param name="userId">用户序列</param>
        public async Task<int> GetMyCouponCount(int userId)
        {
            return await _dal.GetMyCouponCount(userId);
        }
 
        /// <summary>
        ///  优惠券返还
        /// </summary>
        /// <param name="couponCodes">优惠券数组</param>
        public async Task<WebApiCallBack> CancelReturnCoupon(string couponCodes)
        {
            var jm = new WebApiCallBack();
            jm.code = 0;
            var bl = false;
            var ids = couponCodes.Split(",");
            var list = await _dal.QueryListByClauseAsync(p => ids.Contains(p.couponCode));
            if (list != null && list.Any())
            {
                var newList = new List<CoreCmsCoupon>();
                list.ForEach(p =>
                {
                    var eTime = p.endTime.AddMinutes(1);
                    newList.Add(new CoreCmsCoupon()
                    {
                        couponCode = GeneratePromotionCode()[0],
                        promotionId = p.promotionId,
                        isUsed = false,
                        userId = p.userId,
                        createTime = DateTime.Now,
                        remark = "优惠券返还",
                        startTime = p.startTime,
                        endTime = eTime
                    });
                });
                bl = await _dal.InsertAsync(newList) > 0;
                jm.status = bl;
                jm.msg = bl ? "返还成功" : "返还失败";
            }
            return jm;
        }
 
    }
}