admin
2019-01-08 c84d8ecd97d111b01db9cfd807300d0491a95bc8
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
package com.yeshi.fanli.service.impl.order;
 
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
 
import javax.annotation.Resource;
 
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
 
import com.yeshi.fanli.dao.mybatis.ThreeSaleGiftMapper;
import com.yeshi.fanli.dao.mybatis.order.OrderItemMapper;
import com.yeshi.fanli.dao.mybatis.order.OrderMapper;
import com.yeshi.fanli.dao.order.OrderDao;
import com.yeshi.fanli.dao.order.PidOrderDao;
import com.yeshi.fanli.entity.bus.user.HongBao;
import com.yeshi.fanli.entity.bus.user.Order;
import com.yeshi.fanli.entity.bus.user.OrderItem;
import com.yeshi.fanli.entity.bus.user.ThreeSaleGift;
import com.yeshi.fanli.entity.taobao.PidOrder;
import com.yeshi.fanli.entity.taobao.TaoBaoWeiQuanOrder;
import com.yeshi.fanli.exception.ObjectStateException;
import com.yeshi.fanli.service.inter.config.ConfigService;
import com.yeshi.fanli.service.inter.hongbao.HongBaoService;
import com.yeshi.fanli.service.inter.hongbao.ThreeSaleGiftService;
import com.yeshi.fanli.service.inter.hongbao.ThreeSaleSerivce;
import com.yeshi.fanli.service.inter.order.OrderItemServcie;
import com.yeshi.fanli.service.inter.order.OrderService;
import com.yeshi.fanli.service.inter.user.ShareManageService;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.TimeUtil;
import com.yeshi.fanli.util.Utils;
import org.yeshi.utils.NumberUtil;
 
@Service
public class OrderServiceImpl implements OrderService {
 
    @Resource
    private OrderDao orderDao;
 
    @Resource
    private OrderService orderService;
 
    @Resource
    private ShareManageService shareManageService;
 
    @Resource
    private HongBaoService hongBaoService;
 
    @Resource
    private ConfigService configService;
 
    @Resource
    private ThreeSaleSerivce threeSaleSerivce;
 
    @Resource
    private OrderItemServcie orderItemService;
 
    @Resource
    private ThreeSaleGiftService threeSaleGiftService;
 
    @Resource
    private OrderMapper orderMapper;
 
    @Resource
    private OrderItemMapper orderItemMapper;
 
    @Resource
    private PidOrderDao pidOrderDao;
 
    @Resource
    private ThreeSaleGiftMapper threeSaleGiftMapper;
 
    public List<Order> getOrderByUid(int index, long uid) {
 
        int start = index * Constant.PAGE_SIZE;
 
        return orderDao.list("from Order o where o.userInfo.id=? and o.money>0 order by o.createtime desc", start,
                Constant.PAGE_SIZE, new Serializable[] { uid });
 
    }
 
    public long getOrderCountByTime(long startTime, long endTime) {
 
        long count = orderDao.getCount("select count(*) from Order where createtime >=? and  createtime < ?",
                new Serializable[] { startTime, endTime });
 
        return count;
    }
 
    @Transactional(propagation = Propagation.NESTED, rollbackFor = Exception.class)
    public boolean addOrder(Order order) throws Exception {
        order.setVersion(2);
        WriteLock writeLock = orderLock.writeLock();
        // 保存订单
        // long oid;
        try {
            writeLock.lock();
            Order find = findOrderByOrderIdAndType(order.getOrderId(), order.getOrderType());
            if (find != null) {
                return false;
            }
            // 查找是否存在分享赚订单
 
            List<PidOrder> orderList = pidOrderDao.list("from PidOrder p where p.orderId=?",
                    new Serializable[] { order.getOrderId() });
            if (orderList != null && orderList.size() > 0)
                return false;
 
            orderDao.save(order);
        } finally {
            writeLock.unlock();
        }
        // UserInfo userInfo = order.getUserInfo();
        // // 发红包啦
        // HongBao hongBao = HongBaoFactory.createHongBao(new BigDecimal(0),
        // oid, null,
        // order.getUserInfo(), Constant.TAOBAO);
        // hongBaoService.save(hongBao);
        // // 看是不是被传销进来的
        // UserInfo boss1 = threeSaleSerivce.getBoss(userInfo.getId());
        // if (boss1 != null) {
        // // 给上线发个红包
        // HongBao oneSaleHongBao = HongBaoFactory.createHongBao(new
        // BigDecimal(0), null,
        // hongBao, boss1, Constant.ONESALE);
        // hongBaoService.save(oneSaleHongBao);
        // // 继续看是不是被传销进来的
        // UserInfo boss2 = threeSaleSerivce.getBoss(boss1.getId());
        // if (boss2 != null) {
        // // 再发个红包给传销头头
        // HongBao twoSaleHongBao = HongBaoFactory.createHongBao(new
        // BigDecimal(0), null,
        // hongBao, boss2, Constant.TWOSALE);
        // hongBaoService.save(twoSaleHongBao);
        // }
        // }
        return true;
    }
 
