package entrustPool

import (
	"context"
	"errors"
	"strings"

	"github.com/33cn/chain33/common/address"
	"github.com/33cn/chain33/types"
	"gorm.io/gorm"
	"courseSign/server/global"
	"courseSign/server/model/common/request"
	"courseSign/server/model/entrustPool"
	entrustPoolReq "courseSign/server/model/entrustPool/request"
)

type PoolService struct {
}

// CreatePool 创建Pool记录
// Author [piexlmax](https://github.com/piexlmax)
func (poolService *PoolService) CreatePool(pool entrustPool.Pool) (err error) {
	if address.IsEthAddress(pool.MinerAddr) {
		pool.MinerAddr = strings.ToLower(pool.MinerAddr)
	} else {
		return errors.New("wrong address type")
	}
	if address.IsEthAddress(pool.FeeAddr) {
		pool.FeeAddr = strings.ToLower(pool.FeeAddr)
	} else {
		return errors.New("wrong address type")
	}
	pool.Name = strings.TrimSpace(pool.Name)
	pool.MinerAddr = strings.TrimSpace(pool.MinerAddr)
	pool.FeeAddr = strings.TrimSpace(pool.FeeAddr)
	err = address.CheckAddress(pool.FeeAddr,-1)
	if err != nil {
		return err
	}
	err = address.CheckAddress(pool.MinerAddr,-1)
	if err != nil {
		return err
	}
	var pl entrustPool.Pool
	var pn entrustPool.Pool
	if pool.MinerAddr == "" {
		return errors.New("addr not set")
	}
	err = global.GVA_DB.Model(&entrustPool.Pool{}).Where("miner_addr = ?",pool.MinerAddr).First(&pl).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return
	}
	if err == nil && pl.ID > 0 {
		return errors.New("pool is exist")
	}

	err = global.GVA_DB.Model(&entrustPool.Pool{}).Where("name = ?",pool.Name).First(&pn).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return
	}
	if err == nil && pn.ID > 0 {
		return errors.New("pool name is exist")
	}
	// ticket,err := poolService.GetTicketNum(pool.MinerAddr)
	// if err != nil {
	// 	return
	// }
	// if ticket < 20 {
	// 	return errors.New("ticket must over 20 ")
	// }
	isShow := true
	pool.IsShow = &isShow
	err = global.GVA_DB.Create(&pool).Error
	return err
}

func (poolService *PoolService)GetTicketNum(addr string) (int,error) {
	var ticket int
	var err error
	req := &types.ChainExecutor{
		Driver:   "ticket",
		FuncName: "MinerSourceList",
		Param:    types.Encode(&types.ReqString{Data: addr}),
	}
	query ,err := global.Client.QueryChain(context.Background(),req)
	if err != nil && strings.Contains(err.Error(),"ErrNotFound") {
		return 0,nil
	} else if err != nil && !strings.Contains(err.Error(),"ErrNotFound"){
		return 0,err
	}
	var replyStrings types.ReplyStrings
	err = types.Decode(query.GetMsg(), &replyStrings)
	if err != nil {
		return 0, err
	}
	for _, v := range replyStrings.GetDatas() {
		balance,err := global.Client.GetBalance(context.Background(),&types.ReqBalance{
			Addresses:   []string{v},
			Execer:      "ticket",
		})
		if err != nil {
			return ticket,err
		}
		ticket += int((balance.Acc[0].Balance+ balance.Acc[0].Frozen)/1e8) /3000
	}
	return ticket ,nil
}

// DeletePool 删除Pool记录
// Author [piexlmax](https://github.com/piexlmax)
func (poolService *PoolService)DeletePool(pool entrustPool.Pool) (err error) {
	err = global.GVA_DB.Delete(&pool).Error
	return err
}

// DeletePoolByIds 批量删除Pool记录
// Author [piexlmax](https://github.com/piexlmax)
func (poolService *PoolService)DeletePoolByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]entrustPool.Pool{},"id in ?",ids.Ids).Error
	return err
}

// UpdatePool 更新Pool记录
// Author [piexlmax](https://github.com/piexlmax)
func (poolService *PoolService)UpdatePool(pool entrustPool.Pool) (err error) {
	err = global.GVA_DB.Save(&pool).Error
	return err
}

// GetPool 根据id获取Pool记录
// Author [piexlmax](https://github.com/piexlmax)
func (poolService *PoolService)GetPool(id uint) (pool entrustPool.Pool, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&pool).Error
	return
}

// GetPoolByAddr 根据addr获取Pool记录
func (poolService *PoolService)GetPoolByAddr(minerAddr string) (pool entrustPool.Pool, err error) {
	var addr string
	if address.IsEthAddress(minerAddr) {
		addr = strings.ToLower(minerAddr)
	} else {
		addr = minerAddr
	}
	err = global.GVA_DB.Where("miner_addr = ?", addr).First(&pool).Error
	if *pool.IsShow {
		err = errors.New("node not exist")
	}
	return
}

// GetPoolByCreator 根据addr获取Pool记录
func (poolService *PoolService)GetPoolByCreator(creator string) (pool entrustPool.Pool, err error) {
	var addr string
	if address.IsEthAddress(creator) {
		addr = strings.ToLower(creator)
	} else {
		addr = creator
	}
	err = global.GVA_DB.Where("creator = ?", addr).First(&pool).Error
	return
}

func (poolService *PoolService)GetPoolInfoList2(info entrustPoolReq.PoolSearch) (list []entrustPool.Pool, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&entrustPool.Pool{})
	var pools []entrustPool.Pool

	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt !=nil && info.EndCreatedAt !=nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.MinerAddr != "" {
		db = db.Where("miner_addr = ?",info.MinerAddr)
	}
	err = db.Count(&total).Error
	if err!=nil {
		return
	}

	err = db.Limit(limit).Order("tickets desc").Offset(offset).Find(&pools).Error
	return  pools, total, err
}

// GetPoolInfoList 分页获取Pool记录
// Author [piexlmax](https://github.com/piexlmax)
func (poolService *PoolService)GetPoolInfoList(info entrustPoolReq.PoolSearch) (list []entrustPool.Pool, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&entrustPool.Pool{})
    var pools []entrustPool.Pool
	// 搜索显示具体节点
	if info.MinerAddr != "" && info.Name != "" {
		err = errors.New("not support")
		return
	}
	db = db.Where("name_normal = ? ",1)
	if info.MinerAddr != "" {
		db = db.Where("miner_addr = ? ",strings.ToLower(info.MinerAddr))
	} else if info.Name != "" {
		db = db.Where("name = ?",strings.TrimSpace(info.Name))
	} else {
		// 不搜索 需要300票显示
		db = db.Where("tickets >= ? and is_admin = ?",entrustPool.PoolTicketLimit,0)
	}
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.StartCreatedAt !=nil && info.EndCreatedAt !=nil {
     db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
    }
	err = db.Count(&total).Error
	if err!=nil {
    	return
    }

	err = db.Limit(limit).Order("tickets desc").Offset(offset).Find(&pools).Error
	return  pools, total, err
}


// UpdatePool 更新Pool记录
func (poolService *PoolService)UpdateWebPool(pool entrustPool.PoolNameReq) (err error) {
	err = global.GVA_DB.Model(&entrustPool.Pool{}).Where("miner_addr = ? and creator = ?",pool.MinerAddr,pool.Creator).Update("name",pool.Name).Error
	return err
}