package system

import (
	"context"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
)

type BankCardInfo struct {
	Id              int
	Uid             string
	UserName        string
	BankName        string
	BankCode        string
	BankAccountType string
	AccountName     string
	BankNo          string
	IdentifyCard    string
	CertificateNo   string
	PhoneNo         string
	BankAddress     string
	UpdateTime      time.Time
	CreateTime      time.Time
}

const BANK_CARD_INFO = "bank_card_info"

func InsertBankCardInfo(ctx context.Context, bankCardInfo BankCardInfo) bool {
	o := orm.NewOrm()
	_, err := o.InsertWithCtx(ctx, &bankCardInfo)

	if err != nil {
		logs.Error("insert bank card info fail: ", err)
		return false
	}
	return true
}

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

func GetBankCardByMap(ctx context.Context, params map[string]string, displayCount, offset int) []BankCardInfo {
	o := orm.NewOrm()
	var bankCardList []BankCardInfo
	qs := o.QueryTable(BANK_CARD_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, &bankCardList)
	if err != nil {
		logs.Error("get bank card by map fail: ", err)
	}
	return bankCardList
}

func GetBankCardByUid(ctx context.Context, uid string) BankCardInfo {
	o := orm.NewOrm()
	var bankCardInfo BankCardInfo
	_, err := o.QueryTable(bankCardInfo).Filter("uid", uid).Limit(1).AllWithCtx(ctx, &bankCardInfo)
	if err != nil {
		logs.Error("get bank card by uid fail: ", err)
	}

	return bankCardInfo
}

func DeleteBankCardByUid(ctx context.Context, uid string) bool {
	o := orm.NewOrm()
	_, err := o.QueryTable(BANK_CARD_INFO).Filter("uid", uid).DeleteWithCtx(ctx)

	if err != nil {
		logs.Error("delete bank card by uid fail: ", err)
		return false
	}
	return true
}

func UpdateBankCard(ctx context.Context, bankCard BankCardInfo) bool {
	o := orm.NewOrm()
	_, err := o.UpdateWithCtx(ctx, &bankCard)
	if err != nil {
		logs.Error("update bank card fail: ", err)
		return false
	}
	return true
}
