package accounts

import (
	"context"
	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	"time"
)

type AccountInfo struct {
	Id           int
	Status       string
	AccountUid   string
	AccountName  string
	Balance      float64 //账户总余额
	SettleAmount float64 //已经结算的金额
	LoanAmount   float64 //账户押款金额
	FreezeAmount float64 //账户冻结金额
	WaitAmount   float64 //待结算资金
	PayforAmount float64 //代付在途金额
	UpdateTime   time.Time
	CreateTime   time.Time
	//AbleBalance  float64 //账户可用金额
}

const ACCOUNT_INFO = "account_info"

func InsetAcount(ctx context.Context, account AccountInfo) bool {
	o := orm.NewOrm()
	_, err := o.InsertWithCtx(ctx, &account)
	if err != nil {
		logs.Error("insert account fail: ", err)
		return false
	}
	return true
}

func GetAccountByUid(ctx context.Context, accountUid string) AccountInfo {
	o := orm.NewOrm()
	var account AccountInfo
	_, err := o.QueryTable(ACCOUNT_INFO).Filter("account_uid", accountUid).Limit(1).AllWithCtx(ctx, &account)
	if err != nil {
		logs.Error("get account by uid fail: ", err)
	}

	return account
}

func GetAccountLenByMap(ctx context.Context, params map[string]string) int {
	o := orm.NewOrm()
	qs := o.QueryTable(ACCOUNT_INFO)
	for k, v := range params {
		if len(v) > 0 {
			qs = qs.Filter(k, v)
		}
	}
	cnt, err := qs.Limit(-1).OrderBy("-update_time").CountWithCtx(ctx)
	if err != nil {
		logs.Error("get account len by map fail: ", err)
	}
	return int(cnt)
}

func GetAccountByMap(ctx context.Context, params map[string]string, displayCount, offset int) []AccountInfo {
	o := orm.NewOrm()
	var accountList []AccountInfo
	qs := o.QueryTable(ACCOUNT_INFO)
	for k, v := range params {
		if len(v) > 0 {
			qs = qs.Filter(k, v)
		}
	}

	_, err := qs.Limit(displayCount, offset).OrderBy("-update_time").AllWithCtx(ctx, &accountList)
	if err != nil {
		logs.Error("get account by map fail: ", err)
	}
	return accountList
}

func GetAllAccount(ctx context.Context) []AccountInfo {
	o := orm.NewOrm()
	var accountList []AccountInfo

	_, err := o.QueryTable(ACCOUNT_INFO).Limit(-1).AllWithCtx(ctx, &accountList)

	if err != nil {
		logs.Error("get all account fail: ", err)
	}

	return accountList
}

func UpdateAccount(ctx context.Context, account AccountInfo) bool {
	o := orm.NewOrm()
	_, err := o.UpdateWithCtx(ctx, &account)
	if err != nil {
		logs.Error("update account fail: ", err)
		return false
	}
	return true
}

func DeleteAccountByUid(ctx context.Context, accountUid string) bool {
	o := orm.NewOrm()
	_, err := o.QueryTable(ACCOUNT_INFO).Filter("account_uid", accountUid).DeleteWithCtx(ctx)
	if err != nil {
		logs.Error("delete account fail: ", err)
		return false
	}
	return true
}