    public boolean isfirstOrder(long uid) {
 
        List<Order> list = orderDao.list("from Order o where o.userInfo.id = ? and o.state = 1 ", 0, 1,
                new Serializable[] { uid });
        if (list.size() == 0) {
            return true;
        }
        return false;
    }
 
    public int getCount(long uid) {
        Long lcount = orderDao.getCount("select count(o.id) from Order o where o.userInfo.id = ? ",
                new Serializable[] { uid });
        return lcount.intValue();
    }
 
    public List<Order> getOrderList(String key, int index) {
 
        int start = index * Constant.PAGE_SIZE;
 
        boolean b = NumberUtil.isNumeric(key);
        if (b) {
            long uid = Long.parseLong(key);
            return orderDao.list(
                    "from Order o where o.userInfo.id = ? or o.userInfo.nickName like ? order by o.id desc ", start,
                    Constant.PAGE_SIZE, new Serializable[] { uid, "%" + key + "%" });
        }
        return orderDao.list("from Order o where o.userInfo.nickName like ? order by o.id desc", start,
                Constant.PAGE_SIZE, new Serializable[] { "%" + key + "%" });
 
    }
 
    public int getCount() {
        Long lcount = orderDao.getCount("select count(o.id) from Order o");
        return lcount.intValue();
    }
 
    @SuppressWarnings("unchecked")
    public Map<String, Integer> getnewOrderByDate(final int days, Date date) {
 
        final Map<String, Integer> map = new HashMap<String, Integer>();
        long timestampms = date.getTime();
        final long timestamps = timestampms / 1000;
        List<String> list = TimeUtil.getEmupDate(days, timestampms);
        for (String dataStr : list) {
            map.put(dataStr, 0);
        }
        return (Map<String, Integer>) orderDao.excute(new HibernateCallback<Map<String, Integer>>() {
 
            public Map<String, Integer> doInHibernate(Session session) throws HibernateException {
                SQLQuery sqlQuery = session.createSQLQuery(
                        "SELECT DATE(FROM_UNIXTIME(createtime/1000)) c,COUNT(*) FROM yeshi_ec_order WHERE DATE_SUB(FROM_UNIXTIME(?), INTERVAL ? DAY) <= DATE(FROM_UNIXTIME(createtime/1000)) AND DATE(FROM_UNIXTIME(createtime/1000)) <= FROM_UNIXTIME(?) GROUP BY c");
                sqlQuery.setParameter(0, timestamps);
                sqlQuery.setParameter(1, days);
                sqlQuery.setParameter(2, timestamps);
                List<Object[]> list = sqlQuery.list();
                for (Object[] objArr : list) {
                    map.put(TimeUtil.getSimpleDate((Date) objArr[0]), ((BigInteger) objArr[1]).intValue());
                }
                return map;
            }
        });
    }
 
    @SuppressWarnings("unchecked")
    public Map<String, Integer> getnewOrderByMonth(final int months, final Date endDate) {
        List<String> monthList = Utils.getDateMonthList(months, endDate);
        final Map<String, Integer> map = new HashMap<String, Integer>();
        for (String monthStr : monthList) {
            map.put(monthStr, 0);
        }
        return (Map<String, Integer>) orderDao.excute(new HibernateCallback<Map<String, Integer>>() {
 
            public Map<String, Integer> doInHibernate(Session session) throws HibernateException {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(endDate);
                calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
                calendar.set(Calendar.DAY_OF_MONTH, 1);
                long curTime = (calendar.getTime().getTime()) / 1000;
                SQLQuery sqlQuery = session.createSQLQuery(
                        "SELECT DATE_FORMAT(FROM_UNIXTIME(createtime/1000),'%Y-%m') months,COUNT(*) FROM yeshi_ec_order WHERE DATE(FROM_UNIXTIME(createtime/1000)) >= DATE_SUB(FROM_UNIXTIME(?),INTERVAL ? MONTH) AND DATE(FROM_UNIXTIME(createtime/1000)) < FROM_UNIXTIME(?) GROUP BY months");
                sqlQuery.setParameter(0, curTime);
                sqlQuery.setParameter(1, months);
                sqlQuery.setParameter(2, curTime);
                List<Object[]> list = sqlQuery.list();
                for (Object[] objArr : list) {
                    map.put((String) objArr[0], ((BigInteger) objArr[1]).intValue());
                }
                return map;
            }
        });
    }
 
