package task

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/xuri/excelize/v2"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"io/ioutil"
	"log-server/global"
	"log-server/model/task"
	"log-server/model/task/control"
	"log-server/model/task/request"
	"log-server/model/task/response"
	"log-server/model/typeManage"
	"log-server/service/cache"
	"log-server/utils"
	"math"
	"math/rand"
	"net/http"
	"strconv"
	"strings"
	"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 {
	cache       cache.Cache
	common      Common
	gameChannel typeManage.GameChannel
	loginType   typeManage.LoginType
}

// 创建游戏任务
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.NewTargetH = requestData.NewTargetH
	gameTask.RetainedTargetH = requestData.RetainedTargetH
	//gameTask.CreateTime		= requestData.CreateTime
	//gameTask.UpdateTime		= requestData.UpdateTime
	//gameTask.Status			= requestData.Status
	//gameTask.IsDel			= requestData.IsDel
	//gameTask.DeleteTime		= requestData.DeleteTime
	taskRequestData := s.CreateGameTaskRequestData(requestData)
	body, _ := json.Marshal(taskRequestData)
	global.GVA_LOG.Info(string(body))
	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))
	}*/
	newTarget = int(math.Ceil(float64(oldA.NewTargetH-oldA.NewTarget) * newTargetRate))
	var retainedTarget int
	rand.Seed(time.Now().UnixNano())
	retainedTargetRate := rand.Float64()
	//if oldA.RetainedTarget < 100 {
	//	retainedTarget = oldA.RetainedTarget
	//} else if oldA.RetainedTarget > 1000 {
	//	retainedTarget = 1000
	//} else {
	//	retainedTarget = 200
	//}
	retainedTarget = int(math.Ceil(float64(oldA.RetainedTargetH-oldA.RetainedTarget) * retainedTargetRate))
	targetComplete := new(task.GameTargetComplete)
	targetComplete.TaskId = oldA.TaskId
	targetComplete.NewTarget = oldA.NewTarget + newTarget
	if oldA.NewTarget == 0 || oldA.NewTargetH == 0 {
		targetComplete.NewTarget = 0
	}
	targetComplete.RetainedTarget = oldA.RetainedTarget + retainedTarget
	if oldA.RetainedTarget == 1 || oldA.RetainedTargetH == 1 {
		targetComplete.RetainedTarget = 1
	}
	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{}
	gchannel, _ := s.gameChannel.GetGameChannelById(requestData.GamePortId)
	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 = gchannel.ChannelName
	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)
	}

	if api.TaskId != 0 {
		db = db.Where("task_id = ?", api.TaskId)
	}

	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)
	accountMp, gamePortMp, loginTypeMp := apiService.TypeManageToMps(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 = gamePortMp[apiInfo.GamePortId].ChannelName
			apiReply.AccountType = accountMp[apiInfo.AccountType].TypeName
			apiReply.LoginMethod = loginTypeMp[apiInfo.LoginMethod].LoginName
			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.RetainedTargetH = apiInfo.RetainedTargetH
			apiReply.NewTargetH = apiInfo.NewTargetH
			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
}

func (apiService *GameTask) TypeManageToMps(Option task.Option) (map[int]task.AccountTypeOption, map[int]task.GamePortOption, map[int]task.LoginTypeOption) {
	var accountMp = make(map[int]task.AccountTypeOption, len(Option.AccountTypeOptions))
	for _, pc := range Option.AccountTypeOptions {
		accountMp[pc.Id] = pc
	}
	var gamePortMp = make(map[int]task.GamePortOption, len(Option.GamePortOptions))
	for _, gamePort := range Option.GamePortOptions {
		gamePortMp[gamePort.Id] = gamePort
	}
	var loginTypeMp = make(map[int]task.LoginTypeOption, len(Option.LoginTypeOptions))
	for _, loginType := range Option.LoginTypeOptions {
		loginTypeMp[loginType.Id] = loginType
	}
	return accountMp, gamePortMp, loginTypeMp
}

