package models

import (
	"errors"
	"fmt"
	"go-admin/app/admin/models/kuaidi"
	orm "go-admin/common/global"
	"go-admin/logger"
	"time"
)

// gen:qs
//
//go:generate goqueryset -in share_card.go
type UserShareCardBill struct {
	Model
	Uid              uint32    `json:"uid" gorm:"index"`
	BillSn           string    `json:"bill_sn" gorm:"index"`
	State            string    `json:"state" gorm:"index"`
	SendCardType     uint32    `json:"send_card_type"`        // 1-送卡 2-邮寄
	StoreId          uint32    `json:"store_id" gorm:"index"` // 门店id
	ExpressCompany   string    `json:"express_company"`       // 物流公司
	ExpressCompanyNo string    `json:"express_company_no"`    // 物流公司编号
	ExpressNo        string    `json:"express_no"`            // 物流单号
	SendCardTime     time.Time `json:"send_card_time"`        // 递送卡时间
	StockTime        time.Time `json:"stock_time"`            // 入库时间
	RetrieveTime     time.Time `json:"retrieve_time"`         // 收回卡时间 申请收回
	StockRemovalTime time.Time `json:"stock_removal_time"`    // 出库时间
	Remark           string    `json:"remark"`
	Store            Store     `json:"store" gorm:"-"` // 门店
	// user_share_card_bill
	BillGames []ShareCardBillGame `json:"bill_games" gorm:"-"`
}

// gen:qs
type ShareCardBillGame struct {
	Model
	UserShareCardBillId uint32          `json:"user_share_card_bill_id" gorm:"index"`
	Uid                 uint32          `json:"uid" gorm:"index"`
	GameCardId          uint32          `json:"game_card_id" gorm:"index"`
	BillSn              string          `json:"bill_sn" gorm:"index"`
	Count               uint32          `json:"count"`
	State               string          `json:"state" gorm:"index"`
	GameCard            GameCard        `json:"game_card" gorm:"-"` //
	ShareCards          []UserShareCard `json:"share_cards" gorm:"-"`
}

const (
	ShareCardBillStateInCheck       = "in_check"       // 待审核
	ShareCardBillStateInSendCard    = "in_send_card"   // 待递送卡
	ShareCardBillStateSentCard      = "sent_card"      // 已递送卡
	ShareCardBillStateCompleted     = "completed"      // 完成
	ShareCardBillStateCancel        = "cancel"         // 取消
	ShareCardBillStateAuditLose     = "check_lose"     // 审核失败
	ShareCardBillStateReceivingCard = "receiving_card" // 收回中
	ShareCardBillStateReceivedCard  = "received_card"  // 已收回
)

const (
	ShareCardStateInCheck       = "in_check"       // 待审核
	ShareCardStateInSendCard    = "in_send_card"   // 待递送卡
	ShareCardStateSharing       = "sharing"        // 共享中
	ShareCardStateAuditLose     = "check_lose"     // 审核失败
	ShareCardStateCancel        = "cancel"         // 取消
	ShareCardStateReceivingCard = "receiving_card" // 收回中
	ShareCardStateReceivedCard  = "received_card"  // 已收回
)

// 用户的共享卡
// gen:qs
type UserShareCard struct {
	Model

	Uid             uint32 `json:"uid" gorm:"index"`
	GameCardGoodsId uint32 `json:"game_card_goods_id" gorm:"index"`
	SerialNumber    string `json:"serial_number" gorm:"index"` // 编号
	GameCardId      uint32 `json:"game_card_id" gorm:"index"`

	AllotSerialNumber   string `json:"allot_serial_number" gorm:"index"` // 库存共享卡编号 分配收回卡 绑定新卡编号
	AllotCardGoodsId    uint32 `json:"allot_card_goods_id" gorm:"index"` // 库存共享卡id
	UserShareCardBillId uint32 `json:"user_share_card_bill_id"  gorm:"index"`
	BillSn              string `json:"bill_sn" gorm:"index"`

	State string `json:"state" gorm:"index"`

	ShareCardBillGameId     uint32 `json:"share_card_bill_game_id"  gorm:"index"`
	StoreId                 uint32 `json:"store_id" gorm:"index"`                     // 门店id
	ProfitState             uint32 `json:"profit_state"`                              // 1-未生效 2-生效
	TotalVm                 uint32 `json:"total_vm"`                                  // 累计积分
	RetrieveSerialNumber    string `json:"retrieve_serial_number"  gorm:"index"`      // 收卡编号
	RetrieveGameCardGoodsId uint32 `json:"retrieve_game_card_goods_id"  gorm:"index"` // 收回卡id

	GameCard      GameCard       `json:"game_card" gorm:"-"`
	UserInfo      UserInfo       `json:"user_info" gorm:"-"`
	GameCardGoods *GameCardGoods `json:"game_card_goods" gorm:"-"`
	UserShareCard *UserShareCard `json:"user_share_card" gorm:"-"`
	// user_share_card
}

//// 用户共享卡库存状态
////gen:qs
//type UserShareCardStock struct {
//	Model
//	Uid                     uint32   `json:"uid" gorm:"index"`
//	ShareSerialNumber       string   `json:"share_serial_number" gorm:"index"` // 编号
//	BillSn                  string   `json:"bill_sn" gorm:"index"`
//	GameCardId              uint32   `json:"game_card_id" gorm:"index"`
//	State                   string   `json:"state" gorm:"index"`
//	GameCardGoodsId         uint32   `json:"game_card_goods_id" gorm:"index"`
//	UserShareCardBillId     uint32   `json:"user_share_card_bill_id"  gorm:"index"`
//	ShareCardBillGameId     uint32   `json:"share_card_bill_game_id"  gorm:"index"`
//	UserShareCardId         uint32   `json:"user_share_card_id"`
//	StoreId                 uint32   `json:"store_id" gorm:"index"`                     // 门店id
//	ProfitState             uint32   `json:"profit_state"`                              // 1-未生效 2-生效
//	TotalVm                 uint32   `json:"total_vm"`                                  // 累计积分
//	RetrieveSerialNumber    string   `json:"retrieve_serial_number"  gorm:"index"`      // 收卡编号
//	RetrieveGameCardGoodsId uint32   `json:"retrieve_game_card_goods_id"  gorm:"index"` // 收回卡id
//	GameCard                GameCard `json:"game_card" gorm:"-"`
//	UserInfo                UserInfo `json:"user_info" gorm:"-"`
//	//UserShareCard uint32 `json:"user_share_card"`
//}

type ShareBillListReq struct {
	Uid          uint64    `json:"uid" `
	StoreId      uint64    `json:"store_id" ` // 门店id
	BillSn       string    `json:"bill_sn"`
	State        string    `json:"state"`
	SendCardType uint32    `json:"send_card_type"` // 1-送卡 2-邮寄
	ExpressNo    string    `json:"express_no"`     // 物流单号
	StartTime    time.Time `json:"start_time"`     // 开始时间
	EndTime      time.Time `json:"end_time"`       // 结束时间
	Page         int       `json:"pageIndex"`
	PageSize     int       `json:"pageSize"`
}

// 游戏每日发放收益记录
// gen:qs
type ShareCardGameVm struct {
	Model
	GameCardId     uint32 `json:"game_card_id" gorm:"index"`
	HoldCardCount  uint32 `json:"hold_card_count"`           // 用户持有卡数
	StockCardCount uint32 `json:"stock_card_count"`          // 库存卡数
	TotalCardCount uint32 `json:"total_card_count"`          // 总的卡数
	CardProfit     uint32 `json:"card_profit"`               // 理论收益
	Vm             uint32 `json:"vm"`                        // 每张卡发放积分
	ProvideVm      uint32 `json:"provide_vm"`                // 总发放积分
	ProvideDate    string `json:"provide_date" gorm:"index"` // 发放收益时间

	GameCard GameCard `json:"game_card" gorm:"-"`
	//ShareCardGameVm int `json:"share_card_game_vm"`
}

// 用户卡每日收益记录
// gen:qs
type UserShareCardVm struct {
	Model
	ShareCardGameVmId   uint32   `json:"share_card_game_vm_id" gorm:"index"`
	Uid                 uint32   `json:"uid" gorm:"index"`
	SerialNumber        string   `json:"serial_number" gorm:"index"` // 编号
	BillSn              string   `json:"bill_sn" gorm:"index"`
	GameCardId          uint32   `json:"game_card_id" gorm:"index"`
	GameCardGoodsId     uint32   `json:"game_card_goods_id" gorm:"index"`
	UserShareCardBillId uint32   `json:"user_share_card_bill_id"  gorm:"index"`
	CardProfit          uint32   `json:"card_profit"` // 单张卡收益
	Vm                  uint32   `json:"vm"`          // 发放积分
	ProvideDate         string   `json:"provide_date" gorm:"index"`
	UserInfo            UserInfo `json:"user_info" gorm:"-"`
	GameCard            GameCard `json:"game_card" gorm:"-"`
}

// 用户每日收益列表
// gen:qs
type ShareCardDateVm struct {
	Model
	Uid         uint32   `json:"uid" gorm:"index"`
	Vm          uint32   `json:"vm"`                        // 发放积分
	TotalVm     uint32   `json:"total_vm"`                  // 用户累计获取积分
	ProvideDate string   `json:"provide_date" gorm:"index"` // 收益日期
	UserInfo    UserInfo `json:"user_info" gorm:"-"`
	// share_card_date_vm
}

// 总每日收益列表
// gen:qs
type ShareCardVmRecord struct {
	Model
	TotalVm     uint32 `json:"total_vm"`
	ProvideVm   uint32 `json:"provide_vm"`                // 总发放积分
	ProvideDate string `json:"provide_date" gorm:"index"` // 发放收益时间
	//ShareCardVmRecord int `json:"share_card_vm_record"`
}

// 用户收回卡
// gen:qs
type ShareCardRetrieve struct {
	Model
	Uid                    uint32                  `json:"uid" gorm:"index"`
	State                  string                  `json:"state" gorm:"index"`              // 1-暂无库存 2-待发卡 3-待取卡 4-已发卡 5-已收卡 6-已取消
	RetrieveCardType       uint32                  `json:"retrieve_card_type" gorm:"index"` // 1-送卡门店 2-邮寄
	StoreId                uint32                  `json:"store_id" gorm:"index"`           // 门店id
	ExpressCompany         string                  `json:"express_company"`                 // 物流公司
	ExpressCompanyNo       string                  `json:"express_company_no"`              // 物流公司编号
	ExpressNo              string                  `json:"express_no"`                      // 物流单号
	StockRemovalTime       time.Time               `json:"stock_removal_time"`              // 出库时间
	StockTime              time.Time               `json:"stock_time"`                      // 入库时间
	PayState               uint32                  `json:"pay_state"`                       // 1-未支付 2-已支付
	PayAmount              uint32                  `json:"pay_amount"`                      // 支付金额
	Remark                 string                  `json:"remark"`
	OrderSn                string                  `json:"order_sn" gorm:"index"`         // 订单编号
	AddressId              uint32                  `json:"address_id" gorm:"index"`       // 收货地址
	RefundOrderSn          string                  `json:"refund_order_sn"  gorm:"index"` // 订单编号退费
	PickupCode             string                  `json:"pickup_code"`                   // 取货码
	Store                  Store                   `json:"store" gorm:"-"`
	UserAddress            UserAddress             `json:"user_address" gorm:"-"`
	ShareCardRetrieveCards []ShareCardRetrieveCard `json:"share_card_retrieve_cards" gorm:"-"`
	ReceiptTime            time.Time               `json:"receipt_time"` // 签收时间
	//TotalVm  uint32   `json:"total_vm"` // 累计积分
	//ShareCardBillGameId uint32    `json:"share_card_bill_game_id"  gorm:"index"`
	//GameCardGoodsId     uint32    `json:"game_card_goods_id" gorm:"index"`
	//UserShareCardBillId uint32    `json:"user_share_card_bill_id"  gorm:"index"`
	//BillSn              string    `json:"bill_sn" gorm:"index"`
	//GameCardId          uint32    `json:"game_card_id" gorm:"index"`
	//SerialNumber        string    `json:"serial_number" gorm:"index"` // 编号
	//GameCard         GameCard  `json:"game_card" gorm:"-"`
	// share_card_retrieve
}

