package models

import (
	"errors"
	"fmt"
	"github.com/codinl/go-logger"
	"github.com/gin-gonic/gin"
	"github.com/xuri/excelize/v2"
	orm "go-admin/common/global"
	"go-admin/tools"
	"go-admin/tools/config"
	"gorm.io/gorm"
	"regexp"
	"strings"
	"time"
)

// gen:qs
//
//go:generate goqueryset -in cooperative_business.go
type CooperativeBusiness struct {
	Model

	Name     string    `json:"name"  binding:"required"`    // 供应商名称
	Avatar   string    `json:"avatar" binding:"required"`   // logo
	Address  string    `json:"address"`                     // 地址
	Tel      string    `json:"tel" binding:"required"`      // 电话
	AddTime  time.Time `json:"add_time"`                    // 加入时间
	Username string    `json:"username" binding:"required"` // 用户名
	Password string    `json:"password" binding:"required"` // 密码

	CooperativeMemberDeduct          *CooperativeMemberDeduct          `json:"cooperative_member_deduct" gorm:"-"`
	CooperativeAssistantMemberDeduct *CooperativeAssistantMemberDeduct `json:"cooperative_assistant_member_deduct" gorm:"-"`
	//Identification string    `json:"identification"` // 标识
	// cooperative_business
}

/*
门店
游戏
卡
库存
用户  绑定门店 店员

借卡 订单

*/

type CooperativeMemberDeduct struct {
	Model
	CooperativeBusinessId uint32 `json:"cooperative_business_id"`
	GoldDeduct            uint32 `json:"gold_deduct" binding:"required"`       // 黄金会员提成
	PlatinumDeduct        uint32 `json:"platinum_deduct" binding:"required"`   // 白金会员提成
	BlackGoldDeduct       uint32 `json:"black_gold_deduct" binding:"required"` // 黑金金会员提成

	RenewalGoldDeduct      uint32 `json:"renewal_gold_deduct" binding:"required"`       // 续费黄金会员提成
	RenewalPlatinumDeduct  uint32 `json:"renewal_platinum_deduct" binding:"required"`   // 续费白金会员提成
	RenewalBlackGoldDeduct uint32 `json:"renewal_black_gold_deduct" binding:"required"` // 续费黑金金会员提成
	// cooperative_member_deduct
}

type CooperativeAssistantMemberDeduct struct {
	Model
	CooperativeBusinessId  uint32 `json:"cooperative_business_id" `
	StoreId                uint32 `json:"store_id"  `                //
	GoldDeduct             uint32 `json:"gold_deduct"  `             // 黄金会员提成
	PlatinumDeduct         uint32 `json:"platinum_deduct"  `         // 白金会员提成
	BlackGoldDeduct        uint32 `json:"black_gold_deduct"  `       // 黑金金会员提成
	RenewalGoldDeduct      uint32 `json:"renewal_gold_deduct"`       // 续费黄金会员提成
	RenewalPlatinumDeduct  uint32 `json:"renewal_platinum_deduct"`   // 续费白金会员提成
	RenewalBlackGoldDeduct uint32 `json:"renewal_black_gold_deduct"` // 续费黑金金会员提成
	// cooperative_assistant_member_deduct
}

func (m *CooperativeBusiness) SetMemberDeductConfig() {
	var deductConfig CooperativeMemberDeduct
	err := orm.Eloquent.Table("cooperative_member_deduct").Where("cooperative_business_id=?", m.ID).
		Order("id DESC").Limit(1).Find(&deductConfig).Error
	if err != nil && err != RecordNotFound {
		logger.Error("cooperative err:", err)
		return
	}
	m.CooperativeMemberDeduct = &deductConfig
}

func (m *CooperativeBusiness) SetAssistantMemberDeductConfig(storeId uint32) {
	var assistantDeductConfig CooperativeAssistantMemberDeduct
	err := orm.Eloquent.Table("cooperative_assistant_member_deduct").Where("cooperative_business_id=?", m.ID).
		Where("store_id=?", storeId).Order("id DESC").Limit(1).Find(&assistantDeductConfig).Error
	if err != nil && err != RecordNotFound {
		logger.Error("cooperative err:", err)
		return
	}
	m.CooperativeAssistantMemberDeduct = &assistantDeductConfig
}

const (
	PromotionStateUnSettlement = "un_settlement" // 待发起结算
	PromotionStateFinancePay   = "finance_pay"   // 待财务打款
	PromotionStateSettled      = "settled"       // 已解散
)

// 合作商推广会员
type CooperativeMemberPromotion struct {
	Model
	CooperativeBusinessId uint32 `json:"cooperative_business_id" gorm:"index"`
	CooperativeName       string `json:"cooperative_name"`  // 合作商名称
	GoldCount             uint32 `json:"gold_count"`        // 黄金会员数量
	PlatinumCount         uint32 `json:"platinum_count"`    // 白金会员数量
	BlackGoldCount        uint32 `json:"black_gold_count"`  // 黑金会员数量
	PrivilegeCount        uint32 `json:"privilege_count"`   // 尊享会员数量
	Date                  string `json:"date" gorm:"index"` //
	State                 string `json:"state"`             // 待发起结算  待财务打款 已结算

	RenewalGoldCount      uint32 `json:"renewal_gold_count"`       // 续费黄金会员数量
	RenewalPlatinumCount  uint32 `json:"renewal_platinum_count"`   // 续费白金会员数量
	RenewalBlackGoldCount uint32 `json:"renewal_black_gold_count"` // 续费黑金会员数量
	RenewalPrivilegeCount uint32 `json:"renewal_privilege_count"`  // 续费尊享会员数量

	GoldDeduct      uint32 `json:"gold_deduct" gorm:"-"`       // 黄金会员提成
	PlatinumDeduct  uint32 `json:"platinum_deduct" gorm:"-"`   // 白金会员提成
	BlackGoldDeduct uint32 `json:"black_gold_deduct" gorm:"-"` // 黑金金会员提成

	RenewalGoldDeduct      uint32 `json:"renewal_gold_deduct" gorm:"-"`       // 续费黄金会员提成
	RenewalPlatinumDeduct  uint32 `json:"renewal_platinum_deduct" gorm:"-"`   // 续费白金会员提成
	RenewalBlackGoldDeduct uint32 `json:"renewal_black_gold_deduct" gorm:"-"` // 续费黑金金会员提成

	UpgradeGoldToPlatinumCount  uint32 `json:"upgrade_gold_to_platinum_count" gorm:"default:0"`  // 升级：黄金->白金数量
	UpgradeGoldToBlackCount     uint32 `json:"upgrade_gold_to_black_count" gorm:"default:0"`     // 升级：黄金->黑金数量
	UpgradePlatinumToBlackCount uint32 `json:"upgrade_platinum_to_black_count" gorm:"default:0"` // 升级：白金->黑金数量

	DeductAmount uint32 `json:"deduct_amount" gorm:"-"` // 结算净额
	// cooperative_member_promotion
}