//获取启用状态的任务
func (apiService *GameTask) GetUsedGameTaskInfoList(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.GameTaskUnion
	db = db.Select("game_task.*, task_conf.add_fee_notice, task_conf.simulator_type")
	db = db.Joins("left join task_conf on task_conf.task_id = game_task.task_id")
	db = db.Where("is_del = ?", -1)
	if api.TaskName != "" {
		db = db.Where("task_name LIKE ?", "%"+api.TaskName+"%")
	}

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

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

	if api.TaskId != 0 {
		db = db.Where("game_task.task_id = ?", api.TaskId)
	}

	//获取启用状态的任务
	db = db.Where("status = 1")
	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)
	accountMp, gamePortMp, loginTypeMp := apiService.TypeManageToMps(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.GetGameTaskListUnionReply
	if len(apiList) != 0 {
		for _, apiInfo := range apiList {
			var apiReply = new(response.GetGameTaskListUnionReply)
			apiReply.Status = apiInfo.Status
			apiReply.TaskId = apiInfo.TaskId
			apiReply.SimulatorType = apiInfo.SimulatorType
			apiReply.TaskName = apiInfo.TaskName
			apiReply.AddFeeNotice = apiInfo.AddFeeNotice
			apiReply.GamePort = gamePortMp[apiInfo.GamePortId].ChannelName
			apiReply.AccountType = accountMp[apiInfo.AccountType].TypeName
			apiReply.LoginMethod = loginTypeMp[apiInfo.LoginMethod].LoginName
			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.RetainedTargetH = apiInfo.RetainedTargetH
			apiReply.NewTargetH = apiInfo.NewTargetH
			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
	gameTask.RetainedTargetH = requestData.RetainedTargetH
	gameTask.NewTargetH = requestData.NewTargetH
	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")
			date := time.Now().Add(+time.Hour * 24)
			tx.Where("task_id = ?", c.TaskId).Where("create_date = ?", date.Format("2006-01-02")).Delete(&task.GameTargetComplete{})
		} 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,is_complete,hand_new_complete,hand_retained_complete,hand_pay_complete,hand_amount_total").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("不存在的任务")
	}
	d, err := s.GetControlTaskId(requestData.TaskId)
	if err != nil {
		global.GVA_LOG.Error("请求群控数据报错: ", zap.Error(err))
		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
	gameTask.NewTargetH = requestData.NewTargetH
	gameTask.RetainedTargetH = requestData.RetainedTargetH
	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").Save(&gameTask).Error
		if err != nil {
			global.GVA_LOG.Error("更新任务数据失败: ", zap.Error(err))
			return err
		}
		_, err := s.UpdateTaskRequestControl(taskRequestData, d.IdDong)
		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
	}
	//update := map[string]interface{}{
	//	"is_del":      1,
	//	"status":      -1,
	//	"stop_time":   time.Now(),
	//	"delete_time": time.Now(),
	//}
	d, err := s.GetControlTaskId(api.TaskId)
	if err != nil {
		global.GVA_LOG.Error("请求群控数据报错: ", zap.Error(err))
		return errors.New("请求群控数据报错")
	}
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		err := tx.Where("task_id", api.TaskId).Delete(&task.GameTask{}).Error
		if err != nil {
			return err
		}
		_, err = s.DelTaskRequestControl(d.IdDong)
		return err
	})
	return
}

//@function: GetGameTaskTargetInfoList
//@description: 分页获取数据,
//@param: card card.Card, info request.PageInfo, order string, desc bool
//@return: list interface{}, total int64, err error
func (apiService *GameTask) GetGameTaskTargetInfoList(api request.GameTargetCompleteRequest, info request.PageInfo, order string, desc bool, isTx bool) (apiList []response.GetGameTargetComplete, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	startDate := time.Now().Format("2006-01-02")
	endDate := time.Now().Format("2006-01-02")
	if len(api.Date) == 2 {
		startDate = api.Date[0]
		endDate = api.Date[1]
	}
	db := global.GVA_DB.Table("game_target_complete gtc")
	db = db.Select("gtc.id,gtc.task_id,gt.task_name,gt.game_id_xmy,gtc.new_target,gt.login_method,gt.user,gtc.pay_target,gtc.retained_target," +
		"gtc.new_complete,gtc.pay_complete,gtc.retained_complete,gtc.create_date,gtc.amount,gtc.game_rate,gtc.is_complete,gtc.hand_new_complete," +
		"gtc.hand_retained_complete,gtc.hand_pay_complete,gtc.hand_amount_total,gtc.aupr, gtc.total_amount")
	db = db.Joins("left join game_task gt on gt.task_id = gtc.task_id")
	//db = db.Where("gtc.create_date = ?", api.CreateDate)
	db = db.Where("create_date >= ? and create_date <= ?", startDate, endDate)

	if api.TaskName != "" {
		db = db.Where("gt.task_name LIKE ?", "%"+api.TaskName+"%")
	}
	if api.User != "" {
		db = db.Where("gt.user LIKE ?", "%"+api.User+"%")
	}
	if isTx {
		db = db.Where("gt.game_port_id = ?", 1)
	}
	if api.GamePortId != 0 {
		db = db.Where("gt.game_port_id = ?", api.GamePortId)
	}
	if api.TaskId != 0 {
		db = db.Where("gtc.task_id = ?", api.TaskId)
	}
	if api.IsComplete != 0 {
		db = db.Where("gtc.is_complete = ?", api.IsComplete)
	}
	err = db.Count(&total).Error

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

			err = db.Order(OrderStr).Find(&apiList).Error
		} else {
			err = db.Order("gtc.id desc").Find(&apiList).Error
		}
	}
	if len(apiList) != 0 {
		loginType, _ := apiService.loginType.GetLoginTypeData()
		for i, api := range apiList {
			date := strings.Split(api.CreateDate, "T")
			loginMethod, _ := strconv.Atoi(api.LoginMethod)
			apiList[i].LoginMethod = loginType[int64(loginMethod)].LoginName
			apiList[i].CreateDate = date[0]
			apiList[i].NewComplete = api.NewComplete + api.HandNewComplete
			apiList[i].RetainedComplete = api.RetainedComplete + api.HandRetainedComplete
		}
	}
	return apiList, total, err
}

