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 ServiceRentComputerShop struct {
}

func (s *ServiceRentComputerShop) RentComputerShopList(ctx context.Context, api rentComputer.RentComputerShop, 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.RentComputerShop{})
	var total int64
	//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.RentComputerShop
	db = db.Limit(limit).Offset(offset)
	if order != "" {
		var OrderStr string
		// 设置有效排序key 防止sql注入
		// 感谢 Tom4t0 提交漏洞信息
		orderMap := make(map[string]bool, 3)
		orderMap["pc_code"] = true
		orderMap["game_id"] = true
		orderMap["operator"] = 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 statisticsLogsComputer []*response.ComputerStatisticsReply1

	for _, statisticsLog := range statisticsLogs {
		/*var gameInfo []*response.GameInfo
		err = json.Unmarshal([]byte(statisticsLog.GameInfo), &gameInfo)
		for i, _ := range gameInfo {
			statisticsLogComputer := new(response.ComputerStatisticsReply1)
			statisticsLogComputer.GameInfo = gameInfo
			statisticsLogComputer.PcCode = statisticsLog.PcCode
			statisticsLogComputer.Operator = statisticsLog.Operator
			statisticsLogComputer.CreateDate = statisticsLog.CreateDate[:10]
			statisticsLogComputer.GameId = gameInfo[i].GameId
			statisticsLogComputer.PullAccountNum = gameInfo[i].PullAccountNum
			statisticsLogComputer.TaskSuccessNum = gameInfo[i].TaskSuccessNum
			statisticsLogsComputer = append(statisticsLogsComputer, statisticsLogComputer)
		}*/
		//gameIdStr:=strconv.Itoa(statisticsLog.GameId)
		//taskStatistics := s.GameTargetInfo(ctx,s.LogicalLog.CurrentDate(),gameIdStr)
		statisticsLogComputer := new(response.ComputerStatisticsReply1)
		statisticsLogComputer.Id = statisticsLog.Id
		//updateTime, _ := time.ParseInLocation("2006-01-02 15:04:05", statisticsLog.UpdateTime, time.Local)
		statisticsLogComputer.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())
		statisticsLogComputer.PayMethod = statisticsLog.PayMethod
		statisticsLogComputer.CreateTime = statisticsLog.CreateTime

		statisticsLogComputer.Name = statisticsLog.Name
		statisticsLogComputer.Description = statisticsLog.Description

		//if isCurrentDate {
		//	statisticsLogComputer.ComputerFeeRate = s.GetStatisticsPcFeeRate(ctx, statisticsLog.PcCode, statisticsLog.GameId)
		//}
		//statisticsLogComputer.ComputerHourAverageRate = statisticsLog.ComputerHourAverageRate
		statisticsLogsComputer = append(statisticsLogsComputer, statisticsLogComputer)
	}
	return statisticsLogsComputer, total, err
}

func (s *ServiceRentComputerShop) GetRentComputerShopNum() int64 {
	var total int64

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

func (s *ServiceRentComputerShop) GetRentComputerShopById(id int) (computerShop response.ComputerStatisticsReply1, err error) {
	var api rentComputer.RentComputerShop
	err = global.GVA_DB.Where("id = ?", id).First(&api).Error
	if err != nil {
		return
	}
	computerShop.Id = api.Id
	computerShop.Name = api.Name
	computerShop.PayMethod = api.PayMethod
	computerShop.Description = api.Description
	computerShop.UpdateTime = api.UpdateTime
	computerShop.CreateTime = api.CreateTime
	return
}

func (s *ServiceRentComputerShop) CurrentDate() (current string) {
	current = time.Now().Format("2006-01-02")
	return
}

func (s *ServiceRentComputerShop) AddRentComputerShop(requestCoding request.ComputerShopRequest) (err error) {
	if !errors.Is(global.GVA_DB.Where("name = ?", requestCoding.Name).First(&rentComputer.RentComputerShop{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在相同供应商名")
	}
	computerShop := new(rentComputer.RentComputerShop)

	computerShop.Name = requestCoding.Name
	computerShop.PayMethod = requestCoding.PayMethod
	computerShop.Description = requestCoding.Description
	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 *ServiceRentComputerShop) EditRentComputerShop(computerShop rentComputer.RentComputerShop) (err error) {
	err = global.GVA_DB.Save(computerShop).Error
	return err
}

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

func (s *ServiceRentComputerShop) DeleteRentComputerShopById(api rentComputer.RentComputerShop) (err error) {
	var entity rentComputer.RentComputerShop
	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
}