// 合作商推广会员门店  饼图
type CooperativeMemberPromotionStore struct {
	Model
	CooperativeBusinessId       uint32 `json:"cooperative_business_id" gorm:"index"`
	CooperativeName             string `json:"cooperative_name"`                                 // 合作商名称
	StoreId                     uint32 `json:"store_id" gorm:"index"`                            // 门店id
	GoldCount                   uint32 `json:"gold_count"`                                       // 黄金会员数量
	PlatinumCount               uint32 `json:"platinum_count"`                                   // 白金会员数量
	BlackGoldCount              uint32 `json:"black_gold_count"`                                 // 黑金会员数量
	PrivilegeCount              uint32 `json:"privilege_count"`                                  // 尊享会员数量
	Date                        string `json:"date" gorm:"index"`                                //
	RenewalGoldCount            uint32 `json:"renewal_gold_count"`                               // 续费黄金会员数量
	RenewalPlatinumCount        uint32 `json:"renewal_platinum_count"`                           // 续费白金会员数量
	RenewalBlackGoldCount       uint32 `json:"renewal_black_gold_count"`                         // 续费黑金会员数量
	RenewalPrivilegeCount       uint32 `json:"renewal_privilege_count"`                          // 续费尊享会员数量
	UpgradeGoldToPlatinumCount  uint32 `json:"upgrade_gold_to_platinum_count" gorm:"default:0"`  // 升级：黄金->白金数量
	UpgradeGoldToBlackCount     uint32 `json:"upgrade_gold_to_black_count" gorm:"default:0"`     // 升级：黄金->黑金数量
	UpgradePlatinumToBlackCount uint32 `json:"upgrade_platinum_to_black_count" gorm:"default:0"` // 升级：白金->黑金数量
	Store                       *Store `json:"store" gorm:"-"`
	// cooperative_member_promotion_store
}

// 合作商推广会员每天
type CooperativeMemberPromotionDay struct {
	Model
	CooperativeBusinessId       uint32 `json:"cooperative_business_id" gorm:"index"`
	CooperativeName             string `json:"cooperative_name"`                                 // 合作商名称
	GoldCount                   uint32 `json:"gold_count"`                                       // 黄金会员数量
	PlatinumCount               uint32 `json:"platinum_count"`                                   // 白金会员数量
	BlackGoldCount              uint32 `json:"black_gold_count"`                                 // 黑金会员数量
	PrivilegeCount              uint32 `json:"privilege_count"`                                  // 尊享会员数量
	DayTime                     string `json:"day_time" gorm:"index"`                            //
	RenewalGoldCount            uint32 `json:"renewal_gold_count"`                               // 续费黄金会员数量
	RenewalPlatinumCount        uint32 `json:"renewal_platinum_count"`                           // 续费白金会员数量
	RenewalBlackGoldCount       uint32 `json:"renewal_black_gold_count"`                         // 续费黑金会员数量
	RenewalPrivilegeCount       uint32 `json:"renewal_privilege_count"`                          // 续费尊享会员数量
	UpgradeGoldToPlatinumCount  uint32 `json:"upgrade_gold_to_platinum_count" gorm:"default:0"`  // 升级：黄金->白金数量
	UpgradeGoldToBlackCount     uint32 `json:"upgrade_gold_to_black_count" gorm:"default:0"`     // 升级：黄金->黑金数量
	UpgradePlatinumToBlackCount uint32 `json:"upgrade_platinum_to_black_count" gorm:"default:0"` // 升级：白金->黑金数量
	// cooperative_member_promotion_day
}

// 合作商推广会员门店每天   柱状图
type CooperativeMemberPromotionStoreDay struct {
	Model
	CooperativeBusinessId       uint32 `json:"cooperative_business_id" gorm:"index"`
	CooperativeName             string `json:"cooperative_name"`                                 // 合作商名称
	StoreId                     uint32 `json:"store_id" gorm:"index"`                            // 门店id
	GoldCount                   uint32 `json:"gold_count"`                                       // 黄金会员数量
	PlatinumCount               uint32 `json:"platinum_count"`                                   // 白金会员数量
	BlackGoldCount              uint32 `json:"black_gold_count"`                                 // 黑金会员数量
	PrivilegeCount              uint32 `json:"privilege_count"`                                  // 尊享会员数量
	DayTime                     string `json:"day_time" gorm:"index"`                            //
	RenewalGoldCount            uint32 `json:"renewal_gold_count"`                               // 续费黄金会员数量
	RenewalPlatinumCount        uint32 `json:"renewal_platinum_count"`                           // 续费白金会员数量
	RenewalBlackGoldCount       uint32 `json:"renewal_black_gold_count"`                         // 续费黑金会员数量
	RenewalPrivilegeCount       uint32 `json:"renewal_privilege_count"`                          // 续费尊享会员数量
	UpgradeGoldToPlatinumCount  uint32 `json:"upgrade_gold_to_platinum_count" gorm:"default:0"`  // 升级：黄金->白金数量
	UpgradeGoldToBlackCount     uint32 `json:"upgrade_gold_to_black_count" gorm:"default:0"`     // 升级：黄金->黑金数量
	UpgradePlatinumToBlackCount uint32 `json:"upgrade_platinum_to_black_count" gorm:"default:0"` // 升级：白金->黑金数量
	Store                       *Store `json:"store" gorm:"-"`
	// cooperative_member_promotion_store_day
}

