package rentComputer

import (
	"context"
	"errors"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"log-server/global"
	"log-server/model/rentComputer"
	"log-server/model/rentComputer/request"
	"log-server/model/rentComputer/response"
	"time"
)

type ServiceRentSetMeal struct {
}

func (s *ServiceRentSetMeal) RentSetMealList(ctx context.Context, api rentComputer.RentSetMeal, info request.PageInfo, order string, desc bool) (interface{}, int64, error) {
	//global.GVA_LOG.Info("service----GetComputerShopList----strat")
	//date := api.CreateTime
	//isCurrentDate := false
	//if date == "" {
	//	date = s.CurrentDate()
	//	isCurrentDate = true
	//}
	db := global.GVA_DB.Model(&rentComputer.RentSetMeal{})
	var total int64
	db = db.Select("rent_set_meal.id, rent_set_meal.update_time,rent_set_meal.create_time,rent_set_meal.name," +
		"rent_set_meal.remark,rent_set_meal.rent_price,rent_set_meal.price_type,rent_set_meal.rent_price_day,rent_set_meal.shop_id,s.name as shop_name")
	db = db.Joins("left join rent_computer_shop s on s.id = rent_set_meal.shop_id")
	//db = db.Distinct("pc_code", "id", "operator", "create_date", "GROUP_CONCAT(game_id) AS game_ids")
	//db = db.Where("create_date = ?", date)
	//if api.Operator != "" {
	//	db = db.Where("operator like ?", "%"+api.Operator+"%")
	//}
	//if api.PcCode != "" {
	//	db = db.Where("pc_code = ?", api.PcCode)
	//}
	//if api.GameId != 0 {
	//	db = db.Where("game_id = ?", api.GameId)
	//}
	//.Select("count(distinct(name))").Count(&count)
	//err := db.Count(&total).Error
	//err := db.Select("count(distinct(pc_code))").Count(&total).Error
	//db = db.Group("pc_code")
	//db2 := global.GVA_DB.Model(&log.LogComputer{})
	//db2 = db2.Select("count(distinct(pc_code))")
	//db2 = db2.Where("create_date = ?", date)
	//if api.Operator != "" {
	//	db2 = db2.Where("operator like ?", "%"+api.Operator+"%")
	//}
	//if api.PcCode != "" {
	//	db2 = db2.Where("pc_code = ?", api.PcCode)
	//}
	err := db.Count(&total).Error
	//if err != nil {
	//	return nil, 0, err
	//}
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	//var statisticsLogs []*log.LogComputer
	//var statisticsLogs []*rentComputer.RentSetMeal
	var statisticsLogs []*response.SetMealStatisticsReply1
	db = db.Limit(limit).Offset(offset)
	if order != "" {
		var OrderStr string
		// 设置有效排序key 防止sql注入
		// 感谢 Tom4t0 提交漏洞信息
		orderMap := make(map[string]bool, 3)
		orderMap["id"] = true
		if orderMap[order] {
			if desc {
				OrderStr = order + " desc"
			} else {
				OrderStr = order
			}
		} else { // didn't matched any order key in `orderMap`
			global.GVA_LOG.Error("获取失败!", zap.Error(err))
			return statisticsLogs, total, err
		}
		err = db.Order(OrderStr).Find(&statisticsLogs).Error
	} else {
		err = db.Order("id").Find(&statisticsLogs).Error
	}
	if err != nil {
		return nil, 0, err
	}
	var statisticsSetMeals []*response.SetMealStatisticsReply1

	for _, statisticsLog := range statisticsLogs {

		//gameIdStr:=strconv.Itoa(statisticsLog.GameId)
		//taskStatistics := s.GameTargetInfo(ctx,s.LogicalLog.CurrentDate(),gameIdStr)
		statisticsSetMeal := new(response.SetMealStatisticsReply1)
		statisticsSetMeal.Id = statisticsLog.Id
		//updateTime, _ := time.ParseInLocation("2006-01-02 15:04:05", statisticsLog.UpdateTime, time.Local)
		statisticsSetMeal.UpdateTime = statisticsLog.UpdateTime
		//global.GVA_LOG.Info(statisticsLog.CreateTime.String())
		//createTime, _ := time.ParseInLocation("2006-01-02 15:04:05", statisticsLog.CreateTime, time.Local)
		//global.GVA_LOG.Info(createTime.String())
		statisticsSetMeal.CreateTime = statisticsLog.CreateTime
		statisticsSetMeal.Name = statisticsLog.Name
		statisticsSetMeal.Remark = statisticsLog.Remark
		statisticsSetMeal.PriceType = statisticsLog.PriceType
		statisticsSetMeal.RentPriceDay = statisticsLog.RentPriceDay
		statisticsSetMeal.RentPrice = statisticsLog.RentPrice
		statisticsSetMeal.ShopId = statisticsLog.ShopId
		statisticsSetMeal.ShopName = statisticsLog.ShopName
		//if isCurrentDate {
		//	statisticsLogComputer.ComputerFeeRate = s.GetStatisticsPcFeeRate(ctx, statisticsLog.PcCode, statisticsLog.GameId)
		//}
		//statisticsLogComputer.ComputerHourAverageRate = statisticsLog.ComputerHourAverageRate
		statisticsSetMeals = append(statisticsSetMeals, statisticsSetMeal)
	}
	return statisticsSetMeals, total, err
}