    @SuppressWarnings("unchecked")
    public Map<String, Integer> getOrderTotalByDate(int days, Date date) {
 
        final Map<String, Integer> map = new HashMap<String, Integer>();
        long timestampms = date.getTime();
        final List<String> list = TimeUtil.getEmupDate(days, timestampms);
        for (String dataStr : list) {
            map.put(dataStr, 0);
        }
        return (Map<String, Integer>) orderDao.excute(new HibernateCallback<Map<String, Integer>>() {
 
            public Map<String, Integer> doInHibernate(Session session) throws HibernateException {
                StringBuffer sb = new StringBuffer();
                int ii = 0;
                for (String day : list) {
                    if (ii == 0) {
                        sb.append("SELECT '" + day + "' AS t,IFNULL(SUM(a.s),0) FROM yeshi_ec_order_day a WHERE a.c<= '"
                                + day + "' ");
                    } else {
                        sb.append("UNION ALL SELECT '" + day
                                + "' AS t,IFNULL(SUM(a.s),0) FROM yeshi_ec_order_day a WHERE a.c<= '" + day + "' ");
                    }
                    ii++;
                }
 
                SQLQuery sqlQuery = session.createSQLQuery(sb.toString());
                List<Object[]> list = sqlQuery.list();
                for (Object[] objArr : list) {
                    map.put(String.valueOf(objArr[0]), ((BigDecimal) objArr[1]).intValue());
                }
                return map;
            }
        });
    }
 
    @SuppressWarnings("unchecked")
    public Map<String, Integer> getOrderTotalByMonth(int months, Date date) {
        final List<String> monthList = Utils.getDateMonthList(months, date);
        final Map<String, Integer> map = new HashMap<String, Integer>();
        for (String monthStr : monthList) {
            map.put(monthStr, 0);
        }
        return (Map<String, Integer>) orderDao.excute(new HibernateCallback<Map<String, Integer>>() {
 
            public Map<String, Integer> doInHibernate(Session session) throws HibernateException {
 
                StringBuffer sb = new StringBuffer();
                int ii = 0;
                for (String month : monthList) {
                    if (ii == 0) {
                        sb.append("SELECT '" + month
                                + "' AS t,IFNULL(SUM(a.s),0) FROM yeshi_ec_order_month a WHERE a.months<= '" + month
                                + "' ");
                    } else {
                        sb.append("UNION ALL SELECT '" + month
                                + "' AS t,IFNULL(SUM(a.s),0) FROM yeshi_ec_order_month a WHERE a.months<= '" + month
                                + "' ");
                    }
                    ii++;
                }
 
                SQLQuery sqlQuery = session.createSQLQuery(sb.toString());
                List<Object[]> list = sqlQuery.list();
                for (Object[] objArr : list) {
                    map.put((String) objArr[0], ((BigDecimal) objArr[1]).intValue());
                }
                return map;
            }
        });
    }
 
    public Order getOrder(final String orderid, final int orderType) {
        return (Order) orderDao.excute(new HibernateCallback<Order>() {
 
            public Order doInHibernate(Session session) throws HibernateException {
                Query query = session.createQuery("from Order o where o.orderId = ? and o.orderType = ? ");
                query.setParameter(0, orderid);
                query.setParameter(1, orderType);
                List<Order> list = query.list();
                if (list.size() > 0) {
                    return list.get(0);
                }
                return null;
            }
        });
    }
 
    @Transactional(propagation = Propagation.REQUIRED)
    public void failureOrder(final String orderid, final int orderType) throws ObjectStateException {
        // 失效的订单
        List<Order> orderList = orderService.setOrderState(orderid, orderType);
        if (orderList != null && orderList.size() > 0) {
            for (Order order : orderList) {
                // 找到这个失效订单以前发的红包
                List<HongBao> hongBaoList = hongBaoService.findHongBaoByOrderList(order.getId());
                if (hongBaoList != null)
                    for (HongBao hongBao : hongBaoList)
                        // 把红包搞成失效的,分销的红包也要搞失效
                        hongBaoService.relevantInvalid(hongBao.getId());
            }
        }
    }
 