type CooperativeDeductSettle struct {
	Model
	CooperativeMemberPromotionId uint32 `json:"cooperative_member_promotion_id" gorm:"index"`
	CooperativeBusinessId        uint32 `json:"cooperative_business_id" gorm:"index"`
	CooperativeName              string `json:"cooperative_name"`  // 合作商名称
	DeductAmount                 uint32 `json:"deduct_amount"`     // 提成金额
	Date                         string `json:"date" gorm:"index"` //
	State                        string `json:"state"`             // 待财务打款 已结算
	GoldCount                    uint32 `json:"gold_count"`        // 黄金会员数量
	PlatinumCount                uint32 `json:"platinum_count"`    // 白金会员数量
	BlackGoldCount               uint32 `json:"black_gold_count"`  // 黑金会员数量
	PrivilegeCount               uint32 `json:"privilege_count"`   // 尊享会员数量
	GoldDeduct                   uint32 `json:"gold_deduct"`       // 黄金会员提成配置
	PlatinumDeduct               uint32 `json:"platinum_deduct"`   // 白金会员提成配置
	BlackGoldDeduct              uint32 `json:"black_gold_deduct"` // 黑金会员提成配置

	RenewalGoldCount      uint32 `json:"renewal_gold_count"`       // 续费黄金会员数量
	RenewalPlatinumCount  uint32 `json:"renewal_platinum_count"`   // 续费白金会员数量
	RenewalBlackGoldCount uint32 `json:"renewal_black_gold_count"` // 续费黑金会员数量
	RenewalPrivilegeCount uint32 `json:"renewal_privilege_count"`  // 续费尊享会员数量

	RenewalGoldDeduct      uint32 `json:"renewal_gold_deduct"`       // 续费黄金会员提成
	RenewalPlatinumDeduct  uint32 `json:"renewal_platinum_deduct"`   // 续费白金会员提成
	RenewalBlackGoldDeduct uint32 `json:"renewal_black_gold_deduct"` // 续费黑金金会员提成
	// cooperative_deduct_settle
}

type CooperativeBusinessListReq struct {
	StartTime time.Time `json:"start_time"` // 开始时间
	EndTime   time.Time `json:"end_time"`   // 结束时间
	Page      int       `json:"pageIndex"`
	PageSize  int       `json:"pageSize"`
}

type CooperativeBusinessListResp struct {
	Count     int64                 `json:"count"`
	List      []CooperativeBusiness `json:"list"`
	PageIndex int                   `json:"pageIndex"`
	TotalPage int                   `json:"total_page"`
}

func (m *CooperativeBusinessListReq) List() ([]CooperativeBusiness, int64, error) {
	var cooperatives []CooperativeBusiness
	qs := orm.Eloquent.Table("cooperative_business")

	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:", err)
		return cooperatives, 0, err
	}

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

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

	return cooperatives, count, nil
}

func CooperativeBusinessListSetCooperativeMemberDeduct(list []CooperativeBusiness) []CooperativeBusiness {
	ids := make([]uint32, 0, len(list))
	for i, _ := range list {
		ids = append(ids, list[i].ID)
	}
	deductMap, err := GetCooperativeMemberDeductMap(ids)
	if err != nil {
		logger.Error("err:", err)
		return list
	}
	for i, _ := range list {
		v, ok := deductMap[list[i].ID]
		if ok {
			list[i].CooperativeMemberDeduct = v
		}
	}

	return list
}

func CooperativeMemberPromotionStoreListSetStore(list []CooperativeMemberPromotionStore) []CooperativeMemberPromotionStore {
	ids := make([]uint32, 0, len(list))
	for i, _ := range list {
		ids = append(ids, list[i].StoreId)
	}
	if len(ids) == 0 {
		return list
	}

	storeMap := GetStoreMapByIds(ids)

	for i, _ := range list {
		v, ok := storeMap[uint64(list[i].StoreId)]
		if ok {
			list[i].Store = v
		}
	}

	return list
}

func CooperativeMemberPromotionStoreDayListSetStore(list []CooperativeMemberPromotionStoreDay) []CooperativeMemberPromotionStoreDay {
	ids := make([]uint32, 0, len(list))
	for i, _ := range list {
		ids = append(ids, list[i].StoreId)
	}
	if len(ids) == 0 {
		return list
	}

	storeMap := GetStoreMapByIds(ids)

	for i, _ := range list {
		v, ok := storeMap[uint64(list[i].StoreId)]
		if ok {
			list[i].Store = v
		}

	}

	return list
}

type CooperativeMemberPromotionReq struct {
	CooperativeBusinessId uint32 `json:"cooperative_business_id"`
	Date                  string `json:"date"` //
	Page                  int    `json:"pageIndex"`
	PageSize              int    `json:"pageSize"`
}

func (m *CooperativeMemberPromotionReq) List() ([]CooperativeMemberPromotion, int64, error) {
	fmt.Println(" m.CooperativeBusinessId", m.CooperativeBusinessId)
	fmt.Println(" m.Date", m.Date)
	var memberPromotions []CooperativeMemberPromotion
	qs := orm.Eloquent.Table("cooperative_member_promotion").Where("cooperative_business_id=?", m.CooperativeBusinessId)
	if m.Date != "" {
		qs = qs.Where("date=?", m.Date)
	}
	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:", err)
		return memberPromotions, 0, err
	}

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

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

	return memberPromotions, count, nil
}