const (
	RetrieveStateInCheck       = "in_check"        // 待审核
	RetrieveStateCheckLose     = "check_lose"      // 审核失败
	RetrieveStateOutStock      = "out_stock"       // 暂无库存
	RetrieveStateInReceiveCard = "in_receive_card" // 待收卡
	RetrieveStateSentCard      = "sent_card"       // 已发卡
	RetrieveStateReceivedCard  = "received_card"   // 已收卡
	RetrieveStateCancel        = "cancel"          // 取消

	//RetrieveStateInPickCard   = "in_pick_card"  // 待取卡
)

// gen:qs
type ShareCardRetrieveCard struct {
	Model
	ShareCardRetrieveId uint32 `json:"share_card_retrieve_id" gorm:"index"` // 收回卡单id
	UserShareCardId     uint32 `json:"user_share_card_id" gorm:"index"`     // 用户共享卡id
	Uid                 uint32 `json:"uid" gorm:"index"`
	State               string `json:"state" gorm:"index"`          // -暂无库存 -待发卡 -待取卡 -已发卡 -已收卡 -已取消
	TransportType       uint32 `json:"transport_type" gorm:"index"` // 1-送卡到门店 2-邮寄
	SerialNumber        string `json:"serial_number" gorm:"index"`  // 编号
	GameCardGoodsId     uint32 `json:"game_card_goods_id" gorm:"index"`
	GameCardId          uint32 `json:"game_card_id" gorm:"index"`

	StoreId             uint32 `json:"store_id" gorm:"index"` // 共享卡门店id
	UserShareCardBillId uint32 `json:"user_share_card_bill_id"  gorm:"index"`
	BillSn              string `json:"bill_sn" gorm:"index"`

	RetrieveSerialNumber    string `json:"retrieve_serial_number"  gorm:"index"`      // 收卡编号
	RetrieveGameCardGoodsId uint32 `json:"retrieve_game_card_goods_id"  gorm:"index"` // 收回卡id
	Remark                  string `json:"remark"`

	OriginalCardType     string    `json:"original_card_type" gorm:"index"`       // -公共卡 -用户共享  回收前的卡类型 原卡类型
	AllotUserShareCardId uint32    `json:"allot_user_share_card_id" gorm:"index"` // 分配用户共享卡id
	ReceiptTime          time.Time `json:"receipt_time"`                          // 签收时间

	GameCard          GameCard          `json:"game_card" gorm:"-"`
	Store             Store             `json:"store" gorm:"-"`
	ShareCardRetrieve ShareCardRetrieve `json:"share_card_retrieve" gorm:"-"`
	//TotalVm  uint32   `json:"total_vm"` // 累计积分
	//ShareCardBillGameId uint32    `json:"share_card_bill_game_id"  gorm:"index"`
	// share_card_retrieve_card

}

const (
	//CardIssueStateUnFollow  = "unfollow"  // 待处理
	//CardIssueStateFollowed  = "followed"  // 已处理

	CardIssueStateFollowing = "following"  // 处理中
	CardIssueStateFollowed  = "followed"   // 已处理
	CardIssueStateInDeliver = "in_deliver" // 发货中
	CardIssueStateCompleted = "completed"  // 已完成
	CardIssueStateCanceled  = "canceled"   // 已取消
)
const (
	ObtainTypeRetrieveCard = "retrieve_card" // 收回卡
	ObtainTypeRentCard     = "rent_card"     // 租卡
)

type CardIssueFeedback struct {
	Model
	Uid             uint32 `json:"uid" gorm:"index"` // 反馈用户
	GameCardId      uint32 `json:"game_card_id" gorm:"index"`
	SerialNumber    string `json:"serial_number" gorm:"index"` // 编号
	GameCardGoodsId uint32 `json:"game_card_goods_id" gorm:"index"`
	StoreId         uint32 `json:"store_id" gorm:"index"`     // 门店id
	RelevanceId     uint32 `json:"relevance_id" gorm:"index"` // 关联id
	ObtainType      string `json:"obtain_type"`               // 卡类型: -收回卡 -租卡
	State           string `json:"state" gorm:"index"`        // 状态:
	Problem         string `json:"problem"`                   // 问题
	Remark          string `json:"remark"`

	ExpressCompany         string    `json:"express_company"`                         // 物流公司
	ExpressCompanyNo       string    `json:"express_company_no"`                      // 物流公司编号
	ExpressNo              string    `json:"express_no" gorm:"index"`                 // 物流单号
	IsNormalFunction       uint32    `json:"is_normal_function"`                      // 功能是否正常:1-是 2-否
	IsPackingIntact        uint32    `json:"is_packing_intact"`                       // 包装是否完整:1-是 2-否
	IsCardBreakage         uint32    `json:"is_card_breakage"`                        // 卡带是否破损:1-是 2-否
	DeliverExpressCompany  string    `json:"deliver_express_company"`                 // 发货物流公司
	DeliverExpressNo       string    `json:"deliver_express_no" gorm:"index"`         // 发货物流单号
	ReissueSerialNumber    string    `json:"reissue_serial_number" gorm:"index"`      // 补发货编码
	ReissueGameCardGoodsId uint32    `json:"reissue_game_card_goods_id" gorm:"index"` // 补发货卡id
	DeliverTime            time.Time `json:"deliver_time"`                            // 发货时间
	CheckTime              time.Time `json:"check_time"`                              // 检测时间
	CheckSysUid            string    `json:"check_sys_uid" gorm:"index"`              // 检测店员账号用户id
	ReceiptTime            time.Time `json:"receipt_time"`                            // 签收时间
	TransportType          uint32    `json:"transport_type" gorm:"index"`             // 1-送卡到门店 2-邮寄
	UserAddressId          uint32    `json:"user_address_id" gorm:"index"`

	UserInfo          *UserInfo          `json:"user_info" gorm:"-"`
	GameCard          *GameCard          `json:"game_card" gorm:"-"`
	Store             *Store             `json:"store" gorm:"-"`
	ShareCardRetrieve *ShareCardRetrieve `json:"share_card_retrieve" gorm:"-"`
	Order             *Order             `json:"order" gorm:"-"`
	UserAddress       *UserAddress       `json:"user_address" gorm:"-"`
	// card_issue_feedback
}

func (m *ShareBillListReq) List() ([]UserShareCardBill, int64, error) {
	var bills []UserShareCardBill
	qs := orm.Eloquent.Table("user_share_card_bill")
	if m.Uid != 0 {
		qs = qs.Where("uid=?", m.Uid)
	}
	if m.StoreId != 0 {
		qs = qs.Where("store_id=?", m.StoreId)
	}
	if m.BillSn != "" {
		qs = qs.Where("bill_sn=?", m.BillSn)
	}
	if m.State != "" {
		qs = qs.Where("state=?", m.State)
	}
	if m.SendCardType != 0 {
		qs = qs.Where("send_card_type=?", m.SendCardType)
	}
	if m.ExpressNo != "" {
		qs = qs.Where("express_no=?", m.ExpressNo)
	}
	if !m.StartTime.IsZero() {
		qs = qs.Where("created_at>?", m.StartTime)
	}
	if !m.EndTime.IsZero() {
		qs = qs.Where("created_at<?", m.EndTime)
	}
	page := m.Page - 1
	if page < 0 {
		page = 0
	}
	if m.PageSize == 0 {
		m.PageSize = 10
	}
	var count int64
	err := qs.Count(&count).Error
	if err != nil {
		logger.Error("count err:", logger.Field("err", err))
		return bills, 0, err
	}

	//totalPage :=int(count) /m.PageSize + 1

	err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&bills).Error
	if err != nil {
		logger.Error("count err:", logger.Field("err", err))
		return bills, count, err
	}

	if len(bills) > 0 {
		bills = UserShareCardBillListSetGame(bills)
	}

	return bills, count, nil
}

func UserShareCardBillListSetGame(list []UserShareCardBill) []UserShareCardBill {
	list = UserShareCardBillListSetStore(list)
	billIds := make([]uint32, 0, len(list))
	for i, _ := range list {
		billIds = append(billIds, list[i].ID)
	}
	if len(billIds) == 0 {
		return list
	}
	billMap := make(map[uint32][]ShareCardBillGame, 0)
	var games []ShareCardBillGame
	err := orm.Eloquent.Table("share_card_bill_game").Where("user_share_card_bill_id in (?)", billIds).Find(&games).Error
	if err != nil && err != RecordNotFound {
		logger.Error("share card bill  err:", logger.Field("err", err))
		return list
	}
	gameIds := make([]uint32, 0, len(games))
	for i, _ := range games {
		gameIds = append(gameIds, games[i].GameCardId)
	}
	cardMap, err := GameCardMap(gameIds)
	for i, _ := range games {
		v, ok := cardMap[games[i].GameCardId]
		if ok {
			games[i].GameCard = v
		}
	}

	for i, _ := range games {
		billMap[games[i].UserShareCardBillId] = append(billMap[games[i].UserShareCardBillId], games[i])
	}

	if err != nil {
		logger.Error("game card map  err:", logger.Field("err", err))
		return list
	}

	for i, _ := range list {
		v, ok := billMap[list[i].ID]
		if ok {
			list[i].BillGames = v
		}
	}

	return list
}

func UserShareCardBillListSetStore(list []UserShareCardBill) []UserShareCardBill {
	storeIds := make([]uint32, 0, len(list))
	for i, _ := range list {
		storeIds = append(storeIds, list[i].StoreId)
	}
	if len(storeIds) == 0 {
		return list
	}
	storeMap := GetStoreMap()
	for i, _ := range list {
		v, ok := storeMap[list[i].StoreId]
		if ok {
			list[i].Store = v
		}
	}

	return list
}

type ShareBillCardStorageReq struct {
	UserShareCardBillId uint32          `json:"user_share_card_bill_id"`
	StoreId             uint64          `json:"store_id" ` // 门店id
	Cards               []GameCardGoods `json:"cards"`
	CheckType           uint32          `json:"check_type"` // 1-审核失败 2-审核成功
	Remark              string          `json:"remark"`
}

//type BillCardStorageInfo struct {
//	GameCardId   uint32 `json:"game_card_id"`
//	SerialNumber string `json:"serial_number"` // 编号
//}

func (m *ShareBillCardStorageReq) CardStorage() error {
	if m.CheckType == 1 {
		state := ShareCardBillStateInSendCard
		gameState := ShareCardStateInSendCard
		if m.CheckType == 1 {
			state = ShareCardBillStateAuditLose
			gameState = ShareCardStateAuditLose
		}
		begin := orm.Eloquent.Begin()
		err := begin.Table("user_share_card_bill").Where("id=?", m.UserShareCardBillId).Updates(&map[string]interface{}{
			"state":  state,
			"remark": m.Remark,
		}).Error
		if err != nil {
			begin.Rollback()
			logger.Errorf("update user share card bill err:", logger.Field("err", err))
			return err
		}
		err = begin.Table("share_card_bill_game").Where("user_share_card_bill_id=?", m.UserShareCardBillId).Updates(&map[string]interface{}{
			"state": gameState,
		}).Error
		if err != nil {
			begin.Rollback()
			logger.Errorf("update share card bill game err:", logger.Field("err", err))
			return err
		}
		err = begin.Commit().Error
		if err != nil {
			begin.Rollback()
			logger.Errorf("commit err:", logger.Field("err", err))
			return err
		}
		return nil
	}
	for i, _ := range m.Cards {
		if m.Cards[i].SerialNumber == "" {
			logger.Errorf("serial number null:")
			return errors.New("serial number null")
		}
	}
	var userShareCardBill UserShareCardBill
	err := orm.Eloquent.Table("user_share_card_bill").Where("id=?", m.UserShareCardBillId).Find(&userShareCardBill).Error
	if err != nil {
		logger.Errorf("user share card bill game err:", logger.Field("err", err))
		return err
	}
	if userShareCardBill.State != ShareCardBillStateInSendCard && userShareCardBill.State != ShareCardBillStateSentCard {
		logger.Error("state err:")
		return errors.New("state err")
	}
	if len(m.Cards) > 0 {
		gameIds := make([]uint32, 0)
		for i, _ := range m.Cards {
			m.Cards[i].StoreId = m.StoreId
			m.Cards[i].Status = 1
			m.Cards[i].StockTime = time.Now()
			m.Cards[i].CardType = GameCardGoodsTypeShare
			m.Cards[i].ShareProfitType = 2

			m.Cards[i].UserShareCardBill = &userShareCardBill
			gameIds = append(gameIds, uint32(m.Cards[i].GameCardId))
		}
		new(GameCardGoods).Adds(m.Cards)

		begin := orm.Eloquent.Begin()
		err := begin.Table("user_share_card_bill").Where("id=?", m.UserShareCardBillId).Updates(&map[string]interface{}{
			"state":      ShareCardBillStateCompleted,
			"stock_time": time.Now(),
			"remark":     m.Remark,
		}).Error
		if err != nil {
			begin.Rollback()
			logger.Errorf("update user share card bill err:", logger.Field("err", err))
			return err
		}
		err = begin.Table("share_card_bill_game").Where("user_share_card_bill_id=?", m.UserShareCardBillId).
			Where("game_card_id in (?)", gameIds).Updates(&map[string]interface{}{
			"state": ShareCardStateSharing,
		}).Error
		if err != nil {
			begin.Rollback()
			logger.Errorf("update share card bill game err:", logger.Field("err", err))
			return err
		}
		err = begin.Commit().Error
		if err != nil {
			begin.Rollback()
			logger.Errorf("commit err:", logger.Field("err", err))
			return err
		}

		err = orm.Eloquent.Table("share_card_bill_game").Where("user_share_card_bill_id=?", m.UserShareCardBillId).
			Where("state=?", ShareCardStateInCheck).Updates(&map[string]interface{}{
			"state": ShareCardStateCancel,
		}).Error
		if err != nil {
			logger.Errorf("update share card bill game err:", logger.Field("err", err))
			return err
		}

	}

	return nil
}

