package entrustPool

import (
	"strings"
	"time"

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

type PoolAddrService struct {
}

// CreatePoolAddr 创建PoolAddr记录
// Author [piexlmax](https://github.com/piexlmax)
func (poolAddrService *PoolAddrService) CreatePoolAddr(poolAddr entrustPool.PoolAddr) (err error) {
	err = global.GVA_DB.Create(&poolAddr).Error
	return err
}

// DeletePoolAddr 删除PoolAddr记录
// Author [piexlmax](https://github.com/piexlmax)
func (poolAddrService *PoolAddrService)DeletePoolAddr(poolAddr entrustPool.PoolAddr) (err error) {
	err = global.GVA_DB.Delete(&poolAddr).Error
	return err
}

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

// UpdatePoolAddr 更新PoolAddr记录
// Author [piexlmax](https://github.com/piexlmax)
func (poolAddrService *PoolAddrService)UpdatePoolAddr(poolAddr entrustPool.PoolAddr) (err error) {
	err = global.GVA_DB.Save(&poolAddr).Error
	return err
}

// GetPoolAddr 根据id获取PoolAddr记录
// Author [piexlmax](https://github.com/piexlmax)
func (poolAddrService *PoolAddrService)GetPoolAddr(id uint) (poolAddr entrustPool.PoolAddr, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&poolAddr).Error
	return
}

// GetPoolAddrByAddr 根据addr获取PoolAddrInfo记录
func (poolAddrService *PoolAddrService)GetPoolAddrByAddr(addr string) (poolAddr entrustPoolReq.PoolAddrAccount, err error) {
	if address.IsEthAddress(addr) {
		addr = strings.ToLower(addr)
	}
	poolAddr.Addr = addr
	list := make([]*entrustPoolReq.PoolAddrFeeInfo,0)
	poolAddrList := make([]entrustPool.PoolAddr,0)
	err = global.GVA_DB.Model(&entrustPool.PoolAddr{}).Where("addr = ?", addr).Find(&poolAddrList).Error
	if err != nil {
		return
	}
	for _, v := range poolAddrList {
		var pool entrustPool.Pool
		err = global.GVA_DB.Model(&pool).Where("id = ?",*v.PoolId).First(&pool).Error
		if err == nil {
			var add entrustPoolReq.PoolAddrFeeInfo
			add.FeeAddr = pool.FeeAddr
			add.MinerAddr = pool.MinerAddr
			add.Fee = *v.Fee
			add.PoolId = *v.PoolId
			add.FeeHash = v.FeeHash
			add.FeeTBD = *v.FeeTBD
			add.FeeSend = *v.FeeSend
			add.PoolName = pool.Name
			list = append(list,&add)
			if pool.Creator == addr {
				poolAddr.Pool = &pool
			}
		}
	}
	if poolAddr.Pool == nil {
		var pool entrustPool.Pool
		err = global.GVA_DB.Model(&pool).Where("creator = ?",addr).First(&pool).Error
		if err != nil && err != gorm.ErrRecordNotFound {
			return
		} else if err != nil && err == gorm.ErrRecordNotFound {
			err = nil
		} else {
			poolAddr.Pool = &pool
		}
	}
	if len(list) > 0 {
		poolAddr.Data = list
	}
	return
}

// UpdateAddrFee 根据addr hash 更新addr Fee
func (poolAddrService *PoolAddrService)UpdateAddrFee(addr ,miner,hash string) (poolAddr entrustPool.PoolAddr, err error) {
	if address.IsEthAddress(addr) {
		addr = strings.ToLower(addr)
	}
	var pool entrustPool.Pool
	err = global.GVA_DB.Model(&pool).Where("miner_addr = ?",miner).First(&pool).Error
	if err != nil {
		return
	}
	err = global.GVA_DB.Model(&entrustPool.PoolAddr{}).Where("addr = ? and pool_id = ?", addr,pool.ID).First(&poolAddr).Error
	if err != nil {
		return
	}
	if poolAddr.FeeHash != "" {
		err = errno.ErrFeeHashNotConfirm
		return
	}
	err = global.GVA_DB.Model(&entrustPool.PoolAddr{}).Where("id = ?",poolAddr.ID).Updates(map[string]interface{}{"fee_hash":hash,"fee_tbd":time.Now().Unix()+10800}).Error
	if err != nil {
		return
	}
	return
}

// GetPoolAddrInfoList 分页获取PoolAddr记录
// Author [piexlmax](https://github.com/piexlmax)
func (poolAddrService *PoolAddrService)GetPoolAddrInfoList(info entrustPoolReq.PoolAddrSearch) (list []entrustPool.PoolAddr, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&entrustPool.PoolAddr{})
    var poolAddrs []entrustPool.PoolAddr
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.StartCreatedAt !=nil && info.EndCreatedAt !=nil {
     db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
    }
    if info.Addr != "" {
    	db = db.Where("addr = ?",info.Addr)
	}
	if info.MinerAddr != "" {
		db =db.Where("miner_addr = ?",info.MinerAddr)
	}
	err = db.Count(&total).Error
	if err!=nil {
    	return
    }

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