package troll import ( "go_dreamfactory/comm" "go_dreamfactory/pb" cfg "go_dreamfactory/sys/configure/structs" "time" "google.golang.org/protobuf/proto" ) //参数校验 func (this *apiComp) BuyOrSellCheck(session comm.IUserSession, req *pb.TrollBuyOrSellReq) (code pb.ErrorCode) { if len(req.Items) == 0 { code = pb.ErrorCode_ReqParameterError } return } ///获取美食城基本信息 func (this *apiComp) BuyOrSell(session comm.IUserSession, req *pb.TrollBuyOrSellReq) (code pb.ErrorCode, data proto.Message) { var ( //bSell bool // 是否有出售 gold int32 // 当次交易 获得的金币 earn int32 // 只统计赚的金币 update map[string]interface{} ) update = make(map[string]interface{}) if code = this.BuyOrSellCheck(session, req); code != pb.ErrorCode_Success { return // 参数校验失败直接返回 } trolltrain, err := this.module.modelTroll.getTrollList(session.GetUserId()) if err != nil { code = pb.ErrorCode_DBError return } for k, v := range req.Items { if v < 0 { //bSell = true trolltrain.SellCount += 1 // 交易次数+1 } trolltrain.Items[k] += v // 校验 是否大于买入最大限制 goods := this.configure.GetTrollGoods(k) if goods == nil { return } if goods.Max < trolltrain.Items[k] { // 判断是否有效交易 // TODO 买入上限 直接返回 //code = pb.ErrorCode_ return } else if trolltrain.Items[k] < 0 { // TODO 卖出数量不足 直接返回 return } // 第一次购买商品 if trolltrain.TarinPos == 0 { trolltrain.Price[k] = goods.Goodsprice * goods.StarMoney / 1000 trolltrain.RefreshTime = time.Now().Unix() //消耗的金币 gold = trolltrain.Price[k] * trolltrain.Items[k] } else { p := this.configure.GetTrollCoefficient(trolltrain.TarinPos) if p == nil { return } if v < 0 { // 卖出 // 卖出价格 var sellPrice int32 if trolltrain.TarinPos == 0 { sellPrice = goods.Goodsprice * goods.StarMoney / 1000 } else { sellPrice = int32(p.Coefficient) * goods.Goodsprice / 1000 } if sellPrice > trolltrain.Price[k] { // 赚了 earn += (sellPrice - trolltrain.Price[k]) * trolltrain.Items[k] } gold += (sellPrice - trolltrain.Price[k]) * trolltrain.Items[k] } else { // 买入 计算平均价格 totalGold := trolltrain.Items[k] * trolltrain.Price[k] sellPrice := int32(p.Coefficient) * goods.Goodsprice / 1000 totalGold += v * goods.Goodsprice * sellPrice trolltrain.Price[k] = totalGold / (trolltrain.Items[k] + v) } } if gold < 0 { if code = this.module.CheckRes(session, []*cfg.Gameatn{&cfg.Gameatn{ A: "attr", T: "gold", N: earn, }}); code != pb.ErrorCode_Success { return } } } trolltrain.TotalEarn += int64(earn) // 累计获得的金币 update["items"] = trolltrain.Items update["price"] = trolltrain.Price update["totalEarn"] = trolltrain.TotalEarn this.module.ModifyTrollData(session.GetUserId(), update) session.SendMsg(string(this.module.GetType()), TrollBuyOrSellResp, &pb.TrollBuyOrSellResp{Data: trolltrain}) return }