package channel

import (
	"context"
	"encoding/json"
	"errors"
	"kami/internal/model"
	"kami/internal/systemV2/dao"
	"kami/internal/systemV2/model/entity"
	"kami/internal/systemV2/service"
	"kami/utility/lib/libErr"
	"kami/utility/utils"

	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/glog"
)

func init() {
	service.RegisterEntrance(New())
}

func New() *sEntrance {
	return &sEntrance{}
}

type sEntrance struct{}

func (s *sEntrance) Add(ctx context.Context, entrance model.EntranceInput) error {
	params, _ := json.Marshal(entrance.Params)
	err := g.Try(ctx, func(ctx context.Context) {
		_, err := dao.V2RoadInfo.Ctx(ctx).Save(entity.V2RoadInfo{
			Id:         utils.GenerateRandomUUID(),
			Name:       entrance.Name,
			PayType:    entrance.PayType,
			ServiceFee: entrance.ServiceFee,
			TotalLimit: entrance.TotalLimit,
			AllowedMm:  entrance.AllowedMm,
			StartHour:  entrance.StartHour,
			EndHour:    entrance.EndHour,
			Params:     string(params),
			Remark:     entrance.Remark,
			Status:     int(entrance.Status),
		})
		libErr.ErrIsNil(ctx, err, "添加通道失败")
	})
	return err
}

func (s *sEntrance) Update(ctx context.Context, entrance model.EntranceInputWithID) error {
	params, _ := json.Marshal(entrance.Params)
	err := g.Try(ctx, func(ctx context.Context) {
		_, err := dao.V2RoadInfo.Ctx(ctx).Update(entity.V2RoadInfo{
			Id:         entrance.ID,
			Name:       entrance.Name,
			PayType:    entrance.PayType,
			ServiceFee: entrance.ServiceFee,
			TotalLimit: entrance.TotalLimit,
			AllowedMm:  entrance.AllowedMm,
			StartHour:  entrance.StartHour,
			EndHour:    entrance.EndHour,
			Params:     string(params),
			Remark:     entrance.Remark,
			Status:     int(entrance.Status),
		})
		libErr.ErrIsNil(ctx, err, "更新通道失败")
	})
	return err
}

func (s *sEntrance) Delete(ctx context.Context, ID string) error {
	if ID == "" {
		return gerror.New("ID不能为空")
	}
	err := g.Try(ctx, func(ctx context.Context) {
		_, err := dao.V2RoadInfo.Ctx(ctx).WherePri(ID).Delete()
		libErr.ErrIsNil(ctx, err, "更新通道失败")
	})
	return err
}

func (s *sEntrance) List(ctx context.Context, req model.EntranceParamsInput) (total int, data []entity.V2RoadInfo, err error) {
	m := dao.V2RoadInfo.Ctx(ctx)
	total, err2 := m.Count()
	if err2 != nil {
		glog.Errorf(ctx, "获取通道列表失败:%s", err2.Error())
		err = errors.New("获取通道列表失败")
	}
	err2 = m.Page(req.Current, req.PageSize).Scan(&data)
	if err2 != nil {
		total = 0
		glog.Errorf(ctx, "获取通道列表失败:%s", err2.Error())
		err = errors.New("获取通道列表失败")
	}
	return
}
