package shop import ( "go_dreamfactory/comm" "go_dreamfactory/pb" cfg "go_dreamfactory/sys/configure/structs" "go_dreamfactory/utils" "math" "time" "go.mongodb.org/mongo-driver/bson/primitive" "google.golang.org/protobuf/proto" ) //参数校验 func (this *apiComp) BuyCheck(session comm.IUserSession, req *pb.ShopBuyReq) (code pb.ErrorCode) { if req.ShopType == 0 || req.GoodsId == 0 || req.BuyNum <= 0 { code = pb.ErrorCode_ReqParameterError } return } ///获取用户商品列表 func (this *apiComp) Buy(session comm.IUserSession, req *pb.ShopBuyReq) (code pb.ErrorCode, data proto.Message) { var ( err error ok bool conf *cfg.GameShopitemData shopitem *pb.DBShopItem need []*cfg.Gameatn give []*cfg.Gameatn ) if code = this.BuyCheck(session, req); code != pb.ErrorCode_Success { return } if conf, err = this.module.configure.GetShopItemsConfigure(req.GoodsId); err != nil { code = pb.ErrorCode_SystemError return } if shopitem, ok = this.module.modelShopItems.QueryUserShopDataByGoodId(session.GetUserId(), req.GoodsId); !ok { //没有购买记录 shopitem = &pb.DBShopItem{ Id: primitive.NewObjectID().Hex(), Uid: session.GetUserId(), GoodsId: conf.Key, BuyNum: map[int32]int32{1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, LastBuyTime: map[int32]int64{1: 0, 2: 0, 3: 0, 4: 0, 5: 0}, } } need = make([]*cfg.Gameatn, len(conf.Need)) for i, v := range conf.Need { need[i] = &cfg.Gameatn{ A: v.A, T: v.T, N: int32(math.Ceil(float64(v.N)*float64(conf.Sale)/float64(1000))) * req.BuyNum, } } give = make([]*cfg.Gameatn, len(conf.Iteminfo)) for i, v := range conf.Iteminfo { give[i] = &cfg.Gameatn{ A: v.A, T: v.T, N: v.N * req.BuyNum, } } if code = this.module.ConsumeRes(session, need, true); code != pb.ErrorCode_Success { return } if code = this.module.DispenseRes(session, give, true); code != pb.ErrorCode_Success { return } if conf.Buyminnum-shopitem.BuyNum[int32(req.ShopType)] < req.BuyNum { code = pb.ErrorCode_ShopGoodsIsSoldOut return } shopitem.BuyNum[int32(req.ShopType)] += req.BuyNum shopitem.LastBuyTime[int32(req.ShopType)] = time.Now().Unix() if !ok { this.module.modelShopItems.AddList(session.GetUserId(), shopitem.Id, shopitem) } else { this.module.modelShopItems.ChangeList(session.GetUserId(), shopitem.Id, map[string]interface{}{ "buyNum": shopitem.BuyNum, "lastBuyTime": shopitem.LastBuyTime, }) } //随机任务 this.module.ModuleRtask.SendToRtask(session, comm.Rtype64, 1) for _, v := range give { if v.A == comm.ItemType { this.module.ModuleRtask.SendToRtask(session, comm.Rtype65, v.N, utils.ToInt32(v.T)) } } this.module.ModuleRtask.SendToRtask(session, comm.Rtype66, 1, int32(req.ShopType)) for _, v := range need { if v.A == comm.AttrType && (v.T == comm.ResGold || v.T == comm.ResDiamond) { this.module.ModuleRtask.SendToRtask(session, comm.Rtype67, v.N, utils.ToInt32(v.T)) } } session.SendMsg(string(this.module.GetType()), "buy", &pb.ShopBuyResp{IsSucc: true}) return }