package cron

import (
	"time"

	"github.com/parnurzeal/gorequest"
	"go.uber.org/zap"
	"courseSign/server/global"
	"courseSign/server/model/airDrop"
)

type VoiceDailyJob struct {
	JobName string
	client *gorequest.SuperAgent
}

var isVoiceJobRun bool

func (job VoiceDailyJob) Run() {
	job.JobName = "VoiceDailyJob"
	if isVoiceJobRun {
		global.GVA_LOG.Info(job.JobName, zap.String("job", "already run"))
		return
	}
	isVoiceJobRun = true
	global.GVA_LOG.Info(job.JobName, zap.String("job", "start"))
	t := time.Now()
	defer func() {
		isVoiceJobRun = false
		global.GVA_LOG.Info(job.JobName, zap.String("cost", time.Since(t).String()))
	}()
	job.client = gorequest.New()
	var err error

	err = job.CreateRedPackageGroup()
	if err != nil {
		global.GVA_LOG.Error(job.JobName, zap.String("QueryTickets err", err.Error()))
		return
	}
	return
}

// CreateRedPackageGroup 创建红包分组
func (job VoiceDailyJob) CreateRedPackageGroup() error {
	list := make([]*airDrop.VoiceVerify,0)
	err := global.GVA_DB.Model(&airDrop.VoiceVerify{}).Where("status = ?",airDrop.VoiceVerifyNormal).Find(&list).Error
	if err != nil {
		return err
	}
	type voiceRes struct {
		ID string `json:"id"`
		Result int64 `json:"result"`
		Error string `json:"error"`
		Timestamp int64 `json:"timestamp"`
	}
	global.GVA_LOG.Info("待验证条数",zap.Any("count",len(list)))
	for _,v := range list {
		var res voiceRes
		resp,_, errs := job.client.Get("https://voice.bityuan.com/upload/result?address="+v.Addr).EndStruct(&res)
		if len(errs) > 0  {
			global.GVA_LOG.Error("req voice result err",zap.Error(errs[0]))
			continue
		}
		global.GVA_LOG.Info("code",zap.Any("RESULT",resp.StatusCode),zap.Any("voice result",res))
		if resp.StatusCode == 200 {
			if res.Result == 0 || res.Result == 1 {
				err = global.GVA_DB.Model(&airDrop.VoiceVerify{}).Where("id = ?",v.ID).UpdateColumns(map[string]interface{}{"status":airDrop.VoiceVerifyPass,"verify_time":res.Timestamp}).Error
				if err != nil {
					global.GVA_LOG.Error("req voice result update err", zap.Error(err))
					continue
				}
			} else {
				err = global.GVA_DB.Model(&airDrop.VoiceVerify{}).Where("id = ?",v.ID).UpdateColumns(map[string]interface{}{"status":airDrop.VoiceVerifyNotPass,"verify_time":time.Now().Unix()}).Error
				if err != nil {
					global.GVA_LOG.Error("req voice result update err",zap.Error(err))
					continue
				}
			}
		}
	}
	global.GVA_LOG.Info("job done")
	return nil
}