    @Transactional
    public void failureOrderWithWeiQuan(final String orderid, final int orderType) throws ObjectStateException {
        // 失效的订单
        List<Order> orderList = orderService.setOrderState(orderid, orderType);
        if (orderList != null && orderList.size() > 0) {
            for (Order order : orderList) {
                // if (order.getState() == Order.STATE_SHIXIAO)
                // continue;
                // 找到这个失效订单以前发的红包
                List<HongBao> hongBaoList = hongBaoService.findHongBaoByOrderList(order.getId());
                if (hongBaoList != null)
                    for (HongBao hongBao : hongBaoList)
                        // 把红包搞成失效的,分销的红包也要搞失效
                        hongBaoService.relevantInvalidVersion2(hongBao.getId());
 
                List<OrderItem> orderItremList = orderItemService.findByOrderId(order.getId());
                if (orderItremList != null)
                    for (OrderItem orderItem : orderItremList) {
                        OrderItem updateOrderItem = new OrderItem(orderItem.getId());
 
                        updateOrderItem.setState(OrderItem.STATE_TUIKUAN);
                        // 查询
                        List<ThreeSaleGift> giftList = threeSaleGiftService.findThreeSaleGiftList(orderItem.getId());
                        for (ThreeSaleGift tsg : giftList) {
                            if (tsg.getState().intValue() != OrderItem.STATE_DAOZHANG
                                    && tsg.getState().intValue() != OrderItem.STATE_SHOUHOU) {
                                ThreeSaleGift updateTsg = new ThreeSaleGift();
                                updateTsg.setId(tsg.getId());
                                updateTsg.setState(OrderItem.STATE_TUIKUAN);
                                threeSaleGiftMapper.updateByPrimaryKeySelective(updateTsg);
                            }
                        }
                        orderItemMapper.updateByPrimaryKeySelective(updateOrderItem);
                    }
                Order updateOrder = new Order();
                updateOrder.setId(order.getId());
                updateOrder.setState(Order.STATE_SHIXIAO);
                orderMapper.updateByPrimaryKeySelective(updateOrder);
            }
        }
    }
 
    @Transactional
    public List<Order> setOrderState(final String orderid, final int orderType) {
        List<Order> orderList = orderMapper.selectOrderByOrderIdAndOrderType(orderid, orderType);
        if (orderList != null)
            for (Order order : orderList) {
                if (order.getDrawbackTime() == null || order.getDrawbackTime() <= 0) {
                    Order updateOrder = new Order();
                    updateOrder.setId(order.getId());
                    updateOrder.setDrawbackTime(java.lang.System.currentTimeMillis());
                    updateOrder.setState(Order.STATE_SHIXIAO);
                    orderMapper.updateByPrimaryKeySelective(updateOrder);
                    order.setDrawbackTime(updateOrder.getDrawbackTime());
                    order.setState(updateOrder.getState());
                }
            }
        return orderList;
    }
 
    public int getCount(String key) {
        if (NumberUtil.isNumeric(key)) {
 
            if (key.trim().length() < 18) {
                long lk = Long.parseLong(key);
                return (int) orderDao.getCount(
                        "select count(*) from Order o where o.userInfo.id = ? or o.userInfo.nickName like ? ",
                        new Serializable[] { lk, "%" + key + "%" });
            } else {
                return (int) orderDao.getCount("select count(*) from Order o where  o.orderId like ? ",
                        new Serializable[] { "%" + key + "%" });
            }
 
        } else {
            return (int) orderDao.getCount("select count(*) from Order o where o.userInfo.nickName like ? ",
                    new Serializable[] { "%" + key + "%" });
        }
    }
 
    public Order find(long id) {
        return orderDao.find(Order.class, id);
    }
 
    public void update(Order findOrder) {
        orderDao.update(findOrder);
    }
 
    @Override
    public Order findOrderByOrderIdAndType(String orderId, int type) {
        List<Order> list = orderDao.list("from Order o where o.orderId=? and o.orderType=?", 0, 1,
                new Serializable[] { orderId, type });
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }
 
    @Override
    public Order findOrderByOrderIdAndTypeAndVersion(String orderId, int type, int version) {
        List<Order> list = orderDao.list("from Order o where o.orderId=? and o.orderType=? and o.version=?", 0, 1,
                new Serializable[] { orderId, type, version });
        if (list.size() > 0) {
            return list.get(0);
        }
        return null;
    }
 
    @Override
    public Order getSystemOrderByUid(int type, long uid) {
 
        List<Order> list = orderDao.list(
                "from Order o where o.userInfo.id = ? and o.orderType = ? and o.beizhu = '系统添加'", 0, 1,
                new Serializable[] { uid, type });
 
        if (list.size() > 0) {
            return list.get(0);
        }
 
        return null;
    }
 
    @Override
    public List<Order> findOldOrderListAll() {
 
        List<Order> list = orderDao.list("from Order or where or.version=1");
 
        return list;
    }
 
    // 处理维权订单
    @Override
    public void update(TaoBaoWeiQuanOrder order) {
        try {
            failureOrderWithWeiQuan(order.getOrderId(), Order.ORDER_TYPE_TAOBAO);
        } catch (ObjectStateException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public Order getLatestOrder() {
        List<Order> orderList = orderDao.list("from Order order order by order.thirdCreateTime desc", 0, 1, null);
        if (orderList == null || orderList.size() == 0)
            return null;
        return orderList.get(0);
    }
 
}