package task

import (
	"encoding/json"
	"errors"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"log-server/global"
	"log-server/model/task"
	"log-server/model/task/control"
	"log-server/model/task/request"
	"log-server/model/task/response"
	"log-server/utils"
	"math"
	"math/rand"
	"strconv"
	"time"
)

var AccountType = map[int]string{
	1: "小绵羊账号",
	2: "QQ账号",
	3: "魅族账号",
	4: "华为账号",
	5: "测试类型",
	6: "微信",
	7: "微信+QQ",
}

var LoginMethod = map[int]string{
	1: "小绵羊登录",
	2: "魅族账号登录",
	3: "QQ账号登录",
	4: "网易账号登录",
	5: "微信授权登录",
	6: "微信+QQ授权登录",
}
var GamePort = map[int]string{
	1: "腾讯游戏",
	2: "360游戏",
	3: "网易游戏",
	4: "酷派游戏",
	5: "魅族游戏",
}

var (
	CreateTaskUrl           = "/v1/task_statistics"
	GetControlTaskIdUrl     = "/v1/task_statistics/get_data_id"
	UpdateGameTaskStatusUrl = "/v1/install_info/updateinstallstatus"
)

type GameTask struct {
}

// 创建游戏任务
func (s *GameTask) CreateGameTask(requestData request.GameTaskRequest) (err error) {
	if !errors.Is(global.GVA_DB.Where("task_id = ?", requestData.TaskId).First(&task.GameTask{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在相同任务ID")
	}
	gameTask := new(task.GameTask)
	gameTask.TaskId = requestData.TaskId
	gameTask.TaskName = requestData.TaskName
	gameTask.User = requestData.User
	gameTask.NewRetained = requestData.NewRetained
	gameTask.GameName = requestData.GameName
	gameTask.GameId = requestData.GameId
	gameTask.Date = time.Now()
	gameTask.GamePortId = requestData.GamePortId
	gameTask.AccountType = requestData.AccountType
	gameTask.LoginMethod = requestData.LoginMethod
	gameTask.TxChannel = requestData.TxChannel
	gameTask.TxGameId = requestData.TxGameId
	gameTask.MzChannel = requestData.MzChannel
	gameTask.MzGameId = requestData.MzGameId
	gameTask.GameIdXmy = requestData.GameIdXmy
	gameTask.NewTarget = requestData.NewTarget
	gameTask.PayTarget = requestData.PayTarget
	gameTask.RetainedTarget = requestData.RetainedTarget
	gameTask.PayPrice = requestData.PayPrice
	//gameTask.CreateTime		= requestData.CreateTime
	//gameTask.UpdateTime		= requestData.UpdateTime
	//gameTask.Status			= requestData.Status
	//gameTask.IsDel			= requestData.IsDel
	//gameTask.DeleteTime		= requestData.DeleteTime
	taskRequestData := s.CreateGameTaskRequestData(requestData)
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		err = tx.Omit("create_time", "update_time", "status", "is_del", "delete_time", "control_task_id").Create(&gameTask).Error
		if err != nil {
			global.GVA_LOG.Error("添加任务数据失败: ", zap.Error(err))
			return err
		}
		_, err := s.CreateTaskRequestControl(taskRequestData)
		if err != nil {
			global.GVA_LOG.Error("添加任务数据请求群控失败: ", zap.Error(err))
		}
		return err
	})
	if err != nil {
		return err
	}
	// 同步群控任务id
	d, err := s.GetControlTaskId(taskRequestData.GameId)
	if err != nil {
		global.GVA_LOG.Error("获取群控的任务id失败")
		return err
	}
	err = global.GVA_DB.Model(&task.GameTask{}).Where("task_id = ?", taskRequestData.GameId).Update("control_task_id", d.IdDong).Error
	return
}

// 创建游戏任务完成model
func (s *GameTask) CreateGameTargetCompleteModel(oldA task.GameTask, date time.Time) *task.GameTargetComplete {
	var newTarget int
	rand.Seed(time.Now().UnixNano())
	newTargetRate := rand.Float64()
	if oldA.NewTarget <= 10 {
		newTarget = 10
	} else {
		newTarget = int(math.Ceil(float64(oldA.NewTarget) * 0.5))
	}
	var retainedTarget int
	rand.Seed(time.Now().UnixNano())
	retainedTargetRate := rand.Float64()
	if oldA.NewTarget < 100 {
		newTarget = oldA.NewTarget
	} else {
		newTarget = 200
	}
	targetComplete := new(task.GameTargetComplete)
	targetComplete.TaskId = oldA.TaskId
	targetComplete.NewTarget = oldA.NewTarget + int(math.Ceil(newTargetRate*float64(newTarget)))
	targetComplete.RetainedTarget = oldA.RetainedTarget + int(math.Ceil(retainedTargetRate*float64(retainedTarget)))
	targetComplete.PayTarget = 0
	targetComplete.CreateDate = date
	targetComplete.RetainedComplete = 0
	targetComplete.PayComplete = 0
	targetComplete.NewComplete = 0
	return targetComplete
}