func (s *GameTask) FreeUploadWt(gameId, channelId string, date string, money int, path string) (err error) {
	url := "https://sy.nkfzs.com/v2/data_collect/" + path
	requestData := map[string]string{
		"channel_id": channelId,
		"game_id":    gameId,
		"type":       "3",
		"account":    "hand_" + date,
		"money":      strconv.Itoa(money),
	}
	data, code, err := utils.HttpGetReplyCode(url, requestData)
	if err != nil {
		return err
	}
	fmt.Println(code)
	if code != 200 {
		return errors.New(string(data))
	}
	return
}

func (s *GameTask) FreeUploadXjf(gameId, action, account, actionResult, actionState string) (err error) {
	url := global.GVA_CONFIG.ExtranetDomain.Control + "/v1/device/setAccountLog"
	requestData := map[string]string{
		"action":        action,
		"game_id":       gameId,
		"action_result": actionResult,
		"account":       account,
		"actionState":   actionState,
	}
	data, code, err := utils.HttpGetReplyCode(url, requestData)
	if err != nil {
		return err
	}
	fmt.Println(code)
	if code != 200 {
		return errors.New(string(data))
	}
	return
}

func (s *GameTask) QQCardUsedLogUploadXjf(gameId int, account string, money int) (err error) {
	url := global.GVA_CONFIG.ExtranetDomain.Control + "/v1/device/qq_card_hand"
	requestData := map[string]string{
		"game_id":     strconv.Itoa(gameId),
		"card_number": account,
		"money":       strconv.Itoa(money),
	}
	data, code, err := utils.HttpGetReplyCode(url, requestData)
	if err != nil {
		return err
	}
	if code != 200 {
		return errors.New(string(data))
	}
	return
}

//@function: GetGameTaskTargetById
//@description: 根据id获取GameTargetComplete
//@param: id uint
//@return: apiReply response.GetPcListReply, err error
func (c *GameTask) GetGameTaskTargetById(id int, date string) (api response.GetGameTargetComplete, err error) {
	db := global.GVA_DB.Table("game_target_complete gtc")
	db = db.Select("gtc.task_id,gt.task_name,gtc.new_target,gt.login_method,gt.user,gtc.pay_target,gtc.retained_target," +
		"gtc.new_complete,gtc.pay_complete,gtc.retained_complete,gtc.create_date,gtc.amount,gtc.game_rate,gtc.is_complete,gtc.aupr,gtc.total_amount")
	db = db.Joins("left join game_task gt on gt.task_id = gtc.task_id")
	db = db.Where("gtc.task_id = ?", id)
	db = db.Where("gtc.create_date = ?", date)
	err = db.Order("gtc.id desc").Find(&api).Error
	return
}