type CooperativeMemberPromotionStoreReq struct {
	CooperativeBusinessId uint32 `json:"cooperative_business_id"`
	//CooperativeMemberPromotionId uint32 `json:"cooperative_member_promotion_id"`
	StoreId  uint32 `json:"store_id"`
	Date     string `json:"date"`
	Page     int    `json:"pageIndex"`
	PageSize int    `json:"pageSize"`
}

func (m *CooperativeMemberPromotionStoreReq) List() ([]CooperativeMemberPromotionStore, int64, error) {
	var memberStorePromotions []CooperativeMemberPromotionStore
	//var promotion CooperativeMemberPromotion
	//err := orm.Eloquent.Table("cooperative_member_promotion").Where("id=?", m.CooperativeMemberPromotionId).Find(&promotion).Error
	//if err != nil {
	//	logger.Error("cooperative member promotion err:", err)
	//	return memberStorePromotions, 0, err
	//}
	//qs := orm.Eloquent.Table("cooperative_member_promotion_store").Where("store_id=?", m.StoreId)
	qs := orm.Eloquent.Table("cooperative_member_promotion_store").Where("cooperative_business_id=?", m.CooperativeBusinessId)
	if m.StoreId != 0 {
		qs = qs.Where("store_id=?", m.StoreId)
	}
	if m.Date != "" {
		qs = qs.Where("date=?", m.Date)
	}
	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:", err)
		return memberStorePromotions, 0, err
	}

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

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

type CooperativeMemberPromotionDayReq struct {
	CooperativeBusinessId uint32 `json:"cooperative_business_id"`
	Page                  int    `json:"pageIndex"`
	PageSize              int    `json:"pageSize"`
}

func (m *CooperativeMemberPromotionDayReq) List() ([]CooperativeMemberPromotionDay, int64, error) {
	var memberDayPromotions []CooperativeMemberPromotionDay
	qs := orm.Eloquent.Table("cooperative_member_promotion_day").Where("cooperative_business_id=?", m.CooperativeBusinessId)

	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:", err)
		return memberDayPromotions, 0, err
	}

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

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

	return memberDayPromotions, count, nil
}

type CooperativeMemberPromotionStoreDayReq struct {
	CooperativeBusinessId uint32 `json:"cooperative_business_id"`
	StoreId               uint32 `json:"store_id"`
	Page                  int    `json:"pageIndex"`
	PageSize              int    `json:"pageSize"`
}

func (m *CooperativeMemberPromotionStoreDayReq) List() ([]CooperativeMemberPromotionStoreDay, int64, error) {

	var memberStoreDayPromotions []CooperativeMemberPromotionStoreDay
	qs := orm.Eloquent.Table("cooperative_member_promotion_store_day").Where("store_id=?", m.StoreId).
		Where("cooperative_business_id=?", m.CooperativeBusinessId)

	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:", err)
		return memberStoreDayPromotions, 0, err
	}

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

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

type CooperativeMemberPromotionSettleReq struct {
	StartTime             time.Time `json:"start_time"` // 开始时间
	EndTime               time.Time `json:"end_time"`   // 结束时间
	Page                  int       `json:"pageIndex"`
	PageSize              int       `json:"pageSize"`
	CooperativeBusinessId uint32    `json:"cooperative_business_id"`
}

func (m *CooperativeMemberPromotionSettleReq) List() ([]CooperativeDeductSettle, int64, error) {
	var cooperatives []CooperativeDeductSettle
	qs := orm.Eloquent.Table("cooperative_deduct_settle")

	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:", err)
		return cooperatives, 0, err
	}

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

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

	return cooperatives, count, nil
}

type RecordExist struct {
	RecordExist int64 `json:"record_exist"`
}

func QueryRecordExist(sql string) (bool, error) {
	var recordExist RecordExist
	existSql := fmt.Sprintf("SELECT EXISTS (%s) AS record_exist;", sql)
	err := orm.Eloquent.Raw(existSql).Scan(&recordExist).Error
	if err != nil {
		logger.Error("err:", err)
		return false, err
	}

	return recordExist.RecordExist == 1, nil
}

type CooperativePromotionMemberReq struct {
	CooperativeBusinessId uint32    `json:"cooperative_business_id"`
	StoreId               uint32    `json:"store_id"`
	StartTime             time.Time `json:"start_time"` // 开始时间
	EndTime               time.Time `json:"end_time"`   // 结束时间
	Page                  int       `json:"pageIndex"`
	PageSize              int       `json:"pageSize"`
}

func (m *CooperativePromotionMemberReq) List() ([]UserInfo, int64, error) {
	var members []UserInfo
	qs := orm.Eloquent.Table("user").Where("cooperative_business_id=?", m.CooperativeBusinessId).
		Where("member_level in (?)", []uint32{2, 4, 5})
	if m.StoreId != 0 {
		qs = qs.Where("store_id=?", m.StoreId)
	}
	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:", err)
		return members, 0, err
	}

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

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

func UserInfoListDesensitization(list []UserInfo) []UserInfo {
	for i, _ := range list {
		list[i].WxName = HideStar(list[i].WxName)
		list[i].Tel = HideStar(list[i].Tel)
		list[i].CooperativeName = HideStar(list[i].CooperativeName)
		list[i].ShopAssistantName = HideStar(list[i].ShopAssistantName)
		list[i].WxOpenID = HideStar(list[i].WxOpenID)

		list[i].Gender = 0
		list[i].City = ""
		list[i].Province = ""
		list[i].Deposit = 0
		list[i].UserType = 0
	}
	return list
}