func GetShareBillInfo(billId uint32) (UserShareCardBill, error) {
	var userShareCardBill UserShareCardBill
	err := orm.Eloquent.Table("user_share_card_bill").Where("id=?", billId).Find(&userShareCardBill).Error
	if err != nil {
		logger.Errorf("user share card bill err:", logger.Field("err", err))
		return userShareCardBill, err
	}
	bills := []UserShareCardBill{userShareCardBill}
	bills = UserShareCardBillListSetGame(bills)
	if len(bills) == 0 {
		return userShareCardBill, nil
	}
	//userShareCardBill = bills[0]
	err = bills[0].SetShareCard()
	if err != nil {
		logger.Errorf("set share card err:", logger.Field("err", err))
		return userShareCardBill, err
	}

	return bills[0], nil
}

func (m *UserShareCardBill) SetShareCard() error {
	var userShareCards []UserShareCard
	err := orm.Eloquent.Table("user_share_card").Where("user_share_card_bill_id=?", m.ID).Find(&userShareCards).Error
	if err != nil {
		logger.Errorf("user share card err:", logger.Field("err", err))
		return err
	}
	shareCardMap := make(map[uint32][]UserShareCard, 0)
	for i, _ := range userShareCards {
		shareCardMap[userShareCards[i].GameCardId] = append(shareCardMap[userShareCards[i].GameCardId], userShareCards[i])
	}
	if len(m.BillGames) == 0 {
		logger.Error("bill games is nil")
		return nil
	}
	for i, _ := range m.BillGames {
		v, ok := shareCardMap[m.BillGames[i].GameCardId]
		if ok {
			m.BillGames[i].ShareCards = v
		}
	}

	return nil
}

type UserShareCardListReq struct {
	Uid                  uint64    `json:"uid" `
	StoreId              uint64    `json:"store_id" ` // 门店id
	BillSn               string    `json:"bill_sn"`
	State                string    `json:"state"`
	SerialNumber         string    `json:"serial_number"` // 编号
	GameCardId           uint32    `json:"game_card_id"`
	GameCardGoodsId      uint32    `json:"game_card_goods_id"`
	RetrieveSerialNumber string    `json:"retrieve_serial_number"` // 收卡编号
	StartTime            time.Time `json:"start_time"`             // 开始时间
	EndTime              time.Time `json:"end_time"`               // 结束时间
	Page                 int       `json:"pageIndex"`
	PageSize             int       `json:"pageSize"`
}

func (m *UserShareCardListReq) List() ([]UserShareCard, int64, error) {
	var cards []UserShareCard
	qs := orm.Eloquent.Table("user_share_card")
	if m.Uid != 0 {
		qs = qs.Where("uid=?", m.Uid)
	}
	if m.StoreId != 0 {
		qs = qs.Where("store_id=?", m.StoreId)
	}
	if m.BillSn != "" {
		qs = qs.Where("bill_sn=?", m.BillSn)
	}
	if m.State != "" {
		qs = qs.Where("state=?", m.State)
	}
	if m.SerialNumber != "" {
		qs = qs.Where("serial_number=?", m.SerialNumber)
	}
	if m.GameCardId != 0 {
		qs = qs.Where("game_card_id=?", m.GameCardId)
	}
	if m.RetrieveSerialNumber != "" {
		qs = qs.Where("retrieve_serial_number=?", m.RetrieveSerialNumber)
	}
	if !m.StartTime.IsZero() {
		qs = qs.Where("created_at>?", m.StartTime)
	}
	if !m.EndTime.IsZero() {
		qs = qs.Where("created_at<?", m.EndTime)
	}
	page := m.Page - 1
	if page < 0 {
		page = 0
	}
	if m.PageSize == 0 {
		m.PageSize = 10
	}
	var count int64
	err := qs.Count(&count).Error
	if err != nil {
		logger.Error("count err:", logger.Field("err", err))
		return cards, 0, err
	}

	//totalPage :=int(count) /m.PageSize + 1

	err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&cards).Error
	if err != nil {
		logger.Error("count err:", logger.Field("err", err))
		return cards, count, err
	}

	if len(cards) > 0 {
		cards = UserShareCardListSetGame(cards)
	}

	return cards, count, nil
}

func UserShareCardListSetGame(list []UserShareCard) []UserShareCard {
	gameIds := make([]uint32, 0, len(list))
	uids := make([]uint32, 0, len(list))
	for i, _ := range list {
		gameIds = append(gameIds, list[i].GameCardId)
		uids = append(uids, list[i].Uid)
	}
	cardMap, err := GameCardMap(gameIds)
	if err != nil {
		logger.Error("game card map err:", logger.Field("err", err))
		return list
	}
	userInfoMap, err := GetUserInfoMap(uids)
	if err != nil {
		logger.Error("get user info map err:", logger.Field("err", err))
	}

	for i, _ := range list {
		v, ok1 := cardMap[list[i].GameCardId]
		if ok1 {
			list[i].GameCard = v
		}
		userInfo, ok2 := userInfoMap[list[i].Uid]
		if ok2 {
			list[i].UserInfo = userInfo
		}
	}

	return list
}

func UserShareCardVmListSetGame(list []UserShareCardVm) []UserShareCardVm {
	gameIds := make([]uint32, 0, len(list))
	uids := make([]uint32, 0, len(list))
	for i, _ := range list {
		gameIds = append(gameIds, list[i].GameCardId)
		uids = append(uids, list[i].Uid)
	}
	cardMap, err := GameCardMap(gameIds)
	if err != nil {
		logger.Error("game card map err:", logger.Field("err", err))
		return list
	}
	userInfoMap, err := GetUserInfoMap(uids)
	if err != nil {
		logger.Error("get user info map err:", logger.Field("err", err))
	}

	for i, _ := range list {
		v, ok1 := cardMap[list[i].GameCardId]
		if ok1 {
			list[i].GameCard = v
		}
		userInfo, ok2 := userInfoMap[list[i].Uid]
		if ok2 {
			list[i].UserInfo = userInfo
		}
	}

	return list
}

const (
	CardProfitVm = 21
)

func ShareCardProfitEffectCard() {
	//var shareCards []UserShareCard
	//err := orm.Eloquent.Table("user_share_card").Where("profit_state=?",1).
	//	Where("state=?", ShareCardStateSharing).
	//	Find(&shareCards).Error
	//if err != nil {
	//	logger.Error("game share cards err:",logger.Field("err",err))
	//	return
	//}
	//ids := make([]uint32,0,len(shareCards))
	//for i, _ := range shareCards {
	//	ids = append(ids, shareCards[i].ID)
	//}

	err := orm.Eloquent.Table("user_share_card").Where("profit_state=?", 1).
		Where("state=?", ShareCardStateSharing).Update("profit_state", 2).Error
	if err != nil {
		logger.Error("game share cards err:", logger.Field("err", err))
		return
	}
}
func ShareCardProvideVm() {
	//gameCards := make([]UserShareCard, 0)
	var gameCards []UserShareCard
	gameSql := fmt.Sprintf("SELECT * FROM user_share_card WHERE 1 GROUP BY game_card_id ;")
	err := orm.Eloquent.Raw(gameSql).Scan(&gameCards).Error
	if err != nil {
		logger.Error("game cards err:", logger.Field("err", err))
		return
	}
	gameIds := make([]uint32, 0, len(gameCards))
	for i, _ := range gameCards {
		gameIds = append(gameIds, gameCards[i].GameCardId)
	}
	shareCardVmRecord := &ShareCardVmRecord{ProvideDate: ZeroDateFormat(-1)}
	for i, _ := range gameIds {
		shareCardVmRecord.ProvideVmGameId(gameIds[i])
	}
	var vmRecord ShareCardVmRecord
	//orm.Eloquent.Table("share_card_vm_record").Order("id DESC").Limit(1).Find()
	err = orm.Eloquent.Table("share_card_vm_record").Where("provide_date=?", ZeroDateFormat(-2)).Find(&vmRecord).Error
	if err != nil && err != RecordNotFound {
		logger.Error("share card vm record err:", logger.Field("err", err))
		return
	}
	shareCardVmRecord.TotalVm = shareCardVmRecord.ProvideVm + vmRecord.TotalVm
	err = orm.Eloquent.Create(shareCardVmRecord).Error
	if err != nil {
		logger.Error("create share card vm record err:", logger.Field("err", err))
		return
	}
}

func (m *ShareCardVmRecord) ProvideVmGameId(gameId uint32) {
	var shareCards []UserShareCard
	err := orm.Eloquent.Table("user_share_card").Where("state=?", ShareCardStateSharing).
		Where("profit_state=?", 2).Where("game_card_id=?", gameId).Find(&shareCards).Error
	if err != nil {
		logger.Error("game cards err:", logger.Field("err", err))
		return
	}
	if len(shareCards) == 0 {
		return
	}
	record := &ShareCardGameVm{GameCardId: gameId, TotalCardCount: uint32(len(shareCards))}

	//goodsIds := make([]uint32, 0, len(shareCards))
	//for i, _ := range shareCards {
	//	goodsIds = append(goodsIds, shareCards[i].GameCardGoodsId)
	//}
	//var game GameCardGoods
	var holdCount int64
	//err = orm.Eloquent.Table("game_card_goods").Where("game_card_id in (?)", goodsIds).
	//err = orm.Eloquent.Table("game_card_goods").Where("id in (?)", goodsIds).
	err = orm.Eloquent.Table("game_card_goods").Where("game_card_id=?", gameId).Where("share_profit_type=?", 2).
		Where("card_type=?", "user_share").Where("status in (?)", []uint32{2, 3}).Count(&holdCount).Error
	if err != nil {
		logger.Error("stock count err:", logger.Field("err", err))
		return
	}

	//record.HoldCardCount = record.TotalCardCount - uint32(stockCount)
	record.HoldCardCount = uint32(holdCount)
	record.StockCardCount = record.TotalCardCount - uint32(holdCount)
	//record.ProvideDate = TodayZeroDateFormat()
	record.ProvideDate = m.ProvideDate
	record.CardProfit = CardProfitVm
	record.ProvideVm = CardProfitVm * record.HoldCardCount // 用户持有卡的数量
	record.Vm = record.ProvideVm / record.TotalCardCount
	err = orm.Eloquent.Create(record).Error
	if err != nil {
		logger.Error("share card vm record create err:", logger.Field("err", err))
		return
	}
	m.ProvideVm += record.ProvideVm
	record.ProvideVmUser(shareCards)
	//var holdCount int64
	//err = orm.Eloquent.Table("game_card_goods").Where("game_card_id in (?)", goodsIds).
	//	Where("status!=?", 1).Total(&holdCount).Error
	//if err != nil {
	//	logger.Error("stock count err:",logger.Field("err",err))
	//	return
	//}

}

func (m *ShareCardGameVm) ProvideVmUser(cards []UserShareCard) {
	for i, _ := range cards {
		userShareCardVm := &UserShareCardVm{
			ShareCardGameVmId:   m.ID,
			Uid:                 cards[i].Uid,
			SerialNumber:        cards[i].SerialNumber,
			BillSn:              cards[i].BillSn,
			GameCardId:          m.GameCardId,
			GameCardGoodsId:     cards[i].GameCardGoodsId,
			UserShareCardBillId: cards[i].UserShareCardBillId,
			CardProfit:          m.CardProfit,
			Vm:                  m.Vm,
			ProvideDate:         m.ProvideDate,
		}
		err := orm.Eloquent.Create(userShareCardVm).Error
		if err != nil {
			logger.Error("user share card vm create err:", logger.Field("err", err))
		}

		sql := fmt.Sprintf("UPDATE user_share_card SET total_vm=total_vm+%d WHERE game_card_goods_id =%d ;", userShareCardVm.Vm, userShareCardVm.GameCardGoodsId)
		err = orm.Eloquent.Exec(sql).Error
		if err != nil {
			logger.Error("update user share card  err:", logger.Field("err", err))
		}
	}

}