// 更新GameTaskTarget
func (s *GameTask) UpdateGameTaskTarget(requestData request.UpdateGameTaskTargetRequest) (err error) {
	if errors.Is(global.GVA_DB.Where("task_id = ?", requestData.TaskId).Where("create_date = ?", requestData.CreateDate).First(&task.GameTargetComplete{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("不存在的任务")
	}
	gameTask := new(task.GameTargetComplete)
	global.GVA_DB.Where("task_id = ?", requestData.TaskId).Where("create_date = ?", requestData.CreateDate).First(&gameTask)
	var taskData task.GameTask
	err = global.GVA_DB.Where("task_id = ?", requestData.TaskId).First(&taskData).Error
	if err != nil {
		return
	}
	//if gameTask.NewTarget > requestData.NewTarget && gameTask.RetainedTarget > requestData.RetainedTarget {
	//	return errors.New("任务目标不能小于当前目标")
	//}
	updateData := map[string]interface{}{
		"new_target":             requestData.NewTarget,
		"pay_target":             requestData.PayTarget,
		"retained_target":        requestData.RetainedTarget,
		"hand_new_complete":      requestData.HandNewComplete + gameTask.HandNewComplete,
		"hand_retained_complete": requestData.HandRetainedComplete + gameTask.HandRetainedComplete,
		"hand_pay_complete":      requestData.HandPayComplete + gameTask.HandPayComplete,
		"hand_amount_total":      requestData.HandAmountTotal + gameTask.HandAmountTotal,
		"aupr":                   requestData.Aupr,
		"total_amount":           requestData.TotalAmount,
	}
	date := time.Now().Format("2006-01-02")
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		if requestData.IsFree == 1 {
			handComplete := new(task.GameHandComplete)
			handComplete.TaskId = requestData.TaskId
			handComplete.IsFree = requestData.IsFree
			handComplete.HandAmountTotal = requestData.HandAmountTotal
			handComplete.HandPayComplete = requestData.HandPayComplete
			handComplete.HandRetainedComplete = requestData.HandRetainedComplete
			handComplete.HandNewComplete = requestData.HandNewComplete
			handComplete.FreeMethod = requestData.FreeMethod
			handComplete.CreateDate = gameTask.CreateDate
			handComplete.IsUploadWt = requestData.IsUploadWt
			handComplete.IsUploadXjf = requestData.IsUploadXjf
			err := tx.Omit("create_time").Create(&handComplete).Error
			if err != nil {
				return err
			}
			if len(requestData.CardList) > 0 {
				var cards []task.GameHandCardLog
				for _, card := range requestData.CardList {
					var handCardLog task.GameHandCardLog
					handCardLog.TaskId = requestData.TaskId
					handCardLog.Card = card.Card
					handCardLog.Amount = card.Amount
					handCardLog.HandId = handComplete.Id
					cards = append(cards, handCardLog)
				}
				err := tx.Omit("create_time").Create(&cards).Error
				if err != nil {
					return err
				}
			}
		}
		err = tx.Model(&task.GameTargetComplete{}).Where("task_id = ?", requestData.TaskId).Where("create_date = ?", requestData.CreateDate).Updates(updateData).Error
		if err != nil {
			global.GVA_LOG.Error("更新任务数据失败: ", zap.Error(err))
			return err
		}
		if requestData.IsUploadXjf == 1 || requestData.IsUploadWt == 1 {
			if requestData.HandAmountTotal <= 0 {
				return err
			}
			createDate := gameTask.CreateDate.Format("2006-01-02")
			if requestData.IsUploadWt == 1 {
				if taskData.GamePortId == 5 {
					err = s.FreeUploadWt(taskData.MzGameId, taskData.MzChannel, createDate, requestData.HandAmountTotal, "game_task_report_meizu")
				} else if taskData.GamePortId == 1 {
					err = s.FreeUploadWt(taskData.TxGameId, taskData.TxChannel, createDate, requestData.HandAmountTotal, "game_task_report")
				}
				if err != nil {
					global.GVA_LOG.Error("上传wt财务数据失败gameId = "+taskData.TxGameId+"date = "+createDate, zap.Error(err))
				}
			}
			if requestData.IsUploadXjf == 1 {
				for i := 0; i < requestData.HandPayComplete; i++ {
					account := "hand_" + strconv.Itoa(i) + "_" + strconv.Itoa(int(time.Now().Unix()))
					err = s.FreeUploadXjf(strconv.Itoa(taskData.TaskId), "付费充值", account, "付费成功", "")
					if err != nil {
						global.GVA_LOG.Error("上传xjf数据失败taskId = "+strconv.Itoa(taskData.TaskId)+"date = "+createDate, zap.Error(err))
					}
				}
				if requestData.FreeMethod == 1 && len(requestData.CardList) > 0 {
					for _, card := range requestData.CardList {
						err = s.QQCardUsedLogUploadXjf(taskData.TaskId, card.Card, card.Amount)
						if err != nil {
							global.GVA_LOG.Error("上传qq卡数据失败taskId = "+strconv.Itoa(taskData.TaskId)+"date = "+createDate, zap.Error(err))
						}
					}
				}
			}
		}
		return err
	})
	if gameTask.CreateDate.Format("2006-01-02") == date {
		if gameTask.PayTarget < requestData.PayTarget {
			if taskData.GamePortId != 1 {
				return errors.New("不是腾讯任务,不能更付费")
			}
			global.GVA_LOG.Warn("进入修改add update")
			lastPayAddUpdateTimeKey := fmt.Sprintf(LastPayAddUpdateTimeKey, date, gameTask.TaskId)
			_ = s.cache.SetCacheStr(context.Background(), lastPayAddUpdateTimeKey, time.Now().Unix())
			// 本次加付费目标数据
			lastPayAddNumKey := fmt.Sprintf(LastPayAddNumKey, date, gameTask.TaskId)
			_ = s.cache.SetCacheStr(context.Background(), lastPayAddNumKey, requestData.PayTarget-gameTask.PayTarget)
			payErrAddNumKey := fmt.Sprintf(PayErrAddNumKey, date, gameTask.TaskId)
			s.common.SaveGameAddFee(requestData.PayTarget-gameTask.PayTarget, requestData.PayTarget, taskData.TaskName)
			// 如果当前付费目标完成，加入一下逻辑
			if gameTask.PayTarget <= gameTask.PayComplete {
				lastPayCompletedUpdateTimeKey := fmt.Sprintf(LastPayCompletedUpdateTimeKey, date, gameTask.TaskId)
				_ = s.cache.SetCacheStr(context.Background(), lastPayCompletedUpdateTimeKey, time.Now().Unix())
				_ = s.cache.SetCacheStr(context.Background(), payErrAddNumKey, requestData.PayTarget-gameTask.PayTarget)
			} else {
				n, _ := s.cache.GetCacheNum(context.Background(), payErrAddNumKey)
				_ = s.cache.SetCacheStr(context.Background(), payErrAddNumKey, requestData.PayTarget-gameTask.PayTarget+n)
			}
			go s.common.FreeSendMsg(requestData.PayTarget-gameTask.PayTarget, requestData.PayTarget, taskData.TaskId, taskData.TaskName, taskData.User)
			//msg := "# 监控报警 " + time.Now().Format("2006-01-02 15:04:05")
			//msg += "\n"
			//msg += "**" + taskData.User + "**"
			//msg += "\n"
			//msg += taskData.TaskName + ", 付费目标改为" + strconv.Itoa(requestData.PayTarget)
			////url := "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=5ccfb180-c062-48b5-ae18-0c96f7c19f0b"
			//url := global.GVA_CONFIG.SendUrl.SendUrlOne
			//var sendData SendMsg
			//sendData.MsgType = "markdown"
			//sendData.Markdown.Content = msg
			//s.common.SendMsgData(url, sendData)
		}
	}
	return
}