func HideStar(str string) (result string) {
	if str == "" {
		return "***"
	}
	if strings.Contains(str, "@") { // 邮箱
		res := strings.Split(str, "@")
		if len(res[0]) < 3 {
			resString := "***"
			result = resString + "@" + res[1]
		} else {
			res2 := Substr2(str, 0, 3)
			resString := res2 + "***"
			result = resString + "@" + res[1]
		}
		return result
	} else {
		reg := `^1[0-9]\d{9}$`
		rgx := regexp.MustCompile(reg)
		mobileMatch := rgx.MatchString(str)
		if mobileMatch { // 手机号
			result = Substr2(str, 0, 3) + "****" + Substr2(str, 7, 11)
		} else {
			nameRune := []rune(str)
			lens := len(nameRune)
			if lens <= 1 {
				result = "***"
			} else if lens == 2 {
				result = string(nameRune[:1]) + "*"
			} else if lens == 3 {
				result = string(nameRune[:1]) + "*" + string(nameRune[2:3])
			} else if lens == 4 {
				result = string(nameRune[:1]) + "**" + string(nameRune[lens-1:lens])
			} else if lens > 4 {
				result = string(nameRune[:2]) + "***" + string(nameRune[lens-2:lens])
			}
		}
		return
	}
}

func Substr2(str string, start int, end int) string {
	rs := []rune(str)
	return string(rs[start:end])
}

func GetCooperativeMemberDeductMap(ids []uint32) (map[uint32]*CooperativeMemberDeduct, error) {
	deductMap := make(map[uint32]*CooperativeMemberDeduct, 0)
	if len(ids) == 0 {
		return deductMap, nil
	}
	var deducts []CooperativeMemberDeduct
	err := orm.Eloquent.Table("cooperative_member_deduct").Where("cooperative_business_id in (?)", ids).Find(&deducts).Error
	if err != nil {
		logger.Error("deducts err:", err)
		return deductMap, err
	}
	for i, _ := range deducts {
		deductMap[deducts[i].CooperativeBusinessId] = &deducts[i]
	}

	return deductMap, nil
}

func GetCooperativeAssistantMemberDeductMap(ids []uint32) (map[uint32]*CooperativeAssistantMemberDeduct, error) {
	deductMap := make(map[uint32]*CooperativeAssistantMemberDeduct, 0)
	if len(ids) == 0 {
		return deductMap, nil
	}
	var deducts []CooperativeAssistantMemberDeduct
	err := orm.Eloquent.Table("cooperative_assistant_member_deduct").Where("store_id in (?)", ids).Find(&deducts).Error
	if err != nil {
		logger.Error("deducts err:", err)
		return deductMap, err
	}
	for i, _ := range deducts {
		deductMap[deducts[i].StoreId] = &deducts[i]
	}

	return deductMap, nil
}

type CooperativeMemberPromotionStatistic struct {
	Model
	CooperativeBusinessId uint32 `json:"cooperative_business_id" gorm:"index"`
	CooperativeName       string `json:"cooperative_name"`      // 合作商名称
	GoldCount             uint32 `json:"gold_count"`            // 黄金会员数量
	PlatinumCount         uint32 `json:"platinum_count"`        // 白金会员数量
	BlackGoldCount        uint32 `json:"black_gold_count"`      // 黑金会员数量
	PrivilegeCount        uint32 `json:"privilege_count"`       // 尊享会员数量
	DayTime               string `json:"day_time" gorm:"index"` //

	RenewalGoldCount      uint32 `json:"renewal_gold_count"`       // 续费黄金会员数量
	RenewalPlatinumCount  uint32 `json:"renewal_platinum_count"`   // 续费白金会员数量
	RenewalBlackGoldCount uint32 `json:"renewal_black_gold_count"` // 续费黑金会员数量
	RenewalPrivilegeCount uint32 `json:"renewal_privilege_count"`  // 续费尊享会员数量
	Date                  string `json:"date" gorm:"index"`        // 日期
	StoreId               uint32 `json:"store_id" gorm:"index"`    // 门店id

	UpgradeGoldToPlatinumCount  uint32 `json:"upgrade_gold_to_platinum_count" gorm:"default:0"`  // 升级：黄金->白金数量
	UpgradeGoldToBlackCount     uint32 `json:"upgrade_gold_to_black_count" gorm:"default:0"`     // 升级：黄金->黑金数量
	UpgradePlatinumToBlackCount uint32 `json:"upgrade_platinum_to_black_count" gorm:"default:0"` // 升级：白金->黑金数量

	Store *Store `json:"store" gorm:"-"`
	// cooperative_member_promotion_day
}

type CooperativeMemberPromotionStatisticReq struct {
	Type                  uint32 `json:"type"`                    // 1-按天展示 2-按月展示
	CooperativeBusinessId uint32 `json:"cooperative_business_id"` // 合作商id
	StartDate             string `json:"start_date"`              // 开始月份
	EndDate               string `json:"end_date"`                // 结束月份
	StoreId               uint32 `json:"store_id"`                // 门店ID
	Page                  int    `json:"pageIndex"`               // 页码
	PageSize              int    `json:"pageSize"`                // 每页条数
	IsExport              uint32 `json:"is_export"`               // 1-导出
}

type CooperativeMemberPromotionStatisticListResp struct {
	List      []CooperativeMemberPromotionStatistic `json:"list"`
	Total     int64                                 `json:"total"`      // 总条数
	PageIndex int                                   `json:"pageIndex"`  // 页码
	PageSize  int                                   `json:"pageSize"`   // 每页展示条数
	ExportUrl string                                `json:"export_url"` // 导出excel地址
}