type UserShareCardVmListReq struct {
	Uid uint64 `json:"uid" `
	//StoreId      uint64    `json:"store_id" ` // 门店id
	BillSn string `json:"bill_sn"`
	//State           string    `json:"state"`
	SerialNumber    string    `json:"serial_number"` // 编号
	GameCardId      uint32    `json:"game_card_id"`
	GameCardGoodsId uint32    `json:"game_card_goods_id"`
	StartTime       time.Time `json:"start_time"` // 开始时间
	EndTime         time.Time `json:"end_time"`   // 结束时间
	Page            int       `json:"pageIndex"`
	PageSize        int       `json:"pageSize"`
}

func (m *UserShareCardVmListReq) List() ([]UserShareCardVm, int64, error) {
	var cards []UserShareCardVm
	qs := orm.Eloquent.Table("user_share_card_vm")
	if m.Uid != 0 {
		qs = qs.Where("uid=?", m.Uid)
	}
	if m.GameCardGoodsId != 0 {
		qs = qs.Where("game_card_goods_id=?", m.GameCardGoodsId)
	}
	if m.BillSn != "" {
		qs = qs.Where("bill_sn=?", m.BillSn)
	}
	//if m.State != "" {
	//	qs = qs.Where("state=?", m.State)
	//}
	if m.SerialNumber != "" {
		qs = qs.Where("serial_number=?", m.SerialNumber)
	}
	if m.GameCardId != 0 {
		qs = qs.Where("game_card_id=?", m.GameCardId)
	}
	if !m.StartTime.IsZero() {
		qs = qs.Where("created_at>?", m.StartTime)
	}
	if !m.EndTime.IsZero() {
		qs = qs.Where("created_at<?", m.EndTime)
	}
	page := m.Page - 1
	if page < 0 {
		page = 0
	}
	if m.PageSize == 0 {
		m.PageSize = 10
	}
	var count int64
	err := qs.Count(&count).Error
	if err != nil {
		logger.Error("count err:", logger.Field("err", err))
		return cards, 0, err
	}

	//totalPage :=int(count) /m.PageSize + 1

	err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&cards).Error
	if err != nil {
		logger.Error("count err:", logger.Field("err", err))
		return cards, count, err
	}

	if len(cards) > 0 {
		cards = UserShareCardVmListSetGame(cards)
	}

	return cards, count, nil
}

type UserShareCardVmDate struct {
	Uid     uint32 `json:"uid"`
	TotalVm uint32 `json:"total_vm"`
}

func ShareCardUserVmRecord() {
	var gameCards []UserShareCard
	gameSql := fmt.Sprintf("SELECT * FROM user_share_card WHERE 1 GROUP BY uid ;")
	err := orm.Eloquent.Raw(gameSql).Scan(&gameCards).Error
	if err != nil {
		logger.Error("game cards err:", logger.Field("err", err))
		return
	}
	provideDate := ZeroDateFormat(-1)
	//uids := make([]uint32, 0, len(gameCards))
	for i, _ := range gameCards {
		//uids = append(uids, gameCards[i].Uid)
		uid := gameCards[i].Uid
		var vmDate UserShareCardVmDate
		userSql := fmt.Sprintf("SELECT uid,SUM(vm) AS total_vm FROM user_share_card_vm WHERE provide_date = '%s' AND uid =%d  GROUP BY uid ;", provideDate, gameCards[i].Uid)
		//fmt.Println("userSql:", userSql)
		err := orm.Eloquent.Raw(userSql).Scan(&vmDate).Error
		if err != nil {
			logger.Error("user total vm err:", logger.Field("err", err))
			return
		}
		//fmt.Println("vmDate:", vmDate)
		var dateVm ShareCardDateVm
		err = orm.Eloquent.Table("share_card_date_vm").Where("uid=?", uid).Where("provide_date=?", ZeroDateFormat(-2)).Find(&dateVm).Error
		if err != nil && err != RecordNotFound {
			logger.Error("share card date vm err:", logger.Field("err", err))
			return
		}
		shareCardDateVm := &ShareCardDateVm{Uid: uid, ProvideDate: provideDate, TotalVm: dateVm.TotalVm}
		shareCardDateVm.Vm = vmDate.TotalVm
		shareCardDateVm.TotalVm += shareCardDateVm.Vm
		//fmt.Println("shareCardDateVm:", shareCardDateVm)

		err = UserVmUpdate(nil, "", shareCardDateVm.Uid, int(shareCardDateVm.Vm), VmEventUserShareCard, "用户共享卡收益")
		//err = UserVmUpdate(shareCardDateVm.Uid, int(shareCardDateVm.TotalVm), VmEventUserShareCard, "用户共享卡收益")
		if err != nil {
			logger.Error("user vm update err:", logger.Field("err", err))
			return
		}
		err = orm.Eloquent.Create(shareCardDateVm).Error
		if err != nil {
			logger.Error("create share card date vm err:", logger.Field("err", err))
			return
		}
	}
}

func ShareCardRetrieveCardSetStockCardCron() {
	var retrieves []ShareCardRetrieve
	err := orm.Eloquent.Table("share_card_retrieve").Where("state=?", RetrieveStateOutStock).
		Where("pay_state", 2).Order("id ASC").Find(&retrieves).Error
	if err != nil {
		logger.Error("share card retrieve err:", logger.Field("err", err))
		return
	}
	for i, _ := range retrieves {
		err = ShareCardRetrieveCardSetStockCard(retrieves[i].ID, "")
		if err != nil {
			logger.Error("share card retrieve card set stock card  cron err:", logger.Field("err", err))
		}
	}
}

type ShareCardGameVmListReq struct {
	ProvideDate string    `json:"provide_date"` // 发放收益时间
	GameCardId  uint32    `json:"game_card_id"`
	StartTime   time.Time `json:"start_time"` // 开始时间
	EndTime     time.Time `json:"end_time"`   // 结束时间
	Page        int       `json:"pageIndex"`
	PageSize    int       `json:"pageSize"`
}

func (m *ShareCardGameVmListReq) List() ([]ShareCardGameVm, int64, error) {
	var cards []ShareCardGameVm
	qs := orm.Eloquent.Table("share_card_game_vm")
	//if m.Uid != 0 {
	//	qs = qs.Where("uid=?", m.Uid)
	//}
	//if m.GameCardGoodsId != 0 {
	//	qs = qs.Where("game_card_goods_id=?", m.GameCardGoodsId)
	//}
	//if m.BillSn != "" {
	//	qs = qs.Where("bill_sn=?", m.BillSn)
	//}
	//if m.State != "" {
	//	qs = qs.Where("state=?", m.State)
	//}
	//if m.SerialNumber != "" {
	//	qs = qs.Where("serial_number=?", m.SerialNumber)
	//}
	//if m.BillSn != "" {
	//	qs = qs.Where("bill_sn=?", m.BillSn)
	//}
	if m.GameCardId != 0 {
		qs = qs.Where("game_card_id=?", m.GameCardId)
	}
	if !m.StartTime.IsZero() {
		qs = qs.Where("created_at>?", m.StartTime)
	}
	if !m.EndTime.IsZero() {
		qs = qs.Where("created_at<?", m.EndTime)
	}
	page := m.Page - 1
	if page < 0 {
		page = 0
	}
	if m.PageSize == 0 {
		m.PageSize = 10
	}
	var count int64
	err := qs.Count(&count).Error
	if err != nil {
		logger.Error("count err:", logger.Field("err", err))
		return cards, 0, err
	}

	//totalPage :=int(count) /m.PageSize + 1

	err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&cards).Error
	if err != nil {
		logger.Error("count err:", logger.Field("err", err))
		return cards, count, err
	}

	if len(cards) > 0 {
		cards = ShareCardVmListSetGame(cards)
	}

	return cards, count, nil
}

func ShareCardVmListSetGame(list []ShareCardGameVm) []ShareCardGameVm {
	gameIds := make([]uint32, 0, len(list))
	for i, _ := range list {
		gameIds = append(gameIds, list[i].GameCardId)

	}
	cardMap, err := GameCardMap(gameIds)
	if err != nil {
		logger.Error("game card map err:", logger.Field("err", err))
		return list
	}

	for i, _ := range list {
		v, ok1 := cardMap[list[i].GameCardId]
		if ok1 {
			list[i].GameCard = v
		}
	}

	return list
}

type ShareCardUserVmListReq struct {
	ProvideDate string    `json:"provide_date"` // 发放收益时间
	Uid         uint32    `json:"uid"`
	StartTime   time.Time `json:"start_time"` // 开始时间
	EndTime     time.Time `json:"end_time"`   // 结束时间
	Page        int       `json:"pageIndex"`
	PageSize    int       `json:"pageSize"`
}

func (m *ShareCardUserVmListReq) List() ([]ShareCardDateVm, int64, error) {
	var dateVms []ShareCardDateVm
	qs := orm.Eloquent.Table("share_card_date_vm")
	if m.Uid != 0 {
		qs = qs.Where("uid=?", m.Uid)
	}
	if !m.StartTime.IsZero() {
		qs = qs.Where("created_at>?", m.StartTime)
	}
	if !m.EndTime.IsZero() {
		qs = qs.Where("created_at<?", m.EndTime)
	}
	page := m.Page - 1
	if page < 0 {
		page = 0
	}
	if m.PageSize == 0 {
		m.PageSize = 10
	}
	var count int64
	err := qs.Count(&count).Error
	if err != nil {
		logger.Error("count err:", logger.Field("err", err))
		return dateVms, 0, err
	}

	//totalPage :=int(count) /m.PageSize + 1

	err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&dateVms).Error
	if err != nil {
		logger.Error("count err:", logger.Field("err", err))
		return dateVms, count, err
	}

	if len(dateVms) > 0 {
		dateVms = ShareCardUserVmListSetUser(dateVms)
	}

	return dateVms, count, nil
}

func ShareCardUserVmListSetUser(list []ShareCardDateVm) []ShareCardDateVm {
	uids := make([]uint32, 0, len(list))
	for i, _ := range list {
		uids = append(uids, list[i].Uid)
	}

	userMap, err := GetUserInfoMap(uids)
	if err != nil {
		logger.Error("game card map err:", logger.Field("err", err))
		return list
	}

	for i, _ := range list {
		v, ok1 := userMap[list[i].Uid]
		if ok1 {
			list[i].UserInfo = v
		}
	}

	return list
}

type ShareCardRetrieveListReq struct {
	Uid                  uint32    `json:"uid"`
	GameCardId           uint32    `json:"game_card_id"`
	State                string    `json:"state"`              // 1-暂无库存 2-待发卡 3-待取卡 4-已发卡 5-已收卡 6-已取消
	RetrieveCardType     uint32    `json:"retrieve_card_type"` // 1-送卡门店 2-邮寄
	StoreId              uint32    `json:"store_id"`           // 门店id
	ExpressNo            string    `json:"express_no"`         // 物流单号
	PickupCode           string    `json:"pickup_code"`        // 取货码
	RetrieveSerialNumber string    `json:"retrieve_serial_number"`
	StartTime            time.Time `json:"start_time"` // 开始时间
	EndTime              time.Time `json:"end_time"`   // 结束时间
	Page                 int       `json:"pageIndex"`
	PageSize             int       `json:"pageSize"`
}

