package dataStatistics

import (
	"context"
	"errors"
	"github.com/bitly/go-simplejson"
	_ "github.com/bitly/go-simplejson"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"log-server/global"
	"log-server/model/dataStatistics"
	"log-server/model/dataStatistics/request"
	"log-server/model/dataStatistics/response"
	"log-server/utils"
	"strconv"
	"strings"
	"time"
)

type ServiceWeChatScannerDetailed struct {
}

type WeChatGameInfo struct {
	GameName        string
	LcPriceNew      float64
	LcPriceRetained float64
	HmPriceNew      float64
	HmPriceRetained float64
}

type PlatformNum struct {
	Platform string `json:"platform"`
	Count    int    `json:"count"`
}

func (s *ServiceWeChatScannerDetailed) WeChatScannerDetailedList(ctx context.Context, api dataStatistics.WeChatScannerDetailed, info request.PageInfo, order string, desc bool) (interface{}, int64, error) {

	db := global.GVA_DB.Model(&dataStatistics.WeChatScannerDetailed{})
	//global.GVA_LOG.Info(api.NewDate)
	if api.Platform != "" {
		db = db.Where("platform = ?", api.Platform)
	}
	if api.NewDate != "" {
		db = db.Where("new_date = ?", api.NewDate)
	}
	if api.TaskId != 0 {
		db = db.Where("task_id = ?", api.TaskId)
	}
	if api.NewRetained != 0 {
		if api.NewRetained == 1 {
			db = db.Where("new_retained = ?", api.NewRetained)
		} else {
			db = db.Where("new_retained >= ?", api.NewRetained)
		}
	}
	var total int64
	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 apiList []dataStatistics.WeChatScannerDetailed
	db = db.Limit(limit).Offset(offset)
	if order != "" {
		var OrderStr string
		// 设置有效排序key 防止sql注入
		// 感谢 Tom4t0 提交漏洞信息
		orderMap := make(map[string]bool, 3)
		orderMap["id"] = true
		//orderMap["game_id"] = true
		//orderMap["operator"] = true
		if orderMap[order] {
			if desc {
				OrderStr = order + " desc"
			} else {
				OrderStr = order + " desc"
			}
		} else { // didn't matched any order key in `orderMap`
			global.GVA_LOG.Error("获取失败!", zap.Error(err))
			return apiList, total, err
		}
		err = db.Order(OrderStr).Find(&apiList).Error
	} else {
		err = db.Order("id").Find(&apiList).Error
	}
	if err != nil {
		return nil, 0, err
	}
	var arrayResponse []*response.WeChatScannerDetailedResponse
	for _, e := range apiList {
		oneResponse := new(response.WeChatScannerDetailedResponse)
		oneResponse.Id = e.Id
		oneResponse.NewDate = e.NewDate
		oneResponse.OrderId = e.OrderId
		oneResponse.Platform = e.Platform
		oneResponse.AuthorizationTime = e.AuthorizationTime
		oneResponse.TaskId = e.TaskId
		oneResponse.TaskName = e.TaskName
		oneResponse.NewRetained = e.NewRetained

		arrayResponse = append(arrayResponse, oneResponse)
	}
	return arrayResponse, total, err
}

// SyncTodayWeChatScannerDetailed 同步今日
func (s *ServiceWeChatScannerDetailed) SyncTodayWeChatScannerDetailed() {
	today := time.Now().Format("2006-01-02")
	s.SyncWeChatScannerDetailed(today)
}

// SyncYesterdayWeChatScannerDetailed 0点同步昨日数据，确保数据完整性
func (s *ServiceWeChatScannerDetailed) SyncYesterdayWeChatScannerDetailed() {
	today := time.Now()
	yesterday := today.AddDate(0, 0, -1).Format("2006-01-02")
	s.SyncWeChatScannerDetailed(yesterday)
}

