package card_info_walmart

import (
	"context"
	"fmt"
	"kami/internal/consts"
	"kami/internal/errHandler"
	"kami/internal/service"

	"github.com/duke-git/lancet/v2/pointer"
	"github.com/duke-git/lancet/v2/slice"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/xuri/excelize/v2"

	"kami/api/card_info_walmart/v1"
)

func (c *ControllerV1) AccountCookieBatchCheck(ctx context.Context, req *v1.AccountCookieBatchCheckReq) (res *v1.AccountCookieBatchCheckRes, err error) {
	res = &v1.AccountCookieBatchCheckRes{}
	_, err = service.SysAuth().LoginOnlyLogin(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}
	f, err := req.File.Open()
	if err != nil {
		err = errHandler.WrapError(ctx, errHandler.ErrFileBroken, err, "")
		return
	}
	xlsx, err := excelize.OpenReader(f)
	if err != nil {
		err = errHandler.WrapError(ctx, errHandler.ErrFileBroken, err, "")
		return
	}
	if len(xlsx.GetSheetList()) == 0 {
		err = errHandler.WrapError(ctx, errHandler.ErrFileBroken, err, "")
		return
	}
	rows, err := xlsx.GetRows(xlsx.GetSheetList()[0])
	if len(rows) <= 1 {
		res = &v1.AccountCookieBatchCheckRes{
			Msg: "文件中没有数据",
		}
		return
	}
	cks := make([]*v1.AccountCookieBatchInfo, 0)
	slice.ForEachConcurrent(rows, func(index int, item []string) {
		if len(item) < 3 || index == 0 {
			return
		}
		name := gstr.TrimAll(item[0])
		ck := gstr.TrimAll(gstr.TrimAll(item[1]))
		amountLimit := gstr.TrimAll(item[2])
		countLimit := gstr.TrimAll(item[3])

		maxLimit := service.SysConfigDict().GetMaxAccountRedeemCount(ctx, consts.CardRedeemAccountCategoryWalMart)
		if gconv.Int(countLimit) > maxLimit {
			err = errHandler.WrapError(ctx, gcode.CodeInvalidOperation, err, fmt.Sprintf("上传卡密超过管理员设置限制，管理员设置最大次数：%d", maxLimit))
			return
		}
		data := &v1.AccountCookieBatchInfo{
			Name:           name,
			Cookie:         ck,
			MaxAmountLimit: gconv.Int(amountLimit),
			MaxCountLimit:  gconv.Int(countLimit),
			AccountCookieCheckRes: v1.AccountCookieCheckRes{
				IsAvailable: true,
			},
		}
		existWalmartUserInfo, _ := service.CardRedeemAccount().GetNormalOneByCk(ctx, consts.CardRedeemAccountCategoryWalMart, ck)
		if !pointer.IsNil(existWalmartUserInfo) && existWalmartUserInfo.Id != "" {
			data.IsExist = true
		}
		//client, err2 := redeem.GetClient(consts.CardRedeemAccountCategoryWalMart)
		//if err2 != nil {
		//	glog.Error(ctx, "获取客户端失败", err2)
		//	return
		//}
		//
		//result, err2 := client.QueryUserInfoWithCache(ctx, ck, gtime.M*10)
		//if err2 == nil {
		//	data.Username = result.Username
		//	data.Nickname = result.NickName
		//	data.IsAvailable = result.Ok

		//}
		//balance, err2 := client.QueryBalanceWithCache(ctx, &redeemModel.QueryBalanceReq{
		//	Cookie: ck,
		//}, gtime.M*10)
		//if err2 == nil {
		//	data.Balance = balance.Money
		//}
		cks = append(cks, data)
	}, 10)
	res.List = cks
	return
}