func (m *ShareCardRetrieveListReq) List() ([]ShareCardRetrieve, int64, error) {
	var retrieves []ShareCardRetrieve
	qs := orm.Eloquent.Table("share_card_retrieve").Where("pay_state", 2)
	if m.Uid != 0 {
		qs = qs.Where("uid=?", m.Uid)
	}
	//if m.GameCardId != 0 {
	//	//qs = qs.Where("game_card_goods_id=?", m.GameCardGoodsId)
	//}
	if m.RetrieveCardType != 0 {
		qs = qs.Where("retrieve_card_type=?", m.RetrieveCardType)
	}
	if m.StoreId != 0 {
		qs = qs.Where("store_id=?", m.StoreId)
	}
	if m.ExpressNo != "" {
		qs = qs.Where("express_no=?", m.ExpressNo)
	}
	if m.State != "" {
		qs = qs.Where("state=?", m.State)
	}
	if m.PickupCode != "" {
		qs = qs.Where("pickup_code=?", m.PickupCode)
	}
	if m.RetrieveSerialNumber != "" {
		var shareCardRetrieveCards []ShareCardRetrieveCard
		err := orm.Eloquent.Table("share_card_retrieve_card").Where("retrieve_serial_number=?", m.RetrieveSerialNumber).
			Find(&shareCardRetrieveCards).Error
		if err != nil {
			logger.Error("share card retrieve card err:", logger.Field("err", err))
			return retrieves, 0, err
		}
		retrieveIds := make([]uint32, 0, len(shareCardRetrieveCards))
		for i, _ := range shareCardRetrieveCards {
			retrieveIds = append(retrieveIds, shareCardRetrieveCards[i].ShareCardRetrieveId)
		}
		if len(retrieveIds) > 0 {
			qs = qs.Where("id in (?)", retrieveIds)
		}
	}
	if m.GameCardId != 0 {
		var shareCardRetrieveCards []ShareCardRetrieveCard
		err := orm.Eloquent.Table("share_card_retrieve_card").Where("game_card_id=?", m.GameCardId).
			Find(&shareCardRetrieveCards).Error
		if err != nil {
			logger.Error("share card retrieve card err:", logger.Field("err", err))
			return retrieves, 0, err
		}
		retrieveIds := make([]uint32, 0, len(shareCardRetrieveCards))
		for i, _ := range shareCardRetrieveCards {
			retrieveIds = append(retrieveIds, shareCardRetrieveCards[i].ShareCardRetrieveId)
		}
		if len(retrieveIds) > 0 {
			qs = qs.Where("id in (?)", retrieveIds)
		}
	}
	if !m.StartTime.IsZero() {
		qs = qs.Where("created_at>?", m.StartTime)
	}
	if !m.EndTime.IsZero() {
		qs = qs.Where("created_at<?", m.EndTime)
	}
	page := m.Page - 1
	if page < 0 {
		page = 0
	}
	if m.PageSize == 0 {
		m.PageSize = 10
	}
	var count int64
	err := qs.Count(&count).Error
	if err != nil {
		logger.Error("count err:", logger.Field("err", err))
		return retrieves, 0, err
	}

	//totalPage :=int(count) /m.PageSize + 1

	err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&retrieves).Error
	if err != nil {
		logger.Error("count err:", logger.Field("err", err))
		return retrieves, count, err
	}

	if len(retrieves) > 0 {
		retrieves = ShareCardRetrieveSetCards(retrieves)
	}

	return retrieves, count, nil
}

func ShareCardRetrieveSetCards(list []ShareCardRetrieve) []ShareCardRetrieve {
	retrieveIds := make([]uint32, 0, len(list))
	for i, _ := range list {
		retrieveIds = append(retrieveIds, list[i].ID)
	}
	cardsMap, err := GetShareCardRetrieveMapCards(retrieveIds)
	if err != nil {
		logger.Error("get share card retrieve map cards err:", logger.Field("err", err))
		return list
	}
	for i, _ := range list {
		v, ok := cardsMap[list[i].ID]
		if ok {
			list[i].ShareCardRetrieveCards = v
		}
	}
	return list
}

func GetShareCardRetrieveMapCards(retrieveIds []uint32) (map[uint32][]ShareCardRetrieveCard, error) {
	retrieveCardMap := make(map[uint32][]ShareCardRetrieveCard, 0)
	if len(retrieveIds) == 0 {
		return retrieveCardMap, nil
	}

	var shareCardRetrieveCards []ShareCardRetrieveCard
	err := orm.Eloquent.Table("share_card_retrieve_card").Where("share_card_retrieve_id in (?)", retrieveIds).
		Find(&shareCardRetrieveCards).Error
	if err != nil && err != RecordNotFound {
		logger.Error("share card retrieve card err:", logger.Field("err", err))
		return retrieveCardMap, err
	}

	gameIds := make([]uint32, 0, len(shareCardRetrieveCards))
	for i, _ := range shareCardRetrieveCards {
		gameIds = append(gameIds, shareCardRetrieveCards[i].GameCardId)
	}
	gameMap := make(map[uint32]GameCard, 0)
	if len(gameIds) > 0 {
		gameMap, err = GameCardMap(gameIds)
		if err != nil {
			logger.Error("game card map err:", logger.Field("err", err))
			return retrieveCardMap, err
		}
	}

	for i, _ := range shareCardRetrieveCards {
		v, ok := gameMap[shareCardRetrieveCards[i].GameCardId]
		if ok {
			shareCardRetrieveCards[i].GameCard = v
		}
		retrieveCardMap[shareCardRetrieveCards[i].ShareCardRetrieveId] = append(
			retrieveCardMap[shareCardRetrieveCards[i].ShareCardRetrieveId], shareCardRetrieveCards[i])
	}
	return retrieveCardMap, nil
}

func GetShareCardRetrieveInfo(retrieveId uint32) (ShareCardRetrieve, error) {
	var retrieve ShareCardRetrieve
	err := orm.Eloquent.Table("share_card_retrieve").Where("id=?", retrieveId).
		Find(&retrieve).Error
	if err != nil {
		logger.Error("share card retrieve err:", logger.Field("err", err))
		return retrieve, err
	}
	var cards []ShareCardRetrieveCard
	err = orm.Eloquent.Table("share_card_retrieve_card").Where("share_card_retrieve_id=?", retrieveId).
		Find(&cards).Error
	if err != nil {
		logger.Error("share card retrieve card err:", logger.Field("err", err))
		return retrieve, err
	}

	retrieve.ShareCardRetrieveCards = ShareCardRetrieveCardListSetGame(cards)
	err = retrieve.SetStore()
	if err != nil {
		logger.Error("store err:", logger.Field("err", err))
		return retrieve, err
	}

	err = retrieve.SetUserAddress()
	if err != nil {
		logger.Error("user address err:", logger.Field("err", err))
		return retrieve, err
	}

	return retrieve, nil
}

func ShareCardRetrieveCardListSetGame(list []ShareCardRetrieveCard) []ShareCardRetrieveCard {
	gameIds := make([]uint32, 0, len(list))
	retrieveIds := make([]uint32, 0, len(list))
	for i, _ := range list {
		gameIds = append(gameIds, list[i].GameCardId)
		retrieveIds = append(retrieveIds, list[i].ShareCardRetrieveId)
	}

	cardMap, err := GameCardMap(gameIds)
	if err != nil {
		logger.Error("game card map err:", logger.Field("err", err))
		return list
	}

	for i, _ := range list {
		v, ok1 := cardMap[list[i].GameCardId]
		if ok1 {
			list[i].GameCard = v
		}
	}

	return list
}

func (m *ShareCardRetrieve) SetStore() error {
	err := orm.Eloquent.Table("store").Where("id=?", m.StoreId).Find(&m.Store).Error
	if err != nil && err != RecordNotFound {
		logger.Error("set store err:", logger.Field("err", err))
		return err
	}
	return nil
}
func (m *ShareCardRetrieve) SetUserAddress() error {
	err := orm.Eloquent.Table("user_address").Where("id=?", m.AddressId).Find(&m.UserAddress).Error
	if err != nil && err != RecordNotFound {
		logger.Error("set store err:", logger.Field("err", err))
		return err
	}
	return nil
}

func RetrieveCardAudit(retrieveId, auditType uint32, remark string) error {
	// 配置卡
	// 锁定库存
	// 更新状态
	// 锁定卡修改收益状态
	//retrieve, err := GetShareCardRetrieveById(retrieveId)
	//if err != nil {
	//	logger.Error("retrieve err:",logger.Field("err",err))
	//	return err
	//}
	if auditType == 1 {
		begin := orm.Eloquent.Begin()
		err := begin.Table("share_card_retrieve").Where("id=?", retrieveId).Updates(map[string]interface{}{
			"state":       RetrieveStateCheckLose,
			"pickup_code": "已取消",
			"remark":      remark,
		}).Error
		if err != nil {
			begin.Rollback()
			logger.Error("update share card retrieve card err:", logger.Field("err", err))
			return err
		}
		err = begin.Table("share_card_retrieve_card").Where("share_card_retrieve_id=?", retrieveId).Updates(map[string]interface{}{
			"state": RetrieveStateCheckLose,
		}).Error
		if err != nil {
			begin.Rollback()
			logger.Error("update share card retrieve card err:", logger.Field("err", err))
			return err
		}
		err = begin.Commit().Error
		if err != nil {
			begin.Rollback()
			logger.Error("commit err:", logger.Field("err", err))
			return err
		}
		return nil
	} else if auditType == 0 {
		logger.Error("audit type err:")
		return nil
	}
	err := ShareCardRetrieveCardSetStockCard(retrieveId, remark)
	if err != nil {
		logger.Error("share card retrieve card set stock card err:", logger.Field("err", err))
		return err
	}
	//retrieveCards, err := GetShareCardRetrieveCardByRetrieveId(retrieveId)
	//if err != nil {
	//	logger.Error("retrieve err:",logger.Field("err",err))
	//	return err
	//}
	//if len(retrieveCards) == 0 {
	//	logger.Error("user share card ids nil")
	//	return errors.New("user share card ids nil")
	//}
	//userShareCardIds := make([]uint32, 0, len(retrieveCards))
	//for i, _ := range retrieveCards {
	//	userShareCardIds = append(userShareCardIds, retrieveCards[i].UserShareCardId)
	//}
	//storeId := retrieveCards[0].StoreId
	//var shareCards []UserShareCard
	//err = orm.Eloquent.Table("user_share_card").Where("id in (?)", userShareCardIds).
	//	Find(&shareCards).Error
	//if err != nil {
	//	logger.Error("game cards err:",logger.Field("err",err))
	//	return err
	//}
	//if len(shareCards) == 0 {
	//	logger.Error("share cards is nil")
	//	return errors.New("share cards is nil")
	//}
	//shareCards, err = SetUserCardSerialNumber(retrieveCards[0].StoreId, shareCards)
	//if err != nil {
	//	logger.Error("set user card serial number err:",logger.Field("err",err))
	//	return err
	//}
	//shareCards, err = SetRandomCardSerialNumber(retrieveCards[0].StoreId, shareCards)
	//if err != nil {
	//	logger.Error("set random card serial number err:",logger.Field("err",err))
	//	return err
	//}
	//retrieveState := RetrieveStateInSendCard
	//lockGoodsIds := make([]uint32, 0, len(shareCards))
	//for i, _ := range shareCards {
	//
	//	if shareCards[i].RetrieveSerialNumber == "" || shareCards[i].RetrieveGameCardGoodsId == 0 {
	//		shareCards[i].State = ShareCardBillStateReceivedCard
	//		retrieveState = RetrieveStateOutStock
	//		lockGoodsIds = append(lockGoodsIds, shareCards[i].RetrieveGameCardGoodsId)
	//	} else {
	//		shareCards[i].ProfitState = 0
	//	}
	//}
	//begin := orm.Eloquent.Begin()
	//err = begin.Table("share_card_retrieve").Where("id=?", retrieveId).Updates(map[string]interface{}{
	//	"remark": remark,
	//	"state":  retrieveState,
	//}).Error
	//if err != nil {
	//	begin.Rollback()
	//	logger.Error("update share card retrieve card err:",logger.Field("err",err))
	//	return err
	//}
	//for i, _ := range shareCards {
	//	err = begin.Save(&shareCards[i]).Error
	//	if err != nil {
	//		begin.Rollback()
	//		logger.Error("user share card err:",logger.Field("err",err))
	//		return err
	//	}
	//	retrieveCardState := RetrieveStateInSendCard
	//	if shareCards[i].RetrieveSerialNumber == "" || shareCards[i].RetrieveGameCardGoodsId == 0 {
	//		retrieveCardState = RetrieveStateOutStock
	//		err = begin.Table("share_card_retrieve_card").Where("user_share_card_id=?", shareCards[i].ID).Updates(map[string]interface{}{
	//			"state": retrieveCardState,
	//		}).Error
	//		if err != nil {
	//			begin.Rollback()
	//			logger.Error("update share card retrieve err:",logger.Field("err",err))
	//			return err
	//		}
	//		continue
	//	}
	//
	//	err = begin.Table("share_card_retrieve_card").Where("user_share_card_id=?", shareCards[i].ID).Updates(map[string]interface{}{
	//		"state":                       retrieveCardState,
	//		"retrieve_serial_number":      shareCards[i].RetrieveSerialNumber,
	//		"retrieve_game_card_goods_id": shareCards[i].RetrieveGameCardGoodsId,
	//	}).Error
	//	if err != nil {
	//		begin.Rollback()
	//		logger.Error("update share card retrieve err:",logger.Field("err",err))
	//		return err
	//	}
	//	sql := fmt.Sprintf("UPDATE game_card_goods_stock SET rent_stock= rent_stock-1,store_stock=store_stock-1,total_stock=total_stock-1 WHERE store_id=%d AND game_card_id=%d;", storeId, shareCards[i].GameCardId)
	//	fmt.Println("sql:", sql)
	//	err = begin.Exec(sql).Error
	//	if err != nil {
	//		begin.Rollback()
	//		logger.Errorf("err:",logger.Field("err",err))
	//		return err
	//	}
	//}
	//err = begin.Table("game_card_goods").Where("id in (?)", lockGoodsIds).Updates(map[string]interface{}{
	//	"status": 5,
	//}).Error
	//if err != nil {
	//	begin.Rollback()
	//	logger.Error("update share card retrieve card err:",logger.Field("err",err))
	//	return err
	//}
	//err = begin.Commit().Error
	//if err != nil {
	//	begin.Rollback()
	//	logger.Error("commit err:",logger.Field("err",err))
	//	return err
	//}
	return nil
}