func (s *GameTask) TargetStatistics(date string) (apiList []control.TargetStatisticsReply, err error) {
	db := global.GVA_DB.Table("game_target_complete gtc")
	db = db.Select("gtc.task_id,gt.task_name,gtc.new_target,gt.login_method,gt.user,gtc.pay_target,gtc.retained_target," +
		"gtc.new_complete,gtc.pay_complete,gtc.retained_complete,gtc.create_date,gt.tx_channel,gt.tx_game_id,gt.mz_channel," +
		"gt.game_id_xmy,gt.mz_game_id,gt.game_port_id,gt.game_id,gt.game_name," +
		"gtc.hand_new_complete,gtc.hand_retained_complete,gtc.hand_pay_complete,gtc.hand_amount_total")
	db = db.Joins("left join game_task gt on gt.task_id = gtc.task_id")
	db = db.Where("gt.is_del = ?", -1)
	db = db.Where("gt.status = ?", 1)
	db = db.Where("gtc.create_date = ?", date)
	var taskTarget []control.GetTargetStatisticsReply
	err = db.Order("gtc.id desc").Find(&taskTarget).Error
	if len(taskTarget) != 0 {
		loginType, _ := s.loginType.GetLoginTypeData()
		gameChannel, _ := s.gameChannel.GetGameChannelData()
		for _, target := range taskTarget {
			var targetStatistics control.TargetStatisticsReply
			targetStatistics.TaskId = target.TaskId
			targetStatistics.TaskName = target.TaskName
			targetStatistics.Date = date
			targetStatistics.TargetActive = target.RetainedTarget
			targetStatistics.TargetPay = target.PayTarget
			targetStatistics.TargetNew = target.NewTarget
			targetStatistics.CompleteNew = target.NewComplete + target.HandNewComplete
			targetStatistics.CompleteActive = target.RetainedComplete + target.HandRetainedComplete
			targetStatistics.CompletePay = target.PayComplete
			targetStatistics.XmyId = target.GameIdXmy
			targetStatistics.QqId = target.TxGameId
			targetStatistics.QqChannel = target.TxChannel
			targetStatistics.MeiZuGameId = target.MzGameId
			targetStatistics.MeiZuChannel = target.MzChannel
			targetStatistics.LoginMode = loginType[int64(target.LoginMethod)].LoginName
			targetStatistics.GamePort = gameChannel[int64(target.GamePortId)].ChannelName
			targetStatistics.GameDirector = target.User
			targetStatistics.GameId = target.GameId
			targetStatistics.GameName = target.GameName
			apiList = append(apiList, targetStatistics)
		}
	}
	return
}

