package card_info_apple

import (
	"context"
	"github.com/duke-git/lancet/v2/slice"
	"kami/api/card_info_apple/v1"
	"kami/internal/errHandler"
	"kami/internal/model"
	"kami/internal/service"

	"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"
)

func (c *ControllerV1) CardInfoBatchAddFromXlsx(ctx context.Context, req *v1.CardInfoBatchAddFromXlsxReq) (res *v1.CardInfoBatchAddFromXlsxRes, err error) {
	userInfo, err := service.SysAuth().LoginWithIFrameAndLogin(ctx)
	if err != nil {
		err = errHandler.WrapError(ctx, gcode.CodeNotAuthorized, err, "权限不足")
		return
	}
	accountService := service.AppleAccount()
	accountEntities, _ := accountService.GetAll(ctx)
	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
	}
	succeedItem := 0
	failedItem := 0
	existsItem := 0
	rows, err := xlsx.GetRows(xlsx.GetSheetList()[0])
	if len(rows) <= 1 {
		res = &v1.CardInfoBatchAddFromXlsxRes{
			Msg: "文件中没有数据",
		}
		return
	}
	uniqueRows := slice.UniqueBy(rows, func(item []string) string {
		if len(item) <= 2 {
			return ""
		}
		return gstr.Trim(item[0])
	})
	if len(uniqueRows) != len(rows) {
		res = &v1.CardInfoBatchAddFromXlsxRes{
			Msg: "文件中有重复账号",
		}
		return
	}
	for _, row := range rows {

		if len(row) <= 2 {
			continue
		}

		accountName := gstr.Trim(row[0])
		accountPass := gstr.Trim(row[1])

		if accountName == "账号" || accountName == "" {
			continue
		}

		maxAmountLimit := 0
		if len(row) >= 3 {
			maxAmountLimit = gconv.Int(row[2])
		}
		maxCountLimit := 0
		if len(row) >= 4 {
			maxCountLimit = gconv.Int(row[3])
		}

		isDuplicate := false
		for _, accountEntity := range accountEntities {
			if accountEntity.Account == accountName {
				isDuplicate = true
			}
		}
		isRepeated, _ := accountService.IsUnscopedTodayRepeatedByName(ctx, row[0])
		if !isDuplicate || isRepeated {
			err = accountService.Add(ctx, &model.AppleAccountRecordInput{
				AppleAccountRecord: v1.AppleAccountRecord{
					Account:        accountName,
					Password:       accountPass,
					MaxCountLimit:  maxCountLimit,
					MaxAmountLimit: maxAmountLimit,
				},
				UploadUserId: userInfo.Id,
			}, nil)
			if err != nil {
				failedItem++
			} else {
				succeedItem++
			}
		} else {
			existsItem++
		}
	}
	msg := "导入结果"
	if failedItem == 0 {
		msg += "全部导入成功"
	} else {
		msg += "导入成功" + string(rune(succeedItem)) + "个，导入失败" + string(rune(failedItem)) + "个，已存在" + string(rune(existsItem)) + "个"
	}
	res = &v1.CardInfoBatchAddFromXlsxRes{
		Msg: msg,
	}
	return
}