func ShareCardRetrieveCardSetStockCard(retrieveId uint32, remark string) error {
	fmt.Println("---------------------retrieveId:", retrieveId)
	retrieveCards, err := GetShareCardRetrieveCardByRetrieveId(retrieveId)
	if err != nil {
		logger.Error("retrieve err:", logger.Field("err", err))
		return err
	}
	if len(retrieveCards) == 0 {
		logger.Error("user share card ids nil")
		return errors.New("user share card ids nil")
	}
	userShareCardIds := make([]uint32, 0, len(retrieveCards))
	gameIds := make([]uint32, 0, len(retrieveCards))
	for i, _ := range retrieveCards {
		userShareCardIds = append(userShareCardIds, retrieveCards[i].UserShareCardId)
		gameIds = append(gameIds, retrieveCards[i].GameCardId)
	}
	storeId := retrieveCards[0].StoreId
	var shareCards []UserShareCard
	err = orm.Eloquent.Table("user_share_card").Where("id in (?)", userShareCardIds).
		Find(&shareCards).Error
	if err != nil {
		logger.Error("game cards err:", logger.Field("err", err))
		return err
	}
	if len(shareCards) == 0 {
		logger.Error("share cards is nil")
		return errors.New("share cards is nil")
	}
	//stockMap := make(map[uint32]uint32)
	//for i, _ := range shareCards {
	//	stockMap
	//}
	var cardStock []GameCardGoodsStock
	err = orm.Eloquent.Table("game_card_goods_stock").Where("game_card_id in (?)", gameIds).
		Where("store_id=?", retrieveCards[0].StoreId).Find(&cardStock).Error
	if err != nil {
		logger.Error("game cards err:", logger.Field("err", err))
		return err
	}

	cardStockMap := make(map[uint32]uint32, 0)
	for i, _ := range cardStock {
		//fmt.Println("GameCardId:", cardStock[i].GameCardId)
		//fmt.Println("StoreId:", cardStock[i].StoreId)
		//fmt.Println("RentStock:", cardStock[i].RentStock)
		cardStockMap[uint32(cardStock[i].GameCardId)] = cardStock[i].RentStock
	}
	shareCards, err = SetUserCardSerialNumber(retrieveCards[0].StoreId, shareCards, &cardStockMap)
	if err != nil {
		logger.Error("set user card serial number err:", logger.Field("err", err))
		return err
	}
	shareCards, err = SetRandomCardSerialNumber(retrieveCards[0].StoreId, shareCards, &cardStockMap)
	if err != nil {
		logger.Error("set random card serial number err:", logger.Field("err", err))
		return err
	}
	retrieveState := RetrieveStateInReceiveCard

	lockGoodsIds := make([]uint32, 0, len(shareCards))
	for i, _ := range shareCards {
		if shareCards[i].RetrieveSerialNumber == "" || shareCards[i].RetrieveGameCardGoodsId == 0 {
			//shareCards[i].State = ShareCardBillStateReceivedCard
			retrieveState = RetrieveStateOutStock
		} else {
			shareCards[i].State = ShareCardStateReceivingCard
			shareCards[i].ProfitState = 3
			lockGoodsIds = append(lockGoodsIds, shareCards[i].RetrieveGameCardGoodsId)
		}
	}
	begin := orm.Eloquent.Begin()
	err = begin.Table("share_card_retrieve").Where("id=?", retrieveId).Updates(map[string]interface{}{
		"remark": remark,
		"state":  retrieveState,
	}).Error
	if err != nil {
		begin.Rollback()
		logger.Error("update share card retrieve card err:", logger.Field("err", err))
		return err
	}
	for i, _ := range shareCards {
		err = begin.Save(&shareCards[i]).Error
		if err != nil {
			begin.Rollback()
			logger.Error("user share card err:", logger.Field("err", err))
			return err
		}
		retrieveCardState := RetrieveStateInReceiveCard
		if shareCards[i].RetrieveSerialNumber == "" || shareCards[i].RetrieveGameCardGoodsId == 0 {
			retrieveCardState = RetrieveStateOutStock
			err = begin.Table("share_card_retrieve_card").Where("user_share_card_id=?", shareCards[i].ID).Updates(map[string]interface{}{
				"state": retrieveCardState,
			}).Error
			if err != nil {
				begin.Rollback()
				logger.Error("update share card retrieve err:", logger.Field("err", err))
				return err
			}
			continue
		}
		// TODO
		//ShareCardRetrieveCard{}
		updateShareCardRetrieveCardMap := map[string]interface{}{
			"state":                       retrieveCardState,
			"retrieve_serial_number":      shareCards[i].RetrieveSerialNumber,
			"retrieve_game_card_goods_id": shareCards[i].RetrieveGameCardGoodsId,
		}
		if shareCards[i].UserShareCard != nil {
			updateShareCardRetrieveCardMap["allot_user_share_card_id"] = shareCards[i].UserShareCard.ID
		}
		if shareCards[i].GameCardGoods != nil {
			updateShareCardRetrieveCardMap["original_card_type"] = shareCards[i].GameCardGoods.CardType
			if shareCards[i].GameCardGoods.ShareProfitType == 1 {
				err = begin.Table("game_card_goods").Where("id=?", shareCards[i].GameCardGoodsId).Updates(map[string]interface{}{
					"card_type":         GameCardGoodsTypeCommon,
					"share_profit_type": 1,
				}).Error
				if err != nil {
					begin.Rollback()
					logger.Error("update share card retrieve err:", logger.Field("err", err))
					return err
				}
			}
		}
		// TODO
		//err = begin.Table("share_card_retrieve_card").Where("user_share_card_id=?", shareCards[i].ID).Updates(updateShareCardRetrieveCardMap).Error
		err = begin.Table("share_card_retrieve_card").Where("share_card_retrieve_id=?", retrieveId).
			Where("user_share_card_id=?", shareCards[i].ID).Updates(updateShareCardRetrieveCardMap).Error
		if err != nil {
			begin.Rollback()
			logger.Error("update share card retrieve err:", logger.Field("err", err))
			return err
		}
		//sql := fmt.Sprintf("UPDATE game_card_goods_stock SET rent_stock= rent_stock-1,store_stock=store_stock-1,total_stock=total_stock-1 WHERE store_id=%d AND game_card_id=%d;", storeId, shareCards[i].GameCardId)
		sql := fmt.Sprintf("UPDATE game_card_goods_stock SET rent_stock= rent_stock-1,total_stock=total_stock-1 WHERE store_id=%d AND game_card_id=%d;", storeId, shareCards[i].GameCardId)
		fmt.Println("sql:", sql)
		err = begin.Exec(sql).Error
		if err != nil {
			begin.Rollback()
			logger.Errorf("err:", logger.Field("err", err))
			return err
		}

		if shareCards[i].GameCardGoods != nil && shareCards[i].GameCardGoods.SerialNumber != shareCards[i].SerialNumber { // 不是自己的卡
			sideGoods := shareCards[i].GameCardGoods
			//if sideGoods.SerialNumber != shareCards[i].SerialNumber  {
			//}
			//UserShareCard{}
			if sideGoods.ShareProfitType == 2 {
				err = begin.Table("user_share_card").Where("serial_number=?", shareCards[i].RetrieveSerialNumber).Updates(map[string]interface{}{
					"allot_serial_number": shareCards[i].SerialNumber,
					"allot_card_goods_id": shareCards[i].GameCardGoodsId,
				}).Error
				if err != nil {
					begin.Rollback()
					logger.Error("update share card retrieve err:", logger.Field("err", err))
					return err
				}

			} else {

			}
		}
	}

	//var user ShareCardRetrieveCard
	//for i, _ := range shareCards {
	//	err := begin.Table("share_card_retrieve_card").Where("user_share_card_id=?", retrieveCards[i].ID).Updates(map[string]interface{}{
	//		"retrieve_serial_number":      retrieveCards[i].RetrieveSerialNumber,
	//		"retrieve_game_card_goods_id": retrieveCards[i].RetrieveGameCardGoodsId,
	//	}).Error
	//	if err != nil {
	//		begin.Rollback()
	//		logger.Error("update share card retrieve err:",logger.Field("err",err))
	//		return err
	//	}
	//	sql := fmt.Sprintf("UPDATE game_card_goods_stock SET rent_stock= rent_stock-1,store_stock=store_stock-1,total_stock=total_stock-1 WHERE store_id=%d AND game_card_id=%d;", list[i].StoreId, list[i].GameCardId)
	//	fmt.Println("sql:", sql)
	//	err = begin.Exec(sql).Error
	//	if err != nil {
	//		begin.Rollback()
	//		logger.Errorf("err:",logger.Field("err",err))
	//		continue
	//	}
	//}
	if len(lockGoodsIds) > 0 {
		err = begin.Table("game_card_goods").Where("id in (?)", lockGoodsIds).Updates(map[string]interface{}{
			"status": 5,
		}).Error
		if err != nil {
			begin.Rollback()
			logger.Error("update share card retrieve card err:", logger.Field("err", err))
			return err
		}
	}

	err = begin.Commit().Error
	if err != nil {
		begin.Rollback()
		logger.Error("commit err:", logger.Field("err", err))
		return err
	}

	return nil
}

type ShareCardRetrieveCardDeliverReq struct {
	//Uid                 uint32   `json:"uid"`
	SerialNumbers       []string `json:"serial_numbers"`
	ShareCardRetrieveId uint32   `json:"share_card_retrieve_id"`
	StoreId             uint32   `json:"store_id"`           // 门店id
	ExpressCompany      string   `json:"express_company"`    // 物流公司
	ExpressNo           string   `json:"express_no"`         // 物流单号
	ExpressCompanyNo    string   `json:"express_company_no"` // 物流公司编号
}