func (s *GameTask) DayStatisticsData(request request.GameTaskStatisticsRequest) (gameTargetDates []response.GameTargetStatistics, err error) {
	createDate := time.Now().Format("2006-01-02")
	gameChannel, _ := s.gameChannel.GetGameChannelData()
	if request.Date == "" || request.Date == createDate {
		request.Date = time.Now().Format("2006-01-02")
		gameTargets, err := s.EveryDayTargetData(request.Date, request)
		if err != nil {
			return gameTargetDates, err
		}
		for _, gameTarget := range gameTargets {
			var gameTargetDate response.GameTargetStatistics
			gameTargetDate.PayTarget = gameTarget.PayTarget
			gameTargetDate.NewTarget = gameTarget.NewTarget
			gameTargetDate.RetainedTarget = gameTarget.RetainedTarget
			gameTargetDate.PayComplete = gameTarget.PayComplete
			gameTargetDate.NewComplete = gameTarget.NewComplete
			gameTargetDate.RetainedComplete = gameTarget.RetainedComplete
			gameTargetDate.Amount = gameTarget.Amount
			gameTargetDate.GamePort = gameChannel[int64(gameTarget.GamePortId)].ChannelName
			gameTargetDate.User = gameTarget.User
			gameTargetDate.TaskDate = gameTarget.CreateDate.Format("2006-01-02")
			gameTargetDates = append(gameTargetDates, gameTargetDate)
		}

	} else {
		gameTargets, err := s.PastDayTargetData(request.Date, request)
		if err != nil {
			return gameTargetDates, err
		}
		for _, gameTarget := range gameTargets {
			var gameTargetDate response.GameTargetStatistics
			gameTargetDate.PayTarget = gameTarget.PayTarget
			gameTargetDate.NewTarget = gameTarget.NewTarget
			gameTargetDate.RetainedTarget = gameTarget.RetainedTarget
			gameTargetDate.PayComplete = gameTarget.PayComplete
			gameTargetDate.NewComplete = gameTarget.NewComplete
			gameTargetDate.RetainedComplete = gameTarget.RetainedComplete
			gameTargetDate.Amount = gameTarget.Amount
			gameTargetDate.TaskDate = gameTarget.TaskDate.Format("2006-01-02")
			gameTargetDate.GamePort = gameChannel[int64(gameTarget.GamePortId)].ChannelName
			gameTargetDate.User = gameTarget.User
			gameTargetDates = append(gameTargetDates, gameTargetDate)
		}

	}
	return
}

func (s *GameTask) EveryDayTargetData(date string, request request.GameTaskStatisticsRequest) (gameTarget []response.GameTargetCompleteReply, err error) {
	db := global.GVA_DB.Table("game_target_complete gtc")
	db = db.Select("gtc.create_date,SUM(gtc.new_complete) new_complete,SUM(gtc.pay_complete) pay_complete,SUM(gtc.retained_complete) retained_complete,SUM(gtc.new_target) new_target,SUM(gtc.pay_target) pay_target,SUM(gtc.retained_target) retained_target,SUM(gtc.amount) amount,SUM(gtc.hand_pay_complete) hand_pay_complete,SUM(gtc.hand_new_complete) hand_new_complete,SUM(gtc.hand_retained_complete) hand_retained_complete,SUM(gtc.hand_amount_total) hand_amount_total," +
		"gt.user,gt.game_port_id")
	db = db.Joins("left join game_task gt on gt.task_id = gtc.task_id")
	db = db.Where("gtc.create_date = ?", date)
	if request.GroupKey != "" {
		group := "gt." + request.GroupKey
		db = db.Group(group)
	}
	err = db.Find(&gameTarget).Error
	return
}