func (m *CooperativeMemberPromotionStatisticReq) List(c *gin.Context) (*CooperativeMemberPromotionStatisticListResp, error) {
	resp := &CooperativeMemberPromotionStatisticListResp{
		PageIndex: m.Page,
		PageSize:  m.PageSize,
	}
	list := make([]CooperativeMemberPromotionStatistic, 0)

	// 非管理员才判断所属门店
	var validStoreList []uint32
	if !(tools.GetRoleName(c) == "admin" || tools.GetRoleName(c) == "系统管理员") {
		sysUser, err := GetSysUserByCtx(c)
		if err != nil {
			return nil, err
		}

		// 返回sysUser未过期的门店id列表
		validStoreList = GetValidStoreIDs(sysUser.StoreData)
		if m.StoreId != 0 {
			if !Contains(validStoreList, m.StoreId) {
				return nil, errors.New("您没有该门店权限")
			}
		} else {
			if len(validStoreList) == 0 {
				return nil, errors.New("用户未绑定门店")
			}
		}
	}

	page := m.Page - 1
	if page < 0 {
		page = 0
	}
	if m.PageSize == 0 {
		m.PageSize = 10
	}
	startTime := time.Time{}
	endTime := time.Time{}
	if m.StartDate != "" {
		format := ""
		if m.Type == 1 {
			//format = DateFormat
			format = time.RFC3339
		} else {
			format = MDateFormat
		}
		startTime, _ = time.Parse(format, m.StartDate)
	}
	if m.EndDate != "" {
		format := ""
		if m.Type == 1 {
			//format = DateFormat
			format = time.RFC3339
		} else {
			format = MDateFormat
		}
		endTime, _ = time.Parse(format, m.EndDate)
	}

	var count int64

	var err error
	qs := new(gorm.DB)
	switch m.Type {
	case 1:
		if m.StoreId != 0 {
			var memberDayStorePromotions []CooperativeMemberPromotionStoreDay
			qs = orm.Eloquent.Table("cooperative_member_promotion_store_day").Where("store_id=?", m.StoreId).
				Where("cooperative_business_id=?", m.CooperativeBusinessId)
			if len(validStoreList) > 0 {
				if len(validStoreList) == 1 {
					qs = qs.Where("store_id = ?", validStoreList[0])
				} else {
					qs = qs.Where("store_id IN (?)", validStoreList)
				}
			}
			if !startTime.IsZero() {
				qs = qs.Where("created_at>?", startTime)
			}
			if !endTime.IsZero() {
				qs = qs.Where("created_at<?", endTime)
			}

			err = qs.Count(&count).Error
			if err != nil {
				logger.Error("count err:", err)
				return nil, err
			}

			if m.IsExport == 1 {
				err = qs.Order("id DESC").Find(&memberDayStorePromotions).Error
			} else {
				err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&memberDayStorePromotions).Error
			}
			list = CooperativeMemberPromotionStoreDayToStatistic(memberDayStorePromotions)
		} else {
			var memberDayPromotions []CooperativeMemberPromotionDay
			qs = orm.Eloquent.Table("cooperative_member_promotion_day").Where("cooperative_business_id=?", m.CooperativeBusinessId)
			if len(validStoreList) > 0 {
				if len(validStoreList) == 1 {
					qs = qs.Where("store_id = ?", validStoreList[0])
				} else {
					qs = qs.Where("store_id IN (?)", validStoreList)
				}
			}
			if !startTime.IsZero() {
				qs = qs.Where("created_at>?", startTime)
			}
			if !endTime.IsZero() {
				qs = qs.Where("created_at<?", endTime)
			}

			err = qs.Count(&count).Error
			if err != nil {
				logger.Error("count err:", err)
				return nil, err
			}

			if m.IsExport == 1 {
				err = qs.Order("id DESC").Find(&memberDayPromotions).Error
			} else {
				err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&memberDayPromotions).Error
			}
			list = CooperativeMemberPromotionDayListToStatistic(memberDayPromotions)
		}
	case 2:
		if m.StoreId != 0 {
			var memberStorePromotions []CooperativeMemberPromotionStore
			qs = orm.Eloquent.Table("cooperative_member_promotion_store").Where("cooperative_business_id=?", m.CooperativeBusinessId)
			if len(validStoreList) > 0 {
				if len(validStoreList) == 1 {
					qs = qs.Where("store_id = ?", validStoreList[0])
				} else {
					qs = qs.Where("store_id IN (?)", validStoreList)
				}
			}
			if m.StoreId != 0 {
				qs = qs.Where("store_id=?", m.StoreId)
			}
			//if m.Date != "" {
			//	qs = qs.Where("date=?", m.Date)
			//}
			if !startTime.IsZero() {
				qs = qs.Where("created_at>?", startTime)
			}
			if !endTime.IsZero() {
				qs = qs.Where("created_at<?", endTime)
			}

			err = qs.Count(&count).Error
			if err != nil {
				logger.Error("count err:", err)
				return nil, err
			}

			if m.IsExport == 1 {
				err = qs.Order("id DESC").Find(&memberStorePromotions).Error
			} else {
				err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&memberStorePromotions).Error
			}
			list = CooperativeMemberPromotionStoreToStatistic(memberStorePromotions)
		} else {
			var memberPromotions []CooperativeMemberPromotion
			qs = orm.Eloquent.Table("cooperative_member_promotion").Where("cooperative_business_id=?", m.CooperativeBusinessId)
			//if len(validStoreList) > 0 {
			//	if len(validStoreList) == 1 {
			//		qs = qs.Where("store_id = ?", validStoreList[0])
			//	} else {
			//		qs = qs.Where("store_id IN (?)", validStoreList)
			//	}
			//}
			//if m.Date != "" {
			//	qs = qs.Where("date=?", m.Date)
			//}
			if !startTime.IsZero() {
				qs = qs.Where("created_at>?", startTime)
			}
			if !endTime.IsZero() {
				qs = qs.Where("created_at<?", endTime)
			}

			err = qs.Count(&count).Error
			if err != nil {
				logger.Error("count err:", err)
				return nil, err
			}

			if m.IsExport == 1 {
				err = qs.Order("id DESC").Find(&memberPromotions).Error
			} else {
				err = qs.Order("id DESC").Offset(page * m.PageSize).Limit(m.PageSize).Find(&memberPromotions).Error
			}
			list = CooperativeMemberPromotionToStatistic(memberPromotions)
		}
	}
	if err != nil && err != RecordNotFound {
		logger.Error("count err:", err)
		return nil, err
	}

	// 添加门店信息
	err = cooperativeMemberPromotionAddStoreInfo(list)
	if err != nil {
		logger.Error("cooperativeMemberPromotionAddStoreInfo err:", err)
		return nil, err
	}

	//err = qs.Count(&count).Error
	//if err != nil {
	//	logger.Error("count err:", err)
	//	return nil, err
	//}

	if m.IsExport == 1 {
		fileName, err := promotionStatisticListExport(list)
		if err != nil {
			logger.Error("count err:", err)
			return nil, err
		}

		resp.ExportUrl = fileName
	} else {
		resp.List = list
		resp.Total = count

	}

	return resp, nil
}

