package dataStatistics

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

type ServiceWeChatScannerApi struct {
}

var robotService = new(system.RobotService)

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

	db := global.GVA_DB.Model(&dataStatistics.WeChatScannerApi{})

	//global.GVA_LOG.Info(api.NewDate)
	if api.Name != "" {
		db = db.Where("name = ?", api.Name)
	}
	if api.NewDate != "" {
		db = db.Where("new_date = ?", api.NewDate)
	}
	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.WeChatScannerApi
	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.WeChatScannerApiResponse
	for _, e := range apiList {
		oneResponse := new(response.WeChatScannerApiResponse)
		oneResponse.Id = e.Id
		oneResponse.UpdateTime = e.UpdateTime
		oneResponse.CreateTime = e.CreateTime
		oneResponse.Name = e.Name
		oneResponse.Balance = e.Balance
		oneResponse.NewDate = e.NewDate

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

// SyncGetWeChatScannerBalance 定时获取扫码平台余额
func (s *ServiceWeChatScannerApi) SyncGetWeChatScannerBalance() {
	const (
		ZWNBSP = '\uFEFF'
		empty  = ""
	)
	newDate := time.Now().Format("2006-01-02")
	content := ">#### **【扫码平台】预警** (" + time.Now().Format("2006-01-02 15:04:05") + ")：\n"
	var keyWord string
	//浪潮===============================================================
	//lc, err := s.GetLangchaoInfo()
	//if err != nil {
	//	global.GVA_LOG.Error("获取浪潮扫码余额失败，平台可能异常，请注意排查！！！")
	//	//keyWord = "获取浪潮扫码余额失败，平台可能异常，请注意排查！！！,错误信息：" + err.Error() + "\n"
	//}
	//dataLc, _ := simplejson.NewJson(lc)
	//code, _ := dataLc.Get("code").Int()
	//balanceLc := "0"
	//if code == 20000 {
	//	balanceLc, _ = dataLc.Get("data").Get("balance").String()
	//}
	////global.GVA_LOG.Info("浪潮扫码平台余额:" + balanceLc)
	//one := new(dataStatistics.WeChatScannerApi)
	//one.Name = "浪潮"
	//one.UpdateTime = time.Now().Format("2006-01-02 15:04:05")
	//one.CreateTime = time.Now().Format("2006-01-02 15:04:05")
	//one.Balance = balanceLc
	//one.NewDate = newDate
	//_ = global.GVA_DB.Create(&one).Error

	//==========================================================================
	//海马==========================================================================
	hm, err := s.GetHaimaInfo()
	if err != nil {
		global.GVA_LOG.Error("获取海马扫码余额失败，平台可能异常，请注意排查！！！")
		keyWord = "获取海马扫码余额失败，平台可能异常，请注意排查！！！,错误信息：" + err.Error() + "\n"
		content += keyWord
		url := global.GVA_CONFIG.SendUrl.KeyWordSendUrl
		_, _ = robotService.PostRobotToEnterpriseWeChatByMarkdown(url, content)
		return
	}
	//global.GVA_LOG.Info("1:" + string(hm))
	//hm2 := strings.Trim(string(hm), "")
	hm2 := strings.Replace(string(hm), string(ZWNBSP), empty, -1)
	hm = []byte(hm2)
	dataHm, err := simplejson.NewJson(hm)
	if err != nil {
		global.GVA_LOG.Error("NewJson，请注意排查！！！")
		return
	}
	code, err := dataHm.Get("code").Int()
	if err != nil {
		global.GVA_LOG.Error("Int，请注意排查！！！")
		return
	}
	balanceHm := "0"
	if code == 1 {
		balanceHm, _ = dataHm.Get("data").String()
	}
	//global.GVA_LOG.Info("海马扫码平台余额:" + balanceHm)
	one := new(dataStatistics.WeChatScannerApi)
	one.Name = "海马"
	one.Balance = balanceHm
	one.NewDate = newDate
	one.UpdateTime = time.Now().Format("2006-01-02 15:04:05")
	one.CreateTime = time.Now().Format("2006-01-02 15:04:05")
	_ = global.GVA_DB.Create(&one).Error
	//余额不足报警
	//==============================================================================
	//floatBalanceLc, _ := strconv.ParseFloat(balanceLc, 64)
	floatBalanceHm, _ := strconv.ParseFloat(balanceHm, 64)
	//浪潮余额少于10元报警
	//if floatBalanceLc <= 10 {
	//	keyWord += "浪潮扫码平台余额不足，当前余额：" + balanceLc + "元,请及时充值！！！\n"
	//}
	//海马余额少于100元报警
	if floatBalanceHm <= 100 {
		keyWord += "海马扫码平台余额不足，当前余额：" + balanceHm + "元,请及时充值！！！\n"
		keyWord += "[海马网页充值](http://www.yundiani.com/h5/) [海马卡密购买](https://www.fakazhu.cn/links/B7EC925C)"
	}
	if keyWord != "" {
		content += keyWord
		url := global.GVA_CONFIG.SendUrl.KeyWordSendUrl
		_, _ = robotService.PostRobotToEnterpriseWeChatByMarkdown(url, content)
	}
	return
}

// GetLangchaoInfo  获取浪潮
func (s *ServiceWeChatScannerApi) GetLangchaoInfo() (result []byte, err error) {
	jfUrl := "http://202.189.7.240:8082/api/userInfo"
	jfParams := map[string]string{
		"username": "513022",
		"password": "kfzsygdl",
	}
	result, err = utils.HttpGet(jfUrl, jfParams)
	return
}

// GetHaimaInfo 获取海马
func (s *ServiceWeChatScannerApi) GetHaimaInfo() (result []byte, err error) {
	jfUrl := "https://api.yundiani.com/api/openav/checkUserBalance"
	jfParams := map[string]string{
		"uname":    "513022",
		"password": "b52fca684535d924fb0147b9afbff681",
	}
	result, err = utils.HttpGet(jfUrl, jfParams)
	return
}
