package jobs

import (
	"encoding/json"
	"fmt"
	"go-admin/app/admin/models"
	"go-admin/app/admin/service"
	"go-admin/app/admin/service/appservice"
	"go-admin/app/admin/service/dto"
	"go-admin/pkg/utility"
	"io/ioutil"
	"net/http"
	"time"

	"github.com/go-admin-team/go-admin-core/logger"
	"github.com/shopspring/decimal"
)

type TrxQueryJobs struct {
}

const (
	tronGridURL         = "https://api.trongrid.io" // TronGrid API 地址
	UsdtContractAddress = "TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t"
)

// TRC20Transfer 结构体用于解析 TRC20 转账记录
type TRC20Transfer struct {
	TransactionID string `json:"transaction_id"`
	BlockNumber   int64  `json:"block_number"`
	Timestamp     int64  `json:"block_timestamp"`
	FromAddress   string `json:"from"`
	ToAddress     string `json:"to"`
	Value         string `json:"value"`
	TokenInfo     struct {
		Symbol   string `json:"symbol"`
		Address  string `json:"address"`
		Decimals int    `json:"decimals"`
	} `json:"token_info"`
}

// GetTRC20Transfers 获取指定 TRC20 代币的交易记录
func GetTRC20Transfers(contractAddress, accountAddress string, minTimestamp, maxTimestamp int64) ([]TRC20Transfer, error) {
	url := fmt.Sprintf("%s/v1/accounts/%s/transactions/trc20?contract_address=%s", tronGridURL, accountAddress, contractAddress)
	if minTimestamp > 0 {
		url += fmt.Sprintf("&min_timestamp=%d", minTimestamp)
	}
	if maxTimestamp > 0 {
		url += fmt.Sprintf("&max_timestamp=%d", maxTimestamp)
	}
	resp, err := http.Get(url)
	if err != nil {
		return nil, fmt.Errorf("failed to send request: %v", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("failed to read response body: %v", err)
	}

	var result struct {
		Data []TRC20Transfer `json:"data"`
	}
	if err := json.Unmarshal(body, &result); err != nil {
		return nil, fmt.Errorf("failed to unmarshal response: %v", err)
	}
	return result.Data, nil
}

func (t TrxQueryJobs) Exec(arg interface{}) error {
	configService := service.SysConfig{}
	configService.Orm = getDefaultDb()
	req := dto.SysConfigByKeyReq{}
	req.ConfigKey = "member_receive_address"
	configData := dto.GetSysConfigByKEYForServiceResp{}
	configService.GetWithKey(&req, &configData)
	if configData.ConfigValue == "" {
		logger.Error("查询地址为空")
		return nil
	}

	userAppService := appservice.LineUser{}
	userAppService.Orm = getDefaultDb()
	startTime := time.Now().UnixMilli()
	endTime := time.Now().Add(-1 * time.Hour).UnixMilli()
	transfers, err := GetTRC20Transfers(UsdtContractAddress, configData.ConfigValue, endTime, startTime)
	if err != nil {
		logger.Error("查询失败", err)
		return nil
	}

	logs := make([]models.MemberRenwaLog, 0)
	item := models.MemberRenwaLog{}

	for _, transfer := range transfers {
		if transfer.TransactionID == "" || transfer.ToAddress != configData.ConfigValue {
			continue
		}

		//实际金额
		payableAmount := utility.StringToDecimal(transfer.Value).Div(decimal.NewFromInt(10).Pow(decimal.NewFromInt(int64(transfer.TokenInfo.Decimals)))).Truncate(6)
		item.Hash = transfer.TransactionID
		item.PayableAmount = payableAmount
		item.FromAddress = transfer.FromAddress

		logs = append(logs, item)
	}

	if len(logs) > 0 {
		err := userAppService.PayCallBack(logs)

		if err != nil {
			logger.Error("执行完毕,err:")
		}
	}

	return nil
}