// 添加门店信息
func cooperativeMemberPromotionAddStoreInfo(list []CooperativeMemberPromotionStatistic) error {
	// 查询门店信息
	var storeList []Store
	err := orm.Eloquent.Table("store").Find(&storeList).Error
	if err != nil {
		logger.Errorf("err:", err)
		return err
	}
	storeMap := make(map[uint32]Store, 0)
	for i, _ := range storeList {
		storeMap[storeList[i].ID] = storeList[i]
	}

	for i, _ := range list {
		store := storeMap[list[i].StoreId]
		list[i].Store = &store
	}

	return nil
}

// 导出租卡会员统计excel
func promotionStatisticListExport(list []CooperativeMemberPromotionStatistic) (string, error) {
	file := excelize.NewFile()
	fSheet := "Sheet1"

	url := config.ExportConfig.Url
	fileName := time.Now().Format(TimeFormat) + "租卡会员统计" + ".xlsx"
	fmt.Println("url fileName:", url+fileName)

	title1 := []interface{}{"合作商", "门店", "开通会员", "开通会员", "开通会员", "续费会员", "续费会员", "续费会员",
		"升级会员数", "升级会员数", "升级会员数", "日期"}
	title2 := []interface{}{"合作商", "门店", "黄金会员_数量", "白金会员_数量", "黑金会员_数量", "黄金会员_数量", "白金会员_数量",
		"黑金会员_数量", "黄金->白金", "黄金->黑金", "白金->黑金", "日期"}
	for i, _ := range title1 {
		cell, _ := excelize.CoordinatesToCellName(1+i, 1)
		err := file.SetCellValue(fSheet, cell, title1[i])
		if err != nil {
			logger.Error("file set value err:", err)
		}
	}

	for i, _ := range title2 {
		cell, _ := excelize.CoordinatesToCellName(1+i, 2)
		err := file.SetCellValue(fSheet, cell, title2[i])
		if err != nil {
			logger.Error("file set value err:", err)
		}
	}

	var row []interface{}
	nExcelStartRow := 0

	for i := 0; i < len(list); i++ {
		row = []interface{}{
			list[i].CooperativeName,             // 合作商
			list[i].Store.Name,                  // 门店名称
			list[i].GoldCount,                   // 开通会员：黄金会员数量
			list[i].PlatinumCount,               // 开通会员：白金会员数量
			list[i].BlackGoldCount,              // 开通会员：黑金会员数量
			list[i].RenewalGoldCount,            // 续费会员：黄金会员数量
			list[i].RenewalPlatinumCount,        // 续费会员：白金会员数量
			list[i].RenewalBlackGoldCount,       // 续费会员：黑金会员数量
			list[i].UpgradeGoldToPlatinumCount,  // 升级：黄金->白金数量
			list[i].UpgradeGoldToBlackCount,     // 升级：黄金->黑金数量
			list[i].UpgradePlatinumToBlackCount, // 升级：白金->黑金数量
			list[i].Date,
		}

		for j, _ := range row {
			cell, _ := excelize.CoordinatesToCellName(1+j, nExcelStartRow+3)
			err := file.SetCellValue(fSheet, cell, row[j])
			if err != nil {
				logger.Error("file set value err:", err)
			}
		}
		nExcelStartRow++
	}

	// 设置所有单元格的样式: 居中、加边框
	style, _ := file.NewStyle(`{"alignment":{"horizontal":"center","vertical":"center"},
	"border":[{"type":"left","color":"000000","style":1},
	{"type":"top","color":"000000","style":1},
	{"type":"right","color":"000000","style":1},
	{"type":"bottom","color":"000000","style":1}]}`)

	// 设置单元格的样式: 居中、加边框、自动换行
	style1, _ := file.NewStyle(`{"alignment":{"horizontal":"center","vertical":"center","wrap_text":true},
	"border":[{"type":"left","color":"000000","style":1},
	{"type":"top","color":"000000","style":1},
	{"type":"right","color":"000000","style":1},
	{"type":"bottom","color":"000000","style":1}]}`)

	endRow := fmt.Sprintf("L%d", nExcelStartRow+2)
	// 合并单元格
	_ = file.MergeCell(fSheet, "A1", "A2")
	_ = file.MergeCell(fSheet, "B1", "B2")
	_ = file.MergeCell(fSheet, "C1", "E1")
	_ = file.MergeCell(fSheet, "F1", "H1")
	_ = file.MergeCell(fSheet, "I1", "K1")
	_ = file.MergeCell(fSheet, "L1", "L2")
	//设置单元格高度
	file.SetRowHeight("Sheet1", 1, 18)
	file.SetRowHeight("Sheet1", 2, 18)
	// 设置单元格大小
	file.SetColWidth("Sheet1", "A", "A", 15)
	file.SetColWidth("Sheet1", "B", "B", 20)
	// 从列 C 到列 K，逐一设置宽度为 20
	for col := 'C'; col <= 'K'; col++ {
		colName := string(col)
		file.SetColWidth("Sheet1", colName, colName, 12)
	}
	// 应用样式到整个表格
	_ = file.SetCellStyle("Sheet1", "A1", "L1", style1)
	_ = file.SetCellStyle("Sheet1", "A2", endRow, style)

	fmt.Println("save fileName:", config.ExportConfig.Path+fileName)
	if err := file.SaveAs(config.ExportConfig.Path + fileName); err != nil {
		fmt.Println(err)
	}
	return url + fileName, nil
}

