purchasemgr.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. package purchase
  2. import (
  3. "fmt"
  4. "math/rand"
  5. "sync"
  6. "time"
  7. "bet24.com/log"
  8. "bet24.com/servers/common"
  9. "bet24.com/servers/coreservice/serviceconfig"
  10. item "bet24.com/servers/micros/item_inventory/proto"
  11. cash "bet24.com/servers/micros/money/proto"
  12. mail "bet24.com/servers/micros/userservices/proto"
  13. )
  14. type purchaseMgr struct {
  15. sn int // 序号
  16. numbers [][]int // 抽奖码
  17. index int // 索引
  18. user_list map[int]*userPurchase // 用户列表
  19. beginTime time.Time // 开始时间
  20. endTime time.Time // 结束时间
  21. luckNumber int // 中奖码
  22. status int // 状态(0=空闲 1=活动中 3=派奖 2=结束)
  23. lock *sync.RWMutex
  24. }
  25. type userPurchase struct {
  26. UserId int // 用户id
  27. Numbers []int // 号码
  28. }
  29. func newPurchaseMgr() *purchaseMgr {
  30. mgr := new(purchaseMgr)
  31. mgr.user_list = make(map[int]*userPurchase)
  32. mgr.lock = &sync.RWMutex{}
  33. mgr.load()
  34. go mgr.refresh()
  35. log.Debug("purchase manager running")
  36. return mgr
  37. }
  38. func (this *purchaseMgr) load() {
  39. // log.Debug("purchase.load 开始加载数据")
  40. // 从数据库拉取未结束的活动数据
  41. sn, beginTime, endTime, luckNumber, status := sysInfo()
  42. if sn <= 0 {
  43. log.Debug("purchase.load not data")
  44. return
  45. }
  46. // 获取用户数据
  47. userList := userInfo(sn)
  48. index := len(userList)
  49. numbers := this.initNumbers(userList)
  50. this.lock.Lock()
  51. defer this.lock.Unlock()
  52. this.sn = sn
  53. this.beginTime = beginTime
  54. this.endTime = endTime
  55. this.luckNumber = luckNumber
  56. this.status = status
  57. this.user_list = userList
  58. this.index = index
  59. this.numbers = numbers
  60. //log.Debug("purchase.load 加载数据 data ok ==> sn=%d beginTime=%s endTime=%s luckNumber=%d status=%d index=%d numbers=%v",
  61. // this.sn, this.beginTime, this.end, this.luckNumber, this.status, this.index, this.numbers)
  62. }
  63. func (this *purchaseMgr) refresh() {
  64. ticker := time.NewTicker(2 * time.Second)
  65. go func(t *time.Ticker) {
  66. for {
  67. select {
  68. case <-t.C:
  69. this.check()
  70. }
  71. }
  72. }(ticker)
  73. }
  74. func (this *purchaseMgr) check() {
  75. // 派奖中(什么都不处理)
  76. if this.status == STATUS_PRIZE {
  77. return
  78. }
  79. // 活动中
  80. if this.status == STATUS_ACTIVITY {
  81. // 当期还没结束
  82. if this.getNow().After(this.beginTime) && this.getNow().Before(this.endTime) {
  83. return
  84. }
  85. // 结束
  86. this.end()
  87. return
  88. }
  89. // 是否有效期
  90. if !this.isValid() {
  91. return
  92. }
  93. // 开启活动
  94. this.open()
  95. return
  96. }
  97. func (this *purchaseMgr) getNow() time.Time {
  98. // 转换成相同的格式
  99. now, _ := time.Parse(common.Layout, time.Now().Format(common.Layout))
  100. return now
  101. }
  102. // 是否有效
  103. func (this *purchaseMgr) isValid() bool {
  104. // 开始时间
  105. start, err := time.Parse(common.Layout, fmt.Sprintf("%s 00:00:00", time.Now().Format("2006-01-02")))
  106. if err != nil {
  107. log.Error("purchaseMgr startTime fail %v", err)
  108. return false
  109. }
  110. // log.Debug("isValid start = %v", start)
  111. if serviceconfig.Server.PurchaseCfg.BeginHour == "" {
  112. return false
  113. }
  114. beginHour, err := time.ParseDuration(serviceconfig.Server.PurchaseCfg.BeginHour)
  115. if err != nil {
  116. log.Error("purchaseMgr beginHour fail %v", err)
  117. return false
  118. }
  119. // log.Debug("isValid beginHour = %v", beginHour)
  120. start = start.Add(beginHour)
  121. // log.Debug("isValid ==> start = %v", start)
  122. // 结束时间
  123. end, err := time.Parse(common.Layout, fmt.Sprintf("%s 00:00:00", time.Now().Format("2006-01-02")))
  124. if err != nil {
  125. log.Error("purchaseMgr endTime fail %v", err)
  126. return false
  127. }
  128. // log.Debug("isValid end = %v", end)
  129. if serviceconfig.Server.PurchaseCfg.EndHour == "" {
  130. return false
  131. }
  132. endHour, err := time.ParseDuration(serviceconfig.Server.PurchaseCfg.EndHour)
  133. if err != nil {
  134. log.Error("purchaseMgr endHour fail %v", err)
  135. return false
  136. }
  137. // log.Debug("isValid endHour = %v", endHour)
  138. end = end.Add(endHour)
  139. // log.Debug("isValid ==> end = %v", end)
  140. // 不在活动时间段内
  141. if this.getNow().Before(start) || this.getNow().After(end) {
  142. //log.Debug("purchaseMgr.isValid 不在活动时间段内 start=%v end=%v this.getNow()=%v ==> %+v",
  143. // start, end, this.getNow(), this)
  144. return false
  145. }
  146. // log.Debug("purchaseMgr.isValid 活动有效期")
  147. return true
  148. }
  149. // 开启
  150. func (this *purchaseMgr) open() {
  151. duration, err := time.ParseDuration(serviceconfig.Server.PurchaseCfg.Duration)
  152. if err != nil {
  153. log.Error("open duration fail %v", err)
  154. return
  155. }
  156. this.lock.Lock()
  157. this.sn++
  158. this.numbers = this.initNumbers(nil)
  159. this.index = 0
  160. this.user_list = make(map[int]*userPurchase, 0)
  161. this.beginTime = this.getNow()
  162. this.endTime = this.getNow().Add(duration)
  163. this.luckNumber = 0
  164. this.status = STATUS_ACTIVITY
  165. this.lock.Unlock()
  166. // 写数据(开启,活动中状态)
  167. go open(this.sn, this.beginTime, this.endTime, this.luckNumber, this.status)
  168. //log.Debug("purchasemgr.open 已开启 sn=%d beginTime=%s endTime=%s status=%d numbers=%v index=%d",
  169. // this.sn, this.beginTime, this.endTime, this.status, this.numbers, this.index)
  170. return
  171. }
  172. // 初始化
  173. func (this *purchaseMgr) initNumbers(list map[int]*userPurchase) [][]int {
  174. var numbers [][]int
  175. for i := 1; i <= serviceconfig.Server.PurchaseCfg.MaxNumber; i++ {
  176. flag := false
  177. // 已经存在的抽奖码排除
  178. for _, j := range list {
  179. for _, v := range j.Numbers {
  180. // 该抽奖码已存在
  181. if v == i {
  182. flag = true
  183. break
  184. }
  185. }
  186. if flag {
  187. break
  188. }
  189. }
  190. if flag {
  191. continue
  192. }
  193. var items []int
  194. items = append(items, i, 0)
  195. numbers = append(numbers, items)
  196. }
  197. count := len(numbers)
  198. // 打乱顺序
  199. for i := count - 1; i > 0; i-- {
  200. j := rand.Intn(i)
  201. numbers[i], numbers[j] = numbers[j], numbers[i]
  202. }
  203. // 加在头部
  204. for _, v := range list {
  205. for _, k := range v.Numbers {
  206. var items []int
  207. items = append(items, k, v.UserId)
  208. numbers = append([][]int{items}, numbers...)
  209. }
  210. }
  211. return numbers
  212. }
  213. // 结束
  214. func (this *purchaseMgr) end() {
  215. if serviceconfig.Server.PurchaseCfg.MaxNumber <= 0 {
  216. return
  217. }
  218. // 生成随机号码
  219. index := rand.Intn(serviceconfig.Server.PurchaseCfg.MaxNumber)
  220. this.lock.Lock()
  221. this.status = STATUS_PRIZE
  222. this.luckNumber = this.numbers[index][0]
  223. userId := this.numbers[index][1]
  224. sn := this.sn
  225. luckNumber := this.luckNumber
  226. this.lock.Unlock()
  227. // 写数据(派奖状态)
  228. update(this.sn, this.luckNumber, this.status)
  229. // 邮件派奖
  230. this.sendPrize(userId, sn, luckNumber)
  231. this.lock.Lock()
  232. this.status = STATUS_END
  233. this.lock.Unlock()
  234. // 写数据(结束状态)
  235. go update(this.sn, this.luckNumber, this.status)
  236. log.Debug("purchasemgr.end sn=%d status=%d luckNumber=%d userId=%d", this.sn, this.status, this.luckNumber, userId)
  237. return
  238. }
  239. // 邮件派奖
  240. func (this *purchaseMgr) sendPrize(userId, sn, luckNumber int) {
  241. for _, v := range this.user_list {
  242. if v.UserId == userId && v.UserId > 0 {
  243. var items []item.ItemPack
  244. items = append(items, item.ItemPack{
  245. ItemId: serviceconfig.Server.PurchaseCfg.ItemId,
  246. Count: serviceconfig.Server.PurchaseCfg.AwardAmount,
  247. })
  248. // 发送中奖通知
  249. mail.SendSysMail(v.UserId, &mail.SysMail{
  250. Id: 0,
  251. Title: serviceconfig.Server.PurchaseCfg.SuccessTitle,
  252. Content: fmt.Sprintf(serviceconfig.Server.PurchaseCfg.SuccessContent, sn, serviceconfig.Server.PurchaseCfg.AwardAmount),
  253. Status: 0,
  254. SourceName: "100K购",
  255. Crdate: common.GetTimeStamp(),
  256. Tools: items,
  257. })
  258. continue
  259. }
  260. // 发送未中奖通知
  261. mail.SendSysMail(v.UserId, &mail.SysMail{
  262. Id: 0,
  263. Title: serviceconfig.Server.PurchaseCfg.FailTitle,
  264. Content: fmt.Sprintf(serviceconfig.Server.PurchaseCfg.FailContent, sn, luckNumber),
  265. Status: 0,
  266. SourceName: "100K购",
  267. Crdate: common.GetTimeStamp(),
  268. Tools: nil,
  269. })
  270. }
  271. return
  272. }
  273. // 投注(返回操作结果\抽奖码)
  274. func (this *purchaseMgr) bet(userId int, ipAddress string) (int, int) {
  275. this.lock.RLock()
  276. // 活动还没开启
  277. if this.status != STATUS_ACTIVITY {
  278. this.lock.RUnlock()
  279. return 11, 0
  280. }
  281. // 判断是否有空闲
  282. if this.index >= serviceconfig.Server.PurchaseCfg.MaxNumber {
  283. this.lock.RUnlock()
  284. return 12, 0
  285. }
  286. this.lock.RUnlock()
  287. // 扣除金币
  288. if !cash.ReduceMoney(userId, serviceconfig.Server.PurchaseCfg.GoldFee, common.LOGTYPE_PURCHASE, "100K购", fmt.Sprintf("100K购第%d期", this.sn), ipAddress) {
  289. log.Release("purchasemgr.bet userId[%d] bet[%d] not enough gold", userId, serviceconfig.Server.PurchaseCfg.GoldFee)
  290. return 13, 0
  291. }
  292. this.lock.Lock()
  293. number := this.numbers[this.index][0]
  294. this.numbers[this.index][1] = userId
  295. this.index++
  296. this.lock.Unlock()
  297. this.addUser(userId, number)
  298. // 写数据
  299. go bet(userId, this.sn, number)
  300. return 1, number
  301. }
  302. // 记录用户
  303. func (this *purchaseMgr) addUser(userId, number int) {
  304. if userId <= 0 || number <= 0 {
  305. log.Release("purchasemgr.addUser userId[%d] number[%d] 无效数据", userId, number)
  306. return
  307. }
  308. this.lock.RLock()
  309. info, ok := this.user_list[userId]
  310. this.lock.RUnlock()
  311. if !ok {
  312. info = &userPurchase{
  313. UserId: userId,
  314. Numbers: nil,
  315. }
  316. this.lock.Lock()
  317. this.user_list[userId] = info
  318. this.lock.Unlock()
  319. }
  320. info.Numbers = append(info.Numbers, number)
  321. return
  322. }
  323. // 获取当前信息(期数\元宝数量\倒计时\状态\消耗金币)
  324. func (this *purchaseMgr) getSysInfo() (int, int, int64, int, int) {
  325. this.lock.RLock()
  326. defer this.lock.RUnlock()
  327. return this.sn, serviceconfig.Server.PurchaseCfg.AwardAmount,
  328. this.endTime.Sub(this.getNow()).Milliseconds() / 1000, this.status,
  329. serviceconfig.Server.PurchaseCfg.GoldFee
  330. }
  331. // 获取用户抽奖码信息
  332. func (this *purchaseMgr) getUserInfo(userId int) []int {
  333. this.lock.RLock()
  334. info, ok := this.user_list[userId]
  335. this.lock.RUnlock()
  336. if !ok {
  337. return nil
  338. }
  339. return info.Numbers
  340. }
  341. // 小红点提示
  342. func (this *purchaseMgr) checkTip() bool {
  343. this.lock.RLock()
  344. defer this.lock.RUnlock()
  345. return this.status == STATUS_ACTIVITY
  346. }