package task

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/go-redis/redis/v8"
	"go.uber.org/zap"
	"log-server/global"
	"log-server/model/log/request"
	"log-server/model/task"
	"log-server/model/task/control"
	"log-server/utils"
	"strconv"
	"time"
)

type SyncData struct {
	GameTask GameTask
}

func (s *SyncData) SyncXmyGameData(date string) (mps map[int]control.XmyPayRequestReplyData, err error) {
	xmyUrl := "http://api.sheepsdk.17xmy.com/foreign/api/get_youhua_data.php"
	xmyParams := map[string]string{
		"start_day": date,
		"end_day":   date,
	}
	requestData := new(control.XmyReply)
	xmyByteData, err := utils.HttpGet(xmyUrl, xmyParams)
	if err != nil {
		return
	}
	_ = json.Unmarshal(xmyByteData, &requestData)
	mps = map[int]control.XmyPayRequestReplyData{}
	for _, data := range requestData.Data.List {
		gameId, _ := strconv.Atoi(data.GameId)
		mps[gameId] = data
	}
	return
}

func (s *SyncData) SyncXmyFreeData(date string, gameId int) (num int, err error) {
	xmyFreeUrl := "http://rtd.kfzs.com/fake.php"
	xmyFreeParams := map[string]string{
		"day":     date,
		"game_id": strconv.Itoa(gameId),
	}
	requestData := new(control.XmyFreeReply)
	xmyByteData, err := utils.HttpGet(xmyFreeUrl, xmyFreeParams)
	if err != nil {
		return
	}
	_ = json.Unmarshal(xmyByteData, &requestData)
	if len(requestData.Data) != 0 {
		num, _ = strconv.Atoi(requestData.Data[0].Num)
	}
	return
}

func (s *SyncData) SyncWslGameData(date string) (mps map[string]int, err error) {
	wslUrl := "http://148.70.251.170/wsl-A/get_sheep_pay.php"
	wslParams := map[string]string{
		"times": date,
	}
	var requestData []control.WslReply
	wslByteData, err := utils.HttpGet(wslUrl, wslParams)
	if err != nil {
		return
	}
	_ = json.Unmarshal(wslByteData, &requestData)
	mps = map[string]int{}
	for _, data := range requestData {
		num, _ := strconv.Atoi(data.Money)
		mps[data.GameId] = num
	}
	return
}

var taskStatistics = "%s:taskStatistics"

func (s *SyncData) SyncRoomData(date string, gameIdInt int) (ts request.TaskStatistics, err error) {
	ctx := context.Background()
	key := fmt.Sprintf(taskStatistics, date)
	gameIdStr := strconv.Itoa(gameIdInt)
	data, err := global.GVA_REDIS.HGet(ctx, key, gameIdStr).Result()
	if err != nil {
		if err == redis.Nil {
			global.GVA_LOG.Info("SyncRoomData not data", zap.Error(err))
		} else {
			global.GVA_LOG.Error("SyncRoomData fail", zap.Error(err))
			return
		}
	}
	_ = json.Unmarshal([]byte(data), &ts)
	return
}

// 同步每天的任务基础数据
func (s *SyncData) EveryDaySyncTaskData() {
	db := global.GVA_DB.Model(&task.GameTask{})
	var apiList []task.GameTask
	db = db.Where("is_del = ?", -1)
	db = db.Where("status = ?", 1)
	err := db.Order("id desc").Find(&apiList).Error
	if err != nil {
		global.GVA_LOG.Error("EveryDaySyncTaskData fail", zap.Error(err))
		return
	}
	date := time.Now().Add(+time.Hour * 24)
	var gameTargetCompletes []*task.GameTargetComplete
	for _, gameTask := range apiList {
		gameTargetComplete := s.GameTask.CreateGameTargetCompleteModel(gameTask, date)
		gameTargetCompletes = append(gameTargetCompletes, gameTargetComplete)
	}
	err = global.GVA_DB.Model(&task.GameTargetComplete{}).Create(gameTargetCompletes).Error
	if err != nil {
		global.GVA_LOG.Error("create GameTargetComplete fail", zap.Error(err))
		return
	}
	return
}

// 定时同步机房群控、小绵羊数据
func (s *SyncData) SyncTaskData() {
	db := global.GVA_DB.Model(&task.GameTask{})
	var apiList []task.GameTask
	db = db.Where("is_del = ?", -1)
	db = db.Where("status = ?", 1)
	err := db.Order("id desc").Find(&apiList).Error
	if err != nil {
		global.GVA_LOG.Error("EveryDaySyncTaskData fail", zap.Error(err))
		return
	}
	date := time.Now().Format("2006-01-02")
	xmyGameData, err := s.SyncXmyGameData(date)
	if err != nil {
		global.GVA_LOG.Error("SyncTaskData get xmy data fail", zap.Error(err))
		return
	}
	wslData, err := s.SyncWslGameData(date)
	if err != nil {
		global.GVA_LOG.Error("SyncWslGameData get wsl data fail", zap.Error(err))
		return
	}
	for _, gameTask := range apiList {
		var gameTarget task.GameTargetComplete
		roomData, _ := s.SyncRoomData(date, gameTask.TaskId)
		if gameTask.GameIdXmy != "" {
			gameIdXmy, _ := strconv.Atoi(gameTask.GameIdXmy)
			xmyGameInfo := xmyGameData[gameIdXmy]
			gameTarget.NewComplete, _ = strconv.Atoi(xmyGameInfo.UserNum)
			gameTarget.PayComplete, _ = strconv.Atoi(xmyGameInfo.Cnt)
			gameTarget.RetainedComplete, _ = strconv.Atoi(xmyGameInfo.ActiveUserNum)
			gameTarget.Amount, _ = strconv.Atoi(xmyGameInfo.Amount)
			num, _ := s.SyncXmyFreeData(date, gameIdXmy)
			if num != 0 {
				gameTarget.PayTarget = num
			}
		} else {
			gameTarget.NewComplete = roomData.NewCompleteLocal
			gameTarget.PayComplete = roomData.PayCompleteLocal
			gameTarget.RetainedComplete = roomData.NewCompleteLocal + roomData.RetainedCompleteLocal
			gameTarget.Amount = 6
		}
		gameTarget.GameRate = roomData.GameRate
		if gameTask.GamePortId == 5 && gameTask.LoginMethod == 2 {
			mzGameId := gameTask.MzGameId + "-" + gameTask.MzChannel
			if _, ok := wslData[mzGameId]; ok {
				gameTarget.PayTarget = wslData[mzGameId]
			}
		}
		global.GVA_DB.Model(&task.GameTargetComplete{}).Where("task_id = ?", gameTask.TaskId).Where("create_date = ?", date).Omit("create_date", "update_time", "task_id").Updates(gameTarget)
	}

	return
}