func CooperativeMemberPromotionDayListToStatistic(list []CooperativeMemberPromotionDay) []CooperativeMemberPromotionStatistic {
	promotions := make([]CooperativeMemberPromotionStatistic, 0, len(list))
	if len(list) == 0 {
		return promotions
	}
	for i, _ := range list {
		promotions = append(promotions, CooperativeMemberPromotionStatistic{
			Model:                       list[i].Model,
			CooperativeBusinessId:       list[i].CooperativeBusinessId,
			CooperativeName:             list[i].CooperativeName,
			GoldCount:                   list[i].GoldCount,
			PlatinumCount:               list[i].PlatinumCount,
			BlackGoldCount:              list[i].BlackGoldCount,
			PrivilegeCount:              list[i].PrivilegeCount,
			DayTime:                     list[i].DayTime,
			RenewalGoldCount:            list[i].RenewalGoldCount,
			RenewalPlatinumCount:        list[i].RenewalPlatinumCount,
			RenewalBlackGoldCount:       list[i].RenewalBlackGoldCount,
			RenewalPrivilegeCount:       list[i].RenewalPrivilegeCount,
			UpgradeGoldToPlatinumCount:  list[i].UpgradeGoldToPlatinumCount,
			UpgradeGoldToBlackCount:     list[i].UpgradeGoldToBlackCount,
			UpgradePlatinumToBlackCount: list[i].UpgradePlatinumToBlackCount,
			//Date:                  list[i].DayTime,
		})
	}
	return promotions
}

func CooperativeMemberPromotionStoreDayToStatistic(list []CooperativeMemberPromotionStoreDay) []CooperativeMemberPromotionStatistic {
	promotions := make([]CooperativeMemberPromotionStatistic, 0, len(list))
	if len(list) == 0 {
		return promotions
	}
	CooperativeMemberPromotionStoreDayListSetStore(list)
	for i, _ := range list {
		promotions = append(promotions, CooperativeMemberPromotionStatistic{
			Model:                       list[i].Model,
			CooperativeBusinessId:       list[i].CooperativeBusinessId,
			CooperativeName:             list[i].CooperativeName,
			GoldCount:                   list[i].GoldCount,
			PlatinumCount:               list[i].PlatinumCount,
			BlackGoldCount:              list[i].BlackGoldCount,
			PrivilegeCount:              list[i].PrivilegeCount,
			DayTime:                     list[i].DayTime,
			RenewalGoldCount:            list[i].RenewalGoldCount,
			RenewalPlatinumCount:        list[i].RenewalPlatinumCount,
			RenewalBlackGoldCount:       list[i].RenewalBlackGoldCount,
			RenewalPrivilegeCount:       list[i].RenewalPrivilegeCount,
			UpgradeGoldToPlatinumCount:  list[i].UpgradeGoldToPlatinumCount,
			UpgradeGoldToBlackCount:     list[i].UpgradeGoldToBlackCount,
			UpgradePlatinumToBlackCount: list[i].UpgradePlatinumToBlackCount,
			//Date:                  list[i].DayTime,
			StoreId: list[i].StoreId,
			Store:   list[i].Store,
		})
	}
	return promotions
}

func CooperativeMemberPromotionToStatistic(list []CooperativeMemberPromotion) []CooperativeMemberPromotionStatistic {
	promotions := make([]CooperativeMemberPromotionStatistic, 0, len(list))
	if len(list) == 0 {
		return promotions
	}
	for i, _ := range list {
		promotions = append(promotions, CooperativeMemberPromotionStatistic{
			Model:                       list[i].Model,
			CooperativeBusinessId:       list[i].CooperativeBusinessId,
			CooperativeName:             list[i].CooperativeName,
			GoldCount:                   list[i].GoldCount,
			PlatinumCount:               list[i].PlatinumCount,
			BlackGoldCount:              list[i].BlackGoldCount,
			PrivilegeCount:              list[i].PrivilegeCount,
			RenewalGoldCount:            list[i].RenewalGoldCount,
			RenewalPlatinumCount:        list[i].RenewalPlatinumCount,
			RenewalBlackGoldCount:       list[i].RenewalBlackGoldCount,
			RenewalPrivilegeCount:       list[i].RenewalPrivilegeCount,
			Date:                        list[i].Date,
			UpgradePlatinumToBlackCount: list[i].UpgradePlatinumToBlackCount,
			UpgradeGoldToBlackCount:     list[i].UpgradeGoldToBlackCount,
			UpgradeGoldToPlatinumCount:  list[i].UpgradeGoldToPlatinumCount,
			//StoreId:               list[i].StoreId,
		})
	}
	return promotions
}

func CooperativeMemberPromotionStoreToStatistic(list []CooperativeMemberPromotionStore) []CooperativeMemberPromotionStatistic {
	promotions := make([]CooperativeMemberPromotionStatistic, 0, len(list))
	if len(list) == 0 {
		return promotions
	}
	CooperativeMemberPromotionStoreListSetStore(list)
	for i, _ := range list {
		promotions = append(promotions, CooperativeMemberPromotionStatistic{
			Model:                 list[i].Model,
			CooperativeBusinessId: list[i].CooperativeBusinessId,
			CooperativeName:       list[i].CooperativeName,
			GoldCount:             list[i].GoldCount,
			PlatinumCount:         list[i].PlatinumCount,
			BlackGoldCount:        list[i].BlackGoldCount,
			PrivilegeCount:        list[i].PrivilegeCount,
			//DayTime:               list[i].DayTime,
			RenewalGoldCount:            list[i].RenewalGoldCount,
			RenewalPlatinumCount:        list[i].RenewalPlatinumCount,
			RenewalBlackGoldCount:       list[i].RenewalBlackGoldCount,
			RenewalPrivilegeCount:       list[i].RenewalPrivilegeCount,
			Date:                        list[i].Date,
			StoreId:                     list[i].StoreId,
			Store:                       list[i].Store,
			UpgradeGoldToPlatinumCount:  list[i].UpgradeGoldToPlatinumCount,
			UpgradeGoldToBlackCount:     list[i].UpgradeGoldToBlackCount,
			UpgradePlatinumToBlackCount: list[i].UpgradePlatinumToBlackCount,
		})
	}
	return promotions
}