// SyncWeChatScannerDetailed 定时批量同步微信扫码订单号明细,先将微信扫码的游戏写死
func (s *ServiceWeChatScannerDetailed) SyncWeChatScannerDetailed(today string) {

	tencentTasks := map[int]WeChatGameInfo{
		10101:    {GameName: "坦克前线", LcPriceNew: 0.35, LcPriceRetained: 0.01, HmPriceNew: 0.4, HmPriceRetained: 0.01},
		10360903: {GameName: "原始传奇-10360903", LcPriceNew: 0.35, LcPriceRetained: 0.01, HmPriceNew: 0.4, HmPriceRetained: 0.01},
		10361913: {GameName: "原始传奇-10361913", LcPriceNew: 0.35, LcPriceRetained: 0.01, HmPriceNew: 0.4, HmPriceRetained: 0.01},
		10363822: {GameName: "原始传奇-10363822", LcPriceNew: 0.35, LcPriceRetained: 0.01, HmPriceNew: 0.4, HmPriceRetained: 0.01},
		6543:     {GameName: "创造与魔法10361913", LcPriceNew: 0.4, LcPriceRetained: 0.01, HmPriceNew: 0.4, HmPriceRetained: 0.01},
		8767:     {GameName: "奶块10361913", LcPriceNew: 0.35, LcPriceRetained: 0.01, HmPriceNew: 0.4, HmPriceRetained: 0.01},
		888811:   {GameName: "热血合击tx-10360903 ", LcPriceNew: 0.35, LcPriceRetained: 0.01, HmPriceNew: 0.4, HmPriceRetained: 0.01},
	}
	for k, v := range tencentTasks {
		result, err := s.getJfWechatOrder(k, today)
		if err != nil {
			return
		}
		dataJson, err := simplejson.NewJson(result)
		if err != nil {
			return
		}
		dataArr, err := dataJson.Array()
		if err != nil {
			return
		}
		for index, _ := range dataArr {
			info := dataJson.GetIndex(index)
			//GameId, _ := info.Get("GameId").Int()
			WeChatOrder, err := info.Get("WeChatOrder").String()
			Retained, err := info.Get("Retained").Int()
			Time, err := info.Get("Time").String()
			if err != nil {
				return
			}

			orderArr := strings.Split(WeChatOrder, "|")
			orderId := ""
			platform := ""
			if len(orderArr) == 2 {
				orderId = orderArr[0]
				platform = orderArr[1]
			}

			var data dataStatistics.WeChatScannerDetailed
			data.NewDate = today
			data.TaskId = k
			data.Platform = platform
			data.OrderId = orderId
			data.NewRetained = Retained
			data.AuthorizationTime = Time
			data.TaskName = v.GameName
			if errors.Is(global.GVA_DB.Model(&dataStatistics.WeChatScannerDetailed{}).Where("new_date = ? and task_id = ? and order_id = ?", today, k, orderId).First(&dataStatistics.WeChatScannerDetailed{}).Error, gorm.ErrRecordNotFound) {
				_ = global.GVA_DB.Create(&data).Error
			}
		}
		//计算微信扫码消耗
		//SELECT platform, COUNT(*) FROM wechat_scanner_detailed WHERE new_date = '2023-02-07' AND  task_id = 888811 AND new_retained =  1 GROUP BY platform
		arrPlatform := []string{"海马", "浪潮"}
		for _, platform := range arrPlatform {
			var db1Ledger dataStatistics.WeChatScannerLedger
			db1Ledger.TaskId = k
			db1Ledger.TaskName = v.GameName
			db1Ledger.NewDate = today
			db1Ledger.Platform = platform
			var listNum []PlatformNum
			PriceNew := 0.00
			PriceRetained := 0.00
			UnitPriceNew := 0.00
			UnitPriceRetained := 0.00
			err = global.GVA_DB.Model(&dataStatistics.WeChatScannerDetailed{}).Select("platform", "COUNT(*) AS count").Where("new_date = ? and task_id = ? and platform = ? and new_retained = 1", today, k, platform).First(&listNum).Error
			if err != nil {
				return
			}
			for _, e := range listNum {
				if e.Platform == "海马" {
					PriceNew = v.HmPriceNew * float64(e.Count)
					UnitPriceNew = v.HmPriceNew
				} else if e.Platform == "浪潮" {
					//global.GVA_LOG.Info(strconv.Itoa(e.Count))
					PriceNew = v.LcPriceNew * float64(e.Count)
					UnitPriceNew = v.LcPriceNew
					//global.GVA_LOG.Info(strconv.FormatFloat(PriceNew, 'f', 2, 64))
				}
			}
			var listNum2 []PlatformNum
			err = global.GVA_DB.Model(&dataStatistics.WeChatScannerDetailed{}).Select("platform", "COUNT(*) AS count").Where("new_date = ? and task_id = ? and platform = ? and new_retained >= 2", today, k, platform).First(&listNum2).Error
			if err != nil {
				return
			}
			for _, e := range listNum2 {
				if e.Platform == "海马" {
					PriceRetained = v.HmPriceRetained * float64(e.Count)
					UnitPriceRetained = v.HmPriceRetained
				} else if e.Platform == "浪潮" {
					PriceRetained = v.LcPriceRetained * float64(e.Count)
					UnitPriceRetained = v.LcPriceRetained
				}
			}
			db1Ledger.LedgerNew = strconv.FormatFloat(PriceNew, 'f', 2, 64)
			db1Ledger.LedgerRetained = strconv.FormatFloat(PriceRetained, 'f', 2, 64)
			db1Ledger.Ledger = strconv.FormatFloat(PriceNew+PriceRetained, 'f', 2, 64)
			db1Ledger.UnitPriceNew = strconv.FormatFloat(UnitPriceNew, 'f', 2, 64)
			db1Ledger.UnitPriceRetained = strconv.FormatFloat(UnitPriceRetained, 'f', 2, 64)
			//global.GVA_LOG.Info(strconv.Itoa(db1Ledger.TaskId))
			//global.GVA_LOG.Info(db1Ledger.TaskName)
			//global.GVA_LOG.Info(db1Ledger.LedgerNew)
			//global.GVA_LOG.Info(db1Ledger.LedgerRetained)
			//global.GVA_LOG.Info(db1Ledger.Ledger)
			if !errors.Is(global.GVA_DB.Model(&dataStatistics.WeChatScannerLedger{}).Where("new_date = ? and task_id = ? and platform = ?", today, k, platform).First(&dataStatistics.WeChatScannerLedger{}).Error, gorm.ErrRecordNotFound) {
				_ = global.GVA_DB.Model(&dataStatistics.WeChatScannerLedger{}).Where("new_date = ? and task_id = ? and platform = ?", today, k, platform).Updates(db1Ledger).Error
			} else {
				_ = global.GVA_DB.Create(&db1Ledger).Error
			}

		}

	}
}

// SyncGetWeChatScannerBalance 定时获取扫码平台余额
//
// getJfWechatOrder 获取机房后台微信订单列表信息
func (s *ServiceWeChatScannerDetailed) getJfWechatOrder(gameId int, date string) (result []byte, err error) {
	jfUrl := "http://xjf.lianyou.fun:8099/v1/account/get_wechat_order"
	jfParams := map[string]string{
		"game_id": strconv.Itoa(gameId),
		"date":    date,
	}
	result, err = utils.HttpGet(jfUrl, jfParams)
	return
}