func (s *GameTask) PastDayTargetData(date string, request request.GameTaskStatisticsRequest) (gameTarget []task.GameTargetStatistics, err error) {
	db := global.GVA_DB.Table("game_target_statistics")
	db = db.Where("task_date = ?", date)
	if request.GroupKey != "" {
		group := request.GroupKey
		db = db.Group(group)
	}
	err = db.Find(&gameTarget).Error
	return
}

func (s *GameTask) MonthStatisticsData() (gameTarget []task.GameTargetStatistics, err error) {
	year, _, _ := time.Now().Date()
	db := global.GVA_DB.Table("game_target_statistics")
	db = db.Select("task_year,task_month,SUM(new_complete) new_complete,SUM(pay_complete) pay_complete,SUM(retained_complete) retained_complete,SUM(new_target) new_target,SUM(pay_target) pay_target,SUM(retained_target) retained_target,SUM(amount) amount")
	db = db.Where("task_year = ?", year)
	db = db.Group("task_month")
	err = db.Find(&gameTarget).Error
	return
}

func (s *GameTask) GameStatisticsData(date string) (gameTarget []response.GameStatisticsDataReply, err error) {
	if date == "" {
		date = time.Now().Format("2006-01-02")
	}
	db := global.GVA_DB.Table("game_target_complete gtc")
	db = db.Select("gt.user,gt.game_port_id,COUNT(DISTINCT(gtc.task_id)) total,gtc.create_date")
	db = db.Joins("left join game_task gt on gt.task_id = gtc.task_id")
	db = db.Where("gtc.create_date = ?", date)
	db = db.Group("gt.user,gt.game_port_id")
	err = db.Find(&gameTarget).Error
	if err != nil {
		return nil, err
	}
	gameChannel, _ := s.gameChannel.GetGameChannelData()
	for i, target := range gameTarget {
		gameTarget[i].GamePort = gameChannel[int64(target.GamePortId)].ChannelName
		gameTarget[i].CreateDate = date
	}
	return
}

func (s *GameTask) GameStatisticsList(rq request.GameListRequest) (gameTarget []response.GameStatisticsListReply, err error) {
	if rq.Date == "" {
		rq.Date = time.Now().Format("2006-01-02")
	}
	db := global.GVA_DB.Table("game_target_complete gtc")
	db = db.Select("gt.game_port_id,gt.game_name")
	db = db.Joins("left join game_task gt on gt.task_id = gtc.task_id")
	db = db.Where("gtc.create_date = ?", rq.Date)
	db = db.Where("gt.user = ?", rq.User)
	db = db.Where("gt.game_port_id = ?", rq.GamePortId)
	err = db.Find(&gameTarget).Error
	if err != nil {
		return nil, err
	}
	gameChannel, _ := s.gameChannel.GetGameChannelData()
	for i, target := range gameTarget {
		gameTarget[i].GamePort = gameChannel[int64(target.GamePortId)].ChannelName
		gameTarget[i].CreateDate = rq.Date
	}
	return
}

//
func (s *GameTask) ResetFeeUploadXjf(gameId int) (err error) {
	url := global.GVA_CONFIG.ExtranetDomain.Control + "/v1/task_statistics/rerun_retained"
	requestData := map[string]string{
		"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
}

//@function: TaskResetFee
//@description: 重置付费
//@param: api task.GameTask
//@return: err error
func (s *GameTask) TaskResetFee(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
	}
	err = s.ResetFeeUploadXjf(api.TaskId)
	if err != nil {
		global.GVA_LOG.Error("请求群控数据报错: ", zap.Error(err))
		return errors.New("请求群控数据报错")
	}
	return
}

// http请求群控付费账号
func (s *GameTask) GetFeeAccountControl(taskId int) (d []byte, err error) {
	url := global.GVA_CONFIG.ExtranetDomain.Control + "/v1/device/get_log_by_game"
	//url := "http://xjf.lianyou.fun:8099/v1/device/get_log_by_game"
	params := map[string]string{
		"date":          time.Now().Format("2006-01-02"),
		"action":        "付费账号",
		"action_result": "占位",
		"game_id":       strconv.Itoa(taskId),
	}
	d, code, err := utils.HttpGetReplyCode(url, params)
	fmt.Println(code)
	if code != 200 {
		return nil, errors.New(string(d))
	}
	return
}