// 创建任务群控请求数据
func (s *GameTask) CreateGameTaskRequestData(requestData request.GameTaskRequest) control.CreateGameTaskRequest {
	gameTask := control.CreateGameTaskRequest{}
	gameTask.GameId = requestData.TaskId
	gameTask.GameName = requestData.TaskName
	gameTask.Remark = requestData.User
	gameTask.NewRetained = requestData.NewRetained
	gameTask.Date = time.Now().Format("2006-01-02")
	gameTask.GamePort = GamePort[requestData.GamePortId]
	gameTask.GameIdXmy = requestData.GameIdXmy
	gameTask.NewTarget = requestData.NewTarget
	gameTask.PayTarget = requestData.PayTarget
	gameTask.RetainedTarget = requestData.RetainedTarget
	gameTask.PayPrice = requestData.PayPrice
	gameTask.SyDataId = requestData.TaskId
	gameTask.SpiritPackageName = "0"
	gameTask.GamePackageName = "0"
	return gameTask
}

// http请求群控创建任务
func (s *GameTask) CreateTaskRequestControl(requestData control.CreateGameTaskRequest) (d string, err error) {
	url := global.GVA_CONFIG.ExtranetDomain.Control + CreateTaskUrl
	data, code, err := utils.HttpPostReplyCode(url, requestData)
	fmt.Println(code)
	if code != 200 {
		return string(data), errors.New(string(data))
	}
	d = string(data)
	return
}

// http请求群控更新任务
func (s *GameTask) UpdateTaskRequestControl(requestData control.CreateGameTaskRequest, controlTaskId int) (d string, err error) {
	url := global.GVA_CONFIG.ExtranetDomain.Control + CreateTaskUrl + "/" + strconv.Itoa(controlTaskId)
	data, code, err := utils.HttpPutReplyCode(url, requestData)
	fmt.Println(code)
	if code != 200 {
		return string(data), errors.New(string(data))
	}
	d = string(data)
	return
}

type ControlTaskId struct {
	IdDong int
	IdYang int
}