func (m *ShareCardRetrieveCardDeliverReq) Deliver() (error, string) {
	var retrieve ShareCardRetrieve
	err := orm.Eloquent.Table("share_card_retrieve").Where("id=?", m.ShareCardRetrieveId).
		Find(&retrieve).Error
	if err != nil {
		logger.Error("share card retrieve err:", logger.Field("err", err))
		return err, ""
	}
	if retrieve.State != RetrieveStateInReceiveCard {
		logger.Error("share card retrieve state err:")
		return err, "用户收回卡单状态异常"
	}

	if m.StoreId != retrieve.StoreId {
		logger.Error("store id err")
		return errors.New("store id err"), "出库门店与用户申请门店不一致"
	}
	var cards []ShareCardRetrieveCard
	err = orm.Eloquent.Table("share_card_retrieve_card").Where("share_card_retrieve_id=?", m.ShareCardRetrieveId).
		Find(&cards).Error
	if err != nil {
		logger.Error("share card retrieve card err:", logger.Field("err", err))
		return err, ""
	}
	retrieveSerials := make([]string, 0)
	shareCardIds := make([]uint32, 0, len(cards))
	for i, _ := range cards {
		retrieveSerials = append(retrieveSerials, cards[i].RetrieveSerialNumber)
		shareCardIds = append(shareCardIds, cards[i].UserShareCardId)
		//shareCardIds = append(shareCardIds, cards[i].RetrieveGameCardGoodsId)
	}
	//fmt.Println("ShareCardRetrieveId:", m.ShareCardRetrieveId)
	//fmt.Println("SerialNumbers:", m.SerialNumbers)
	//fmt.Println("retrieveSerials:", retrieveSerials)
	// 收益状态修改  锁定
	if !LoopCompareStringSlice(m.SerialNumbers, retrieveSerials) {
		logger.Error("serial numbers err")
		return errors.New("serial numbers err"), "出库卡与系统分配的卡不一致"
	}
	begin := orm.Eloquent.Begin()
	err = begin.Table("game_card_goods").Where("serial_number in (?)", m.SerialNumbers).Updates(map[string]interface{}{
		"status": 6,
	}).Error
	if err != nil {
		begin.Rollback()
		logger.Error("update game card goods err:", logger.Field("err", err))
		return err, ""
	}

	err = begin.Table("user_share_card").Where("id in (?)", shareCardIds).Updates(map[string]interface{}{
		"state": ShareCardStateReceivedCard,
	}).Error
	if err != nil {
		begin.Rollback()
		logger.Error("update game card goods err:", logger.Field("err", err))
		return err, ""
	}
	receiptTime := time.Time{}
	retrieveState := RetrieveStateSentCard
	if retrieve.RetrieveCardType == 1 {
		retrieveState = RetrieveStateReceivedCard
		receiptTime = time.Now()
	}
	err = begin.Table("share_card_retrieve").Where("id=?", m.ShareCardRetrieveId).Updates(map[string]interface{}{
		//"state":           RetrieveStateSentCard,
		"state":              retrieveState,
		"pickup_code":        "已取卡",
		"express_company":    m.ExpressCompany,
		"express_no":         m.ExpressNo,
		"express_company_no": m.ExpressCompanyNo,
		"stock_removal_time": time.Now(),
		"receipt_time":       receiptTime,
	}).Error
	if err != nil {
		begin.Rollback()
		logger.Error("update share card retrieve card err:", logger.Field("err", err))
		return err, ""
	}
	err = begin.Table("share_card_retrieve_card").Where("share_card_retrieve_id=?", m.ShareCardRetrieveId).Updates(map[string]interface{}{
		//"state": RetrieveStateSentCard,
		"state":        retrieveState,
		"receipt_time": receiptTime,
	}).Error
	if err != nil {
		begin.Rollback()
		logger.Error("update share card retrieve card err:", logger.Field("err", err))
		return err, ""
	}
	err = begin.Commit().Error
	if err != nil {
		begin.Rollback()
		logger.Error("commit err:", logger.Field("err", err))
		return err, ""
	}

	if m.ExpressCompanyNo != "" && m.ExpressNo != "" {
		_, err = kuaidi.SubscribeExpressState(m.ExpressCompanyNo, m.ExpressNo)
		if err != nil {
			logger.Error("subscribe express state err:", logger.Field("err", err))
		}
	}
	return nil, ""
}

func SetUserCardSerialNumber(storeId uint32, list []UserShareCard, cardStockMap *map[uint32]uint32) ([]UserShareCard, error) {
	for i, _ := range list {
		if list[i].RetrieveSerialNumber != "" {
			continue
		}
		cardCount, ok := (*cardStockMap)[list[i].GameCardId]
		if !ok {
			continue
		}
		fmt.Println("cardCount:", cardCount, list[i].GameCardId, storeId)
		if cardCount == 0 {
			continue
		}
		var goods GameCardGoods
		err := orm.Eloquent.Table("game_card_goods").Where("store_id=?", storeId).
			Where("serial_number=?", list[i].SerialNumber).Where("status=?", 1).Find(&goods).Error
		//err := NewGameCardGoodsQuerySet(DB).StoreIdEq(uint64(storeId)).SerialNumberEq(list[i].SerialNumber).
		//	StatusEq(1).One(&goods)
		if err != nil && err != RecordNotFound {
			logger.Error("game card goods err:", logger.Field("err", err))
			return list, err
		}
		if goods.ID == list[i].GameCardGoodsId {
			list[i].RetrieveSerialNumber = goods.SerialNumber
			list[i].RetrieveGameCardGoodsId = goods.ID
			(*cardStockMap)[list[i].GameCardId] = cardCount - 1
		}

	}
	return list, nil
}

func SetRandomCardSerialNumber(storeId uint32, list []UserShareCard, cardStockMap *map[uint32]uint32) ([]UserShareCard, error) {
	//allotedCardGoodsMap := make(map[string]uint32, 0)
	allotedCardGoodsIds := make([]uint32, 0)
	//userShareCardMap := make(map[uint32][]UserShareCard, 0)
	//for i, _ := range list {
	//	if list[i].RetrieveSerialNumber != "" {
	//		continue
	//	}
	//	userShareCardMap[list[i].GameCardId] = append(userShareCardMap[list[i].GameCardId], list[i])
	//}

	for i, _ := range list {
		if list[i].RetrieveSerialNumber != "" {
			continue
		}
		cardCount, ok := (*cardStockMap)[list[i].GameCardId]
		if !ok {
			continue
		}
		fmt.Println("RandomCard cardCount:", cardCount, list[i].GameCardId, storeId)
		if cardCount == 0 {
			continue
		}
		var goods GameCardGoods
		qs := orm.Eloquent.Table("game_card_goods").Where("store_id=?", storeId).
			Where("game_card_id=?", list[i].GameCardId).Where("status=?", 1)
		if len(allotedCardGoodsIds) > 0 {
			qs = qs.Where("id NOT IN (?)", allotedCardGoodsIds)
		}
		err := qs.Order("id ASC").Limit(1).Find(&goods).Error
		//err := NewGameCardGoodsQuerySet(DB).StoreIdEq(uint64(storeId)).GameCardIdEq(uint64(list[i].GameCardId)).
		//	StatusEq(1).OrderAscByID().Limit(1).One(&goods)
		if err != nil && err != RecordNotFound {
			logger.Error("game card goods err:", logger.Field("err", err))
			return list, err
		}
		if err != RecordNotFound {
			list[i].RetrieveSerialNumber = goods.SerialNumber
			list[i].RetrieveGameCardGoodsId = goods.ID
			list[i].GameCardGoods = &goods
			allotedCardGoodsIds = append(allotedCardGoodsIds, goods.ID)
			if goods.ShareProfitType == 2 {
				var userShareCard UserShareCard
				err := orm.Eloquent.Table("user_share_card").Where("serial_number=?", goods.SerialNumber).Find(&userShareCard).Error
				if err != nil {
					logger.Error("user share card err:", logger.Field("err", err))
					return list, err
				}
				list[i].UserShareCard = &userShareCard
			}
			(*cardStockMap)[list[i].GameCardId] = cardCount - 1
		}
	}
	return list, nil
}

func LoopCompareStringSlice(a, b []string) bool {
	if len(a) != len(b) {
		return false
	}
	if (a == nil) != (b == nil) {
		return false
	}

	aMap := make(map[string]int, 0)
	for i, _ := range a {
		aMap[a[i]] = i
	}
	bMap := make(map[string]int, 0)
	for i, _ := range b {
		if _, ok := aMap[b[i]]; !ok {
			return false
		}
		bMap[b[i]] = i
	}

	for i, _ := range a {
		if _, ok := bMap[a[i]]; !ok {
			return false
		}
	}
	return true
}

//func GetShareCardRetrieveById(retrieveId uint32) (ShareCardRetrieve, error) {
//	var retrieve ShareCardRetrieve
//	err := orm.Eloquent.Table("share_card_retrieve").Where("id=?", retrieveId).
//		Find(&retrieve).Error
//	if err != nil {
//		logger.Error("share card retrieve err:",logger.Field("err",err))
//		return retrieve, err
//	}
//	return retrieve, nil
//}

func GetShareCardRetrieveCardByRetrieveId(retrieveId uint32) ([]ShareCardRetrieveCard, error) {
	var cards []ShareCardRetrieveCard
	err := orm.Eloquent.Table("share_card_retrieve_card").Where("share_card_retrieve_id=?", retrieveId).
		Where("retrieve_serial_number=?", "").Find(&cards).Error
	if err != nil {
		logger.Error("share card retrieve err:", logger.Field("err", err))
		return cards, err
	}
	return cards, nil
}

type CardIssueListReq struct {
	Uid          uint32    `json:"uid"`
	GameCardId   uint32    `json:"game_card_id"`
	State        string    `json:"state"` // 1-暂无库存 2-待发卡 3-待取卡 4-已发卡 5-已收卡 6-已取消
	SerialNumber string    `json:"serial_number"`
	StoreId      uint32    `json:"store_id"`   // 门店id
	StartTime    time.Time `json:"start_time"` // 开始时间
	EndTime      time.Time `json:"end_time"`   // 结束时间
	Page         int       `json:"pageIndex"`
	PageSize     int       `json:"pageSize"`
}

func (m *CardIssueListReq) List() ([]CardIssueFeedback, int64, error) {
	var cardIssues []CardIssueFeedback
	qs := orm.Eloquent.Table("card_issue_feedback")
	if m.Uid != 0 {
		qs = qs.Where("uid=?", m.Uid)
	}
	if m.GameCardId != 0 {
		qs = qs.Where("game_card_id=?", m.GameCardId)
	}
	if m.StoreId != 0 {
		qs = qs.Where("store_id=?", m.StoreId)
	}
	if m.SerialNumber != "" {
		qs = qs.Where("serial_number=?", m.SerialNumber)
	}
	if m.State != "" {
		qs = qs.Where("state=?", m.State)
	}
	if !m.StartTime.IsZero() {
		qs = qs.Where("created_at>?", m.StartTime)
	}
	if !m.EndTime.IsZero() {
		qs = qs.Where("created_at<?", m.EndTime)
	}
	page := m.Page - 1
	if page < 0 {
		page = 0
	}
	if m.PageSize == 0 {
		m.PageSize = 10
	}
	var count int64
	err := qs.Count(&count).Error
	if err != nil {
		logger.Error("count err:", logger.Field("err", err))
		return cardIssues, 0, err
	}

	//totalPage :=int(count) /m.PageSize + 1

	err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&cardIssues).Error
	if err != nil && err != RecordNotFound {
		logger.Error("count err:", logger.Field("err", err))
		return cardIssues, count, err
	}

	if len(cardIssues) > 0 {
		cardIssues = CardIssueFeedbackListSetGame(cardIssues)
	}

	return cardIssues, count, nil
}

func CardIssueFeedbackListSetGame(list []CardIssueFeedback) []CardIssueFeedback {
	if len(list) == 0 {
		return list
	}
	gameIds := make([]uint32, 0, len(list))
	uids := make([]uint32, 0, len(list))
	for i, _ := range list {
		gameIds = append(gameIds, list[i].GameCardId)
		uids = append(uids, list[i].Uid)
	}

	gameMap, err := GameCardMap(gameIds)
	if err != nil {
		logger.Error("game card map err:", logger.Field("err", err))
		return list
	}

	infoMap, err := GetUserInfoMap(uids)
	if err != nil {
		logger.Error("user info  map err:", logger.Field("err", err))
		return list
	}

	for i, _ := range list {
		game, ok1 := gameMap[list[i].GameCardId]
		if ok1 {
			list[i].GameCard = &game
		}
		userInfo, ok2 := infoMap[list[i].Uid]
		if ok2 {
			list[i].UserInfo = &userInfo
		}
	}

	return list
}