type FeeAccount struct {
	Account  string `json:"account"`
	Password string `json:"password"`
}

func (s *GameTask) GetFeeAccountList(taskId int) (fa []FeeAccount, err error) {
	b, err := s.GetFeeAccountControl(taskId)
	if err != nil {
		return
	}
	err = json.Unmarshal(b, &fa)
	if err != nil {
		return
	}
	return
}

//从小绵羊后台获取数据并返回
func (apiService *GameTask) GetXmyTaskList(startDay string, endDay string) (list interface{}, err error) {
	var apisReply *response.XmyGameDataReply
	client := &http.Client{}
	url := "http://api.sheepsdk.17xmy.com/foreign/api/get_youhua_data.php?start_day=" + startDay + "&end_day=" + endDay
	req, err := http.NewRequest("GET", url, nil) //GET大写
	if err != nil {
		return
	}
	rep, err := client.Do(req) //发起请求
	if err != nil {
		return
	}
	data, err := ioutil.ReadAll(rep.Body)
	rep.Body.Close()
	json.Unmarshal(data, &apisReply)
	if err != nil {
		return
	}
	//fmt.Printf("%s", apisReply)
	return apisReply.Data, err
}

func (exa *GameTask) TaskStatisticsList2Excel(infoList []response.GetGameTargetComplete, filePath string) error {
	excel := excelize.NewFile()
	excel.SetSheetRow("Sheet1", "A1", &[]string{
		"日期",
		"任务id",
		"任务名称",
		"登录方式",
		"目标新增",
		"目标付费",
		"目标活跃",
		"完成新增",
		"完成付费",
		"完成活跃",
		"未完新增",
		"未完付费",
		"未完活跃",
		"负责人",
		"完成",
		"手动付费",
		"手动付费金额",
		"付费流水"})
	for i, statisticsLog := range infoList {
		axis := fmt.Sprintf("A%d", i+2)
		newNo := 0
		retainedNo := 0
		payNo := 0
		isComplete := "是"
		if statisticsLog.IsComplete == -1 {
			isComplete = "否"
		}
		if statisticsLog.PayComplete < statisticsLog.PayTarget {
			payNo = statisticsLog.PayTarget - statisticsLog.PayComplete
		}
		if statisticsLog.RetainedComplete+statisticsLog.HandRetainedComplete < statisticsLog.RetainedTarget {
			retainedNo = statisticsLog.RetainedTarget - statisticsLog.RetainedComplete - statisticsLog.HandRetainedComplete
		}
		if statisticsLog.NewComplete+statisticsLog.HandNewComplete < statisticsLog.NewTarget {
			newNo = statisticsLog.NewTarget - statisticsLog.NewComplete - statisticsLog.HandNewComplete
		}
		excel.SetSheetRow("Sheet1", axis, &[]interface{}{
			statisticsLog.CreateDate[:10],
			statisticsLog.TaskId,
			statisticsLog.TaskName,
			statisticsLog.LoginMethod,
			statisticsLog.NewTarget,
			statisticsLog.PayTarget,
			statisticsLog.RetainedTarget,
			statisticsLog.NewComplete + statisticsLog.NewComplete,
			statisticsLog.PayComplete,
			statisticsLog.RetainedComplete + statisticsLog.HandRetainedComplete,
			newNo,
			payNo,
			retainedNo,
			statisticsLog.User,
			isComplete,
			statisticsLog.HandPayComplete,
			statisticsLog.HandAmountTotal,
			statisticsLog.Amount,
		})
	}
	err := excel.SaveAs(filePath)
	return err
}

func (apiService *GameTask) TemporaryTask(ctx context.Context, pcCode string) (temporaryConf task.CentralControlConf, err error) {
	date := time.Now().Format("2006-01-02")
	key := fmt.Sprintf(cache.TemporaryTaskPcCode, date, pcCode)
	taskId, _ := apiService.cache.GetCacheStr(ctx, key)
	if taskId == "" {
		return temporaryConf, errors.New("没有任务数据")
	}
	err = global.GVA_DB.Model(&task.CentralControlConf{}).Where("task_id", taskId).First(&temporaryConf).Error
	if err == nil {
		global.GVA_REDIS.Del(ctx, key)
	}
	return temporaryConf, err
}