// http请求获取群控创建任务id
func (s *GameTask) GetControlTaskId(gameId int) (d *ControlTaskId, err error) {
	url := global.GVA_CONFIG.ExtranetDomain.Control + GetControlTaskIdUrl
	requestData := map[string]string{
		"game_id": strconv.Itoa(gameId),
	}
	data, code, err := utils.HttpGetReplyCode(url, requestData)
	fmt.Println(code)
	if code != 200 {
		return d, errors.New(string(data))
	}
	msg := new(ControlTaskId)
	_ = json.Unmarshal(data, &msg)
	d = msg
	return
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetGameTaskInfoList
//@description: 分页获取数据,
//@param: card card.Card, info request.PageInfo, order string, desc bool
//@return: list interface{}, total int64, err error
func (apiService *GameTask) GetGameTaskInfoList(api task.GameTask, info request.PageInfo, order string, desc bool) (list interface{}, options interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.GVA_DB.Model(&task.GameTask{})
	var apiList []task.GameTask
	db = db.Where("is_del = ?", -1)
	if api.TaskName != "" {
		db = db.Where("task_name LIKE ?", "%"+api.TaskName+"%")
	}

	if api.User != "" {
		db = db.Where("user LIKE ?", "%"+api.User+"%")
	}

	if api.Status != 0 {
		db = db.Where("status = ?", api.Status)
	}

	err = db.Count(&total).Error



	//查找厂商名称，登录类型名称、账号类型名称
	option := task.Option{}
	global.GVA_DB.Table("game_channel").Select("id","channel_name").Find(&option.GamePortOptions)
	global.GVA_DB.Table("login_type").Select("id", "login_name").Find(&option.LoginTypeOptions)
	global.GVA_DB.Table("account_type").Select("id", "type_name").Find(&option.AccountTypeOptions)
	global.GVA_DB.Table("game_list").Select("id", "game_name").Find(&option.GameListOptions)
	//fmt.Println(option)



	if err != nil {
		return apiList, option , total, err
	} else {
		db = db.Limit(limit).Offset(offset)
		if order != "" {
			var OrderStr string
			// 设置有效排序key 防止sql注入
			// 感谢 Tom4t0 提交漏洞信息
			orderMap := make(map[string]bool, 4)
			orderMap["id"] = true
			orderMap["task_name"] = true
			orderMap["user"] = true
			if orderMap[order] {
				if desc {
					OrderStr = order + " desc"
				} else {
					OrderStr = order
				}
			} else { // didn't matched any order key in `orderMap`
				err = fmt.Errorf("非法的排序字段: %v", order)
				return apiList, option, total, err
			}

			err = db.Order(OrderStr).Find(&apiList).Error
		} else {
			err = db.Order("id desc").Find(&apiList).Error
		}
	}
	var apisReply []*response.GetGameTaskListReply
	if len(apiList) != 0 {
		for _, apiInfo := range apiList {
			var apiReply = new(response.GetGameTaskListReply)
			apiReply.Status = apiInfo.Status
			apiReply.TaskId = apiInfo.TaskId
			apiReply.TaskName = apiInfo.TaskName
			apiReply.GamePort = GamePort[apiInfo.GamePortId]
			apiReply.AccountType = AccountType[apiInfo.AccountType]
			apiReply.LoginMethod = LoginMethod[apiInfo.LoginMethod]
			apiReply.CreateTime = apiInfo.CreateTime.Format("2006-01-02 15:04:05")
			apiReply.User = apiInfo.User
			apiReply.Date = apiInfo.Date.Format("2006-01-02")
			apiReply.GameName = apiInfo.GameName
			apiReply.UpdateTime = apiInfo.UpdateTime.Format("2006-01-02 15:04:05")
			apiReply.NewTarget = apiInfo.NewTarget
			apiReply.PayTarget = apiInfo.PayTarget
			apiReply.RetainedTarget = apiInfo.RetainedTarget
			apiReply.PayPrice = apiInfo.PayPrice
			apiReply.StopTime = apiInfo.StopTime.Format("2006-01-02 15:04:05")
			if apiInfo.Status == 1 {
				apiReply.StopTime = ""
			}
			apisReply = append(apisReply, apiReply)
		}

	}
	return apisReply, option,  total, err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetGameTaskById
//@description: 根据id获取GameTask
//@param: id uint
//@return: apiReply response.GetPcListReply, err error
func (c *GameTask) GetGameTaskById(id int) (gameTask request.GameTaskRequest, err error) {
	var requestData task.GameTask
	err = global.GVA_DB.Where("task_id = ?", id).First(&requestData).Error
	if err != nil {
		return
	}
	gameTask.TaskId = requestData.TaskId
	gameTask.TaskName = requestData.TaskName
	gameTask.User = requestData.User
	gameTask.NewRetained = requestData.NewRetained
	gameTask.GameName = requestData.GameName
	gameTask.GamePortId = requestData.GamePortId
	gameTask.AccountType = requestData.AccountType
	gameTask.LoginMethod = requestData.LoginMethod
	gameTask.TxChannel = requestData.TxChannel
	gameTask.TxGameId = requestData.TxGameId
	gameTask.MzChannel = requestData.MzChannel
	gameTask.MzGameId = requestData.MzGameId
	gameTask.GameIdXmy = requestData.GameIdXmy
	gameTask.NewTarget = requestData.NewTarget
	gameTask.PayTarget = requestData.PayTarget
	gameTask.RetainedTarget = requestData.RetainedTarget
	gameTask.PayPrice = requestData.PayPrice
	return
}

// http请求群控更新任务装
func (s *GameTask) UpdateControlStatus(gameId int, status int) (err error) {
	url := global.GVA_CONFIG.ExtranetDomain.Control + UpdateGameTaskStatusUrl
	requestData := map[string]string{
		"status":  strconv.Itoa(status),
		"game_id": strconv.Itoa(gameId),
	}
	data, code, err := utils.HttpGetReplyCode(url, requestData)
	if err != nil {
		return err
	}
	fmt.Println(code)
	if code != 200 {
		return errors.New(string(data))
	}
	return
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: UpdateGameTaskStatus
//@description: 根据id更新GameTask状态
//@param: GameTask request.UpdateGameTaskRequest
//@return: err error
func (s *GameTask) UpdateGameTaskStatus(c request.UpdateGameTaskStatusRequest) (err error) {
	var oldA task.GameTask
	err = global.GVA_DB.Where("task_id = ?", c.TaskId).First(&oldA).Error
	if err != nil {
		return err
	}
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		update := map[string]interface{}{
			"status": c.Status,
		}
		status := c.Status
		if c.Status == -1 {
			status = 0
			update["stop_time"] = time.Now().Format("2006-01-02 15:04:05")
		} else {
			date := time.Now()
			if !errors.Is(tx.Where("task_id = ?", c.TaskId).Where("create_date = ?", date.Format("2006-01-02")).First(&task.GameTargetComplete{}).Error, gorm.ErrRecordNotFound) {
				global.GVA_LOG.Info("当天的任务目标已存在")
			} else {
				targetComplete := s.CreateGameTargetCompleteModel(oldA, date)
				err := tx.Omit("update_time").Create(&targetComplete).Error
				if err != nil {
					global.GVA_LOG.Error("创建任务目标数据失败", zap.Error(err))
					return err
				}
			}
		}
		err := tx.Table("game_task").Where("task_id", c.TaskId).Updates(update).Error
		if err != nil {
			return err
		}
		err = s.UpdateControlStatus(c.TaskId, status)
		return err
	})

	return err
}

// 更新GameTask
func (s *GameTask) UpdateGameTask(requestData request.GameTaskRequest) (err error) {
	if errors.Is(global.GVA_DB.Where("task_id = ?", requestData.TaskId).First(&task.GameTask{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("不存在的任务")
	}
	gameTask := new(task.GameTask)
	global.GVA_DB.Where("task_id = ?", requestData.TaskId).First(&gameTask)
	gameTask.TaskId = requestData.TaskId
	gameTask.TaskName = requestData.TaskName
	gameTask.User = requestData.User
	gameTask.NewRetained = requestData.NewRetained
	gameTask.GameName = requestData.GameName
	gameTask.GameId = requestData.GameId
	gameTask.GamePortId = requestData.GamePortId
	gameTask.AccountType = requestData.AccountType
	gameTask.LoginMethod = requestData.LoginMethod
	gameTask.TxChannel = requestData.TxChannel
	gameTask.TxGameId = requestData.TxGameId
	gameTask.MzChannel = requestData.MzChannel
	gameTask.MzGameId = requestData.MzGameId
	gameTask.GameIdXmy = requestData.GameIdXmy
	gameTask.NewTarget = requestData.NewTarget
	gameTask.PayTarget = requestData.PayTarget
	gameTask.RetainedTarget = requestData.RetainedTarget
	gameTask.PayPrice = requestData.PayPrice
	taskRequestData := s.CreateGameTaskRequestData(requestData)
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		err = tx.Where("task_id = ?", requestData.TaskId).Omit("create_time", "update_time", "status", "is_del", "delete_time", "control_task_id", "date", "task_id").Updates(&gameTask).Error
		if err != nil {
			global.GVA_LOG.Error("更新任务数据失败: ", zap.Error(err))
			return err
		}
		_, err := s.UpdateTaskRequestControl(taskRequestData, gameTask.ControlTaskId)
		if err != nil {
			global.GVA_LOG.Error("更新任务数据请求群控失败: ", zap.Error(err))
		}
		return err
	})
	return
}

// http请求群控刪除任务
func (s *GameTask) DelTaskRequestControl(controlTaskId int) (d string, err error) {
	url := global.GVA_CONFIG.ExtranetDomain.Control + CreateTaskUrl + "/" + strconv.Itoa(controlTaskId)
	data, code, err := utils.HttpDeleteReplyCode(url, nil)
	fmt.Println(code)
	if code != 200 {
		return string(data), errors.New(string(data))
	}
	d = string(data)
	return
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteGameTask
//@description: 删除GameTask
//@param: api task.GameTask
//@return: err error
func (s *GameTask) DeleteGameTask(api request.GameTaskRequest) (err error) {
	var entity task.GameTask
	err = global.GVA_DB.Where("task_id = ?", api.TaskId).First(&entity).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return err
	}
	gameTask := new(task.GameTask)
	global.GVA_DB.Where("task_id = ?", api.TaskId).First(&gameTask)
	controlTaskId := gameTask.ControlTaskId
	update := map[string]interface{}{
		"is_del":      1,
		"status":      -1,
		"stop_time":   time.Now(),
		"delete_time": time.Now(),
	}
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		err := tx.Table("game_task").Where("task_id", api.TaskId).Updates(update).Error
		if err != nil {
			return err
		}
		_, err = s.DelTaskRequestControl(controlTaskId)
		return err
	})
	return
}
