package brc

import (
	"ffie-admin/server/global"
	"ffie-admin/server/model/brc"
	brcReq "ffie-admin/server/model/brc/request"
	"ffie-admin/server/model/common/request"
	"ffie-admin/server/model/common/response"
	"ffie-admin/server/service"
	"ffie-admin/server/utils"
	"strings"

	"github.com/blockcypher/gobcy/v2"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type BrcListApi struct {
}

var brcListService = service.ServiceGroupApp.BrcServiceGroup.BrcListService

// CreateBrcList 创建BrcList
// @Tags BrcList
// @Summary 创建BrcList
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body brc.BrcList true "创建BrcList"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /brcList/createBrcList [post]
func (brcListApi *BrcListApi) CreateBrcList(c *gin.Context) {
	var brcList brc.BrcList
	err := c.ShouldBindJSON(&brcList)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	verify := utils.Rules{
		"Inscription": {utils.NotEmpty()},
		"Hash":        {utils.NotEmpty()},
		"LockAddr":    {utils.NotEmpty()},
	}
	if err := utils.Verify(brcList, verify); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	bc := global.GVA_GOBCY
	var zeroGobcyAPI gobcy.API
	if bc == zeroGobcyAPI {
		response.FailWithMessage("BlockCypher 客户端未初始化", c)
		return
	}

	// 使用 BlockCypher API 获取交易详情
	tx, err := bc.GetTX(brcList.Hash, nil)
	if err != nil {
		global.GVA_LOG.Error("查询链上铭文失败!", zap.Error(err))
		response.FailWithMessage("链上未找到对应铭文或查询失败", c)
		return
	}
	if tx.Hash == "" {
		response.FailWithMessage("链上交易不存在", c)
		return
	}

	// 遍历交易输出，查找铭文数据
	foundInscription := false
	for _, vout := range tx.Outputs {
		// 检查 ScriptPubKey 是否包含 asm 字段
		if vout.Script != "" {
			asm := vout.Script
			global.GVA_LOG.Info("asm:", zap.String("asm", asm))
			if asm != "" {
				// 检查是否符合 ord 协议特征
				if strings.Contains(asm, "OP_FALSE OP_IF") && strings.Contains(asm, "ord") {
					// 检查铭文 ID 是否存在
					if strings.Contains(asm, brcList.Inscription) {
						foundInscription = true
						break
					}
				}
			}
		}
	}

	if !foundInscription {
		global.GVA_LOG.Error("链上未找到匹配的铭文 ID!", zap.String("期望铭文 ID", brcList.Inscription))
		response.FailWithMessage("链上未找到匹配的铭文 ID", c)
		return
	}
	/*
		// 通过 global.GVA_BTCCli 对铭文进行查询验证
		if global.GVA_BTCCli == nil {
			response.FailWithMessage("BTC 客户端未初始化", c)
			return
		}
		// 将 brcList.Hash 从 string 转换为 chainhash.Hash 格式
		txHash, err := chainhash.NewHashFromStr(brcList.Hash)
		if err != nil {
			global.GVA_LOG.Error("哈希格式转换失败!", zap.Error(err))
			response.FailWithMessage("哈希格式无效", c)
			return
		}
		// 使用转换后的 txHash 查询链上的铭文信息
		tx, err := global.GVA_BTCCli.GetRawTransactionVerbose(txHash)
		if err != nil {
			global.GVA_LOG.Error("查询链上铭文失败!", zap.Error(err))
			response.FailWithMessage("链上未找到对应铭文或查询失败", c)
			return
		}
		if tx == nil {
			response.FailWithMessage("链上交易不存在", c)
			return
		}

		// 遍历交易输出，查找铭文数据
		foundInscription := false
		for _, vout := range tx.Vout {
			// 检查 ScriptPubKey 是否为 nil 或空字符串，结构体包含切片不能直接比较，通过检查 Asm 字段来判断
			if vout.ScriptPubKey.Asm != "" {
				// 检查是否包含铭文协议标记，这里以常见的 "ord" 协议为例
				asm := vout.ScriptPubKey.Asm
				// 字符串类型不能和 nil 比较，改为判断是否为空字符串
				global.GVA_LOG.Info("asm:", zap.String("asm", asm))
				if asm != "" {
					// 检查是否符合 ord 协议特征
					if strings.Contains(asm, "OP_FALSE OP_IF") && strings.Contains(asm, "ord") {
						// 检查铭文 ID 是否存在
						if strings.Contains(asm, brcList.Inscription) {
							foundInscription = true
							break
						}
					}
				}
			}
		}

		if !foundInscription {
			global.GVA_LOG.Error("链上未找到匹配的铭文 ID!", zap.String("期望铭文 ID", brcList.Inscription))
			response.FailWithMessage("链上未找到匹配的铭文 ID", c)
			return
		}
	*/
	if err := brcListService.CreateBrcList(brcList); err != nil {
		global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败", c)
	} else {
		response.OkWithMessage("创建成功", c)
	}
}

// DeleteBrcList 删除BrcList
// @Tags BrcList
// @Summary 删除BrcList
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body brc.BrcList true "删除BrcList"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /brcList/deleteBrcList [delete]
func (brcListApi *BrcListApi) DeleteBrcList(c *gin.Context) {
	var brcList brc.BrcList
	err := c.ShouldBindJSON(&brcList)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := brcListService.DeleteBrcList(brcList); err != nil {
		global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
	} else {
		response.OkWithMessage("删除成功", c)
	}
}

// DeleteBrcListByIds 批量删除BrcList
// @Tags BrcList
// @Summary 批量删除BrcList
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "批量删除BrcList"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /brcList/deleteBrcListByIds [delete]
func (brcListApi *BrcListApi) DeleteBrcListByIds(c *gin.Context) {
	var IDS request.IdsReq
	err := c.ShouldBindJSON(&IDS)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := brcListService.DeleteBrcListByIds(IDS); err != nil {
		global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败", c)
	} else {
		response.OkWithMessage("批量删除成功", c)
	}
}

// UpdateBrcList 更新BrcList
// @Tags BrcList
// @Summary 更新BrcList
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body brc.BrcList true "更新BrcList"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /brcList/updateBrcList [put]
func (brcListApi *BrcListApi) UpdateBrcList(c *gin.Context) {
	var brcList brc.BrcList
	err := c.ShouldBindJSON(&brcList)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	verify := utils.Rules{
		"Inscription": {utils.NotEmpty()},
		"Hash":        {utils.NotEmpty()},
		"LockAddr":    {utils.NotEmpty()},
	}
	if err := utils.Verify(brcList, verify); err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := brcListService.UpdateBrcList(brcList); err != nil {
		global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败", c)
	} else {
		response.OkWithMessage("更新成功", c)
	}
}

// FindBrcList 用id查询BrcList
// @Tags BrcList
// @Summary 用id查询BrcList
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query brc.BrcList true "用id查询BrcList"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /brcList/findBrcList [get]
func (brcListApi *BrcListApi) FindBrcList(c *gin.Context) {
	var brcList brc.BrcList
	err := c.ShouldBindQuery(&brcList)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if rebrcList, err := brcListService.GetBrcList(brcList.ID); err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithData(gin.H{"rebrcList": rebrcList}, c)
	}
}

// FindBrcByToken 用id查询BrcList
// @Tags BrcList
// @Summary 用id查询BrcList
// @accept application/json
// @Produce application/json
// @Param data query brc.BrcList true "用id查询BrcList"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /brcList/findBrcListByToken [get]
func (brcListApi *BrcListApi) FindBrcByToken(c *gin.Context) {
	var brcList brc.BrcList
	err := c.ShouldBindQuery(&brcList)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if rebrcList, err := brcListService.GetBrcListByToken(brcList.Token); err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithData(gin.H{"brc": rebrcList}, c)
	}
}

// GetBrcListList 分页获取BrcList列表
// @Tags BrcList
// @Summary 分页获取BrcList列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query brcReq.BrcListSearch true "分页获取BrcList列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /brcList/getBrcListList [get]
func (brcListApi *BrcListApi) GetBrcListList(c *gin.Context) {
	var pageInfo brcReq.BrcListSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if list, total, err := brcListService.GetBrcListInfoList(pageInfo); err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	} else {
		response.OkWithDetailed(response.PageResult{
			List:     list,
			Total:    total,
			Page:     pageInfo.Page,
			PageSize: pageInfo.PageSize,
		}, "获取成功", c)
	}
}