func GetCardIssueFeedbackInfo(issueId uint32) (CardIssueFeedback, error) {
	var cardIssue CardIssueFeedback
	err := orm.Eloquent.Table("card_issue_feedback").Where("id=?", issueId).Find(&cardIssue).Error
	if err != nil {
		logger.Error("card issue feedback err:")
		return cardIssue, err
	}
	list := []CardIssueFeedback{cardIssue}
	list = CardIssueFeedbackListSetGame(list)
	if len(list) == 0 {
		return cardIssue, nil
	}
	cardIssue = list[0]
	var store Store
	err = orm.Eloquent.Table("store").Where("id=?", cardIssue.StoreId).Find(&store).Error
	if err != nil {
		logger.Error("store err:")
		return cardIssue, err
	}
	var userAddress UserAddress
	err = orm.Eloquent.Table("user_address").Where("id=?", cardIssue.UserAddressId).Find(&userAddress).Error
	if err != nil {
		logger.Error("store err:")
		return cardIssue, err
	}

	cardIssue.Store = &store
	cardIssue.UserAddress = &userAddress
	if cardIssue.ObtainType == ObtainTypeRetrieveCard {
		var cardRetrieves ShareCardRetrieveCard
		err = orm.Eloquent.Table("share_card_retrieve_card").Where("id=?", cardIssue.RelevanceId).Find(&cardRetrieves).Error
		if err != nil {
			logger.Error("card issue feedback err:")
			return cardIssue, err
		}

		var shareCardRetrieve ShareCardRetrieve
		err := orm.Eloquent.Table("share_card_retrieve").Where("id=?", cardRetrieves.ShareCardRetrieveId).Find(&shareCardRetrieve).Error
		if err != nil {
			logger.Error("card issue feedback err:")
			return cardIssue, err
		}

		shareCardRetrieve.ShareCardRetrieveCards = []ShareCardRetrieveCard{cardRetrieves}
		cardIssue.ShareCardRetrieve = &shareCardRetrieve
	} else {
		var orderCards OrderCard
		err = orm.Eloquent.Table("order_card").Where("id=?", cardIssue.RelevanceId).Find(&orderCards).Error
		if err != nil {
			logger.Error("card issue feedback err:")
			return cardIssue, err
		}

		var order Order
		err := orm.Eloquent.Table("order").Where("id=?", orderCards.OrderId).Find(&order).Error
		if err != nil {
			logger.Error("card issue feedback err:")
			return cardIssue, err
		}

		order.OrderCards = []OrderCard{orderCards}
		cardIssue.Order = &order
	}

	return cardIssue, nil
}

type ExpressStatePushReq struct {
	Status     string `json:"status"`
	Message    string `json:"message"`
	LastResult struct {
		Message string `json:"message"`
		Nu      string `json:"nu"`
		Ischeck string `json:"ischeck"`
		Com     string `json:"com"`
		Status  string `json:"status"`
		State   int    `json:"state"`
		Data    []struct {
			Time       string      `json:"time"`
			Context    string      `json:"context"`
			Ftime      string      `json:"ftime"`
			AreaCode   *string     `json:"areaCode"`
			AreaName   *string     `json:"areaName"`
			Status     string      `json:"status"`
			Location   interface{} `json:"location"`
			AreaCenter interface{} `json:"areaCenter"`
			AreaPinYin interface{} `json:"areaPinYin"`
			StatusCode interface{} `json:"statusCode"`
		} `json:"data"`
		Loop bool `json:"loop"`
	} `json:"lastResult"`
}

func TakeExpressStatePush(pushReq *ExpressStatePushReq) {
	fmt.Println("LastResult:Nu", pushReq.LastResult.Nu)
	fmt.Println("LastResult:State", pushReq.LastResult.State)
	if pushReq.LastResult.State == 3 {
		//var cardIssue CardIssueFeedback
		//err := orm.Eloquent.Table("card_issue_feedback").Where("deliver_express_no=?", pushReq.LastResult.Nu).Find(&cardIssue).Error
		//if err == nil {
		//	err = orm.Eloquent.Table("card_issue_feedback").Where("id=?", cardIssue.ID).Updates(map[string]interface{}{
		//		"receipt_time": time.Now(),
		//	}).Error
		//	if err != nil {
		//		logger.Error("update card issue feedback err:",logger.Field("err",err))
		//		return
		//	}
		//
		//	err = orm.Eloquent.Table("card_issue_feedback").Where("id=?", cardIssue.ID).Updates(map[string]interface{}{
		//		"receipt_time": time.Now(),
		//	}).Error
		//	if err != nil {
		//		logger.Error("update card issue feedback err:",logger.Field("err",err))
		//		return
		//	}
		//
		//	var userInfo UserInfo
		//	err := orm.Eloquent.Table("user").Where("uid=?", cardIssue.Uid).Find(&userInfo).Error
		//	if err != nil {
		//		logger.Error("user info err:",logger.Field("err",err))
		//		return
		//	}
		//	if userInfo.Tel == "" {
		//		return
		//	}
		//	err = SmsSend(userInfo.Tel, "【明慧科技】温馨提示：您的收回卡已签收，请及时检查卡带确认功能正常，如有问题，请于签收后48小时内通过小程序发起异常反馈。")
		//	if err != nil {
		//		logger.Errorf("SmsSend err:",logger.Field("err",err))
		//		return
		//	}
		//	return
		//}

		var shareCardRetrieve ShareCardRetrieve
		err := orm.Eloquent.Table("card_issue_feedback").Where("express_no=?", pushReq.LastResult.Nu).Find(&shareCardRetrieve).Error
		if err == nil {
			err = orm.Eloquent.Table("share_card_retrieve").Where("id=?", shareCardRetrieve.ID).Updates(map[string]interface{}{
				"receipt_time": time.Now(),
			}).Error
			if err != nil {
				logger.Error("update card issue feedback err:", logger.Field("err", err))
				return
			}

			err = orm.Eloquent.Table("share_card_retrieve_card").Where("share_card_retrieve_id=?", shareCardRetrieve.ID).Updates(map[string]interface{}{
				"receipt_time": time.Now(),
			}).Error
			if err != nil {
				logger.Error("update card issue feedback err:", logger.Field("err", err))
				return
			}

			var userInfo UserInfo
			err := orm.Eloquent.Table("user").Where("uid=?", shareCardRetrieve.Uid).Find(&userInfo).Error
			if err != nil {
				logger.Error("user info err:", logger.Field("err", err))
				return
			}
			if userInfo.Tel == "" {
				return
			}
			err = GtSendMessage([]string{userInfo.Tel}, "【明慧科技】温馨提示：您的收回卡已签收，请及时检查卡带确认功能正常，如有问题，请于签收后48小时内通过小程序发起异常反馈。")
			if err != nil {
				logger.Errorf("SmsSend err:", logger.Field("err", err))
				return
			}
			return
		}

		//if cardIssue.ObtainType == ObtainTypeRetrieveCard {
		//} else if cardIssue.ObtainType == ObtainTypeRentCard {
		//}

		var order Order
		err = orm.Eloquent.Table("order").Where("express_no=?", pushReq.LastResult.Nu).Find(&order).Error
		if err == nil {
			//logger.Error("order err:",logger.Field("err",err))
			err = orm.Eloquent.Table("order").Where("id=?", order.ID).Updates(map[string]interface{}{
				"receipt_time": time.Now(),
			}).Error
			if err != nil {
				logger.Error("update card issue feedback err:", logger.Field("err", err))
				return
			}

			err = orm.Eloquent.Table("order_card").Where("order_id=?", order.ID).Updates(map[string]interface{}{
				"receipt_time": time.Now(),
			}).Error
			if err != nil {
				logger.Error("update card issue feedback err:", logger.Field("err", err))
				return
			}

			var userInfo UserInfo
			err := orm.Eloquent.Table("user").Where("uid=?", order.Uid).Find(&userInfo).Error
			if err != nil {
				logger.Error("user info err:", logger.Field("err", err))
				return
			}
			if userInfo.Tel == "" {
				return
			}
			err = GtSendMessage([]string{userInfo.Tel}, "【明慧科技】温馨提示：您的借卡已签收，请及时检查卡带确认功能正常，如有问题，请于签收后48小时内通过小程序发起异常反馈。")
			if err != nil {
				logger.Errorf("SmsSend err:", logger.Field("err", err))
				return
			}
			return
		}
	}

	// 修改状态  签收时间
	// 推送通知

}

type FunctionUnusualCardListReq struct {
	StoreId      uint32    `json:"store_id"`
	Status       int       `json:"status"`
	GameCardId   int       `json:"game_card_id"`
	SerialNumber string    `json:"serial_number" ` // 编号
	StartTime    time.Time `json:"start_time"`
	EndTime      time.Time `json:"end_time"` // 结束时间
	Page         int       `json:"pageIndex"`
	PageSize     int       `json:"pageSize"`
}

func (m *FunctionUnusualCardListReq) List() ([]GameCardGoods, int64, error) {
	var cardGoods []GameCardGoods
	qs := orm.Eloquent.Table("game_card_goods").Where("function_state=?", 1)
	if m.GameCardId != 0 {
		qs = qs.Where("game_card_id=?", m.GameCardId)
	}
	if m.StoreId != 0 {
		qs = qs.Where("store_id=?", m.StoreId)
	}
	if m.SerialNumber != "" {
		qs = qs.Where("serial_number=?", m.SerialNumber)
	}
	if m.Status != 0 {
		qs = qs.Where("state=?", m.Status)
	}
	if !m.StartTime.IsZero() {
		qs = qs.Where("created_at>?", m.StartTime)
	}
	if !m.EndTime.IsZero() {
		qs = qs.Where("created_at<?", m.EndTime)
	}
	page := m.Page - 1
	if page < 0 {
		page = 0
	}
	if m.PageSize == 0 {
		m.PageSize = 10
	}
	var count int64
	err := qs.Count(&count).Error
	if err != nil {
		logger.Error("count err:", logger.Field("err", err))
		return cardGoods, 0, err
	}

	//totalPage :=int(count) /m.PageSize + 1

	err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&cardGoods).Error
	if err != nil && err != RecordNotFound {
		logger.Error("count err:", logger.Field("err", err))
		return cardGoods, count, err
	}

	if len(cardGoods) > 0 {
		//cardGoods = CannibalizeGameCardGoodsSetInfo(cardGoods)
		if len(cardGoods) > 0 {
			storeIds := make([]uint32, 0)
			gameCardIds := make([]uint32, 0)

			for i, _ := range cardGoods {
				storeIds = append(storeIds, uint32(cardGoods[i].StoreId))
				gameCardIds = append(gameCardIds, uint32(cardGoods[i].GameCardId))
			}

			cardMap := GetGameCardMapByIds(gameCardIds)
			storeMap := GetStoreMapByIds(storeIds)

			for i, _ := range cardGoods {
				gameCard, ok1 := cardMap[cardGoods[i].GameCardId]
				if ok1 {
					cardGoods[i].GameCard = gameCard
				}
				store, ok2 := storeMap[cardGoods[i].StoreId]
				if ok2 {
					cardGoods[i].Store = store
				}
			}
		}
	}

	return cardGoods, count, nil
}

//func GetUserShareCardBillList(uid uint32, page, pageSize int) ([]UserShareCardBill, int, error) {
//	page = page - 1
//	if page < 0 {
//		page = 0
//	}
//	if pageSize == 0 {
//		pageSize = 10
//	}
//	var shareCardBills []UserShareCardBill
//	qs := NewUserShareCardBillQuerySet(DB).UidEq(uid)
//
//	count, err := qs.Total()
//	if err != nil {
//		logger.Error("user share card bill count err:",logger.Field("err",err))
//		return shareCardBills, 0, err
//	}
//	totalPage := count/pageSize + 1
//	err = qs.OrderDescByID().Offset(page * pageSize).Limit(pageSize).All(&shareCardBills)
//	if err != nil && err != RecordNotFound {
//		logger.Error("user share card bill err:",logger.Field("err",err))
//		return shareCardBills, 0, err
//	}
//	if len(shareCardBills) == 0 {
//		return shareCardBills, 0, nil
//	}
//	shareCardBills = UserShareCardBillListSetGame(shareCardBills)
//	return shareCardBills, totalPage, nil
//}
//
//func UserShareCardBillListSetGame(list []UserShareCardBill) []UserShareCardBill {
//	billIds := make([]uint32, 0, len(list))
//	for i, _ := range list {
//		billIds = append(billIds, list[i].ID)
//	}
//	if len(billIds) == 0 {
//		return list
//	}
//	billMap := make(map[uint32][]ShareCardBillGame, 0)
//	var games []ShareCardBillGame
//	err := NewShareCardBillGameQuerySet(DB).UserShareCardBillIdIn(billIds...).All(&games)
//	if err != nil && err != RecordNotFound {
//		logger.Error("share card bill  err:",logger.Field("err",err))
//		return list
//	}
//	gameIds := make([]uint32, 0, len(games))
//	for i, _ := range games {
//		gameIds = append(gameIds, games[i].GameCardId)
//	}
//	cardMap, err := GameCardMap(gameIds)
//	for i, _ := range games {
//		v, ok := cardMap[games[i].GameCardId]
//		if ok {
//			games[i].GameCard = v
//		}
//	}
//
//	for i, _ := range games {
//		billMap[games[i].UserShareCardBillId] = append(billMap[games[i].UserShareCardBillId], games[i])
//	}
//
//	if err != nil {
//		logger.Error("game card map  err:",logger.Field("err",err))
//		return list
//	}
//
//	for i, _ := range list {
//		v, ok := billMap[list[i].ID]
//		if ok {
//			list[i].BillGames = v
//		}
//	}
//
//	return list
//}
