package card_info_original_jd

import (
	"context"
	"kami/internal/consts"
	"kami/internal/errHandler"
	"kami/internal/service"
	redeemModel "kami/utility/integration/redeem"
	redeem "kami/utility/integration/redeem/client"

	"github.com/duke-git/lancet/v2/pointer"
	"github.com/duke-git/lancet/v2/slice"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/util/gconv"
	"github.com/xuri/excelize/v2"

	"github.com/gogf/gf/v2/errors/gcode"

	"kami/api/card_info_original_jd/v1"
)

func (c *ControllerV1) OriginalJDAccountCookieBatchCheck(ctx context.Context, req *v1.OriginalJDAccountCookieBatchCheckReq) (res *v1.OriginalJDAccountCookieBatchCheckRes, err error) {
	_, err = service.SysAuth().LoginOnlyIFrame(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}
	res = &v1.OriginalJDAccountCookieBatchCheckRes{}
	_, 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.OriginalJDAccountCookieBatchCheckRes{
			Msg: "文件中没有数据",
		}
		return
	}
	cks := make([]*v1.OriginalJDAccountCookieBatchInfo, 0)
	slice.ForEachConcurrent(rows, func(index int, item []string) {
		if len(item) < 3 || index == 0 {
			return
		}
		name := item[0]
		ck := item[1]
		amountLimit := item[2]
		countLimit := item[3]
		data := &v1.OriginalJDAccountCookieBatchInfo{
			Name:           name,
			Cookie:         ck,
			MaxAmountLimit: gconv.Int(amountLimit),
			MaxCountLimit:  gconv.Int(countLimit),
		}
		client, err2 := redeem.GetClient(consts.CardRedeemAccountCategoryOriginalJD)
		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
			existJdUserInfo, _ := service.CardRedeemAccount().GetNormalOneByUsername(ctx, data.Username, consts.CardRedeemAccountCategoryOriginalJD)
			if !pointer.IsNil(existJdUserInfo) && existJdUserInfo.Id != "" {
				data.IsExist = true
			}
		}
		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
}