func (s *ServiceRentSetMeal) GetRentSetMealNum() int64 {
	var total int64

	db := global.GVA_DB.Model(&rentComputer.RentSetMeal{})
	db = db.Distinct("id")
	_ = db.Count(&total).Error
	return total
}

func (s *ServiceRentSetMeal) GetRentSetMealById(id int) (computerShop response.SetMealStatisticsReply1, err error) {
	var api rentComputer.RentSetMeal
	err = global.GVA_DB.Where("id = ?", id).First(&api).Error
	if err != nil {
		return
	}
	computerShop.Id = api.Id
	computerShop.Name = api.Name
	computerShop.Remark = api.Remark
	computerShop.RentPrice = api.RentPrice
	computerShop.PriceType = api.PriceType
	computerShop.RentPriceDay = api.RentPriceDay
	computerShop.ShopId = api.ShopId
	computerShop.UpdateTime = api.UpdateTime
	computerShop.CreateTime = api.CreateTime
	return
}

func (s *ServiceRentSetMeal) AddRentSetMeal(requestCoding request.SetMealRequest) (err error) {
	//fmt.Printf("%#v\n", &requestCoding)
	if !errors.Is(global.GVA_DB.Where("name = ? and price_type = ? and shop_id = ?", requestCoding.Name, requestCoding.PriceType, requestCoding.ShopId).First(&rentComputer.RentSetMeal{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在相同套餐")
	}
	computerShop := new(rentComputer.RentSetMeal)

	priceType := requestCoding.PriceType
	rentPrice := requestCoding.RentPrice
	rentPriceDay := float64(0)
	computerShop.Name = requestCoding.Name
	computerShop.Remark = requestCoding.Remark

	if priceType == 0 {
		rentPriceDay = float64(int(rentPrice))
	} else if priceType == 1 {
		rentPriceDay = rentPrice / 7
	} else if priceType == 2 {
		rentPriceDay = rentPrice / 30
	}
	computerShop.PriceType = priceType
	computerShop.RentPrice = rentPrice
	computerShop.RentPriceDay = rentPriceDay
	computerShop.ShopId = requestCoding.ShopId
	computerShop.CreateTime = time.Now().Format("2006-01-02 15:04:05")
	computerShop.UpdateTime = time.Now().Format("2006-01-02 15:04:05")
	//key := codeListCacheKey
	//_ = s.cache.DelBatheHsCache(context.Background(), key)
	return global.GVA_DB.Create(&computerShop).Error
}

func (s *ServiceRentSetMeal) EditRentSetMeal(setMeal rentComputer.RentSetMeal) (err error) {
	priceType := setMeal.PriceType
	rentPrice := setMeal.RentPrice
	rentPriceDay := float64(0)
	if priceType == 0 {
		rentPriceDay = float64(int(rentPrice))
	} else if priceType == 1 {
		rentPriceDay = rentPrice / 7
	} else if priceType == 2 {
		rentPriceDay = rentPrice / 30
	}
	setMeal.RentPriceDay = rentPriceDay
	err = global.GVA_DB.Save(setMeal).Error
	return err
}

func (s *ServiceRentSetMeal) DeleteRentSetMealByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]rentComputer.RentSetMeal{}, "id in ?", ids.Ids).Error
	return err
}

func (s *ServiceRentSetMeal) DeleteRentSetMealById(api rentComputer.RentSetMeal) (err error) {
	var entity rentComputer.RentSetMeal
	err = global.GVA_DB.Where("id = ?", api.Id).First(&entity).Error // 根据id查询api记录
	if errors.Is(err, gorm.ErrRecordNotFound) {                      // api记录不存在
		return err
	}
	return global.GVA_DB.Delete(&entity).Error
}
