package admin_menu

import (
	"context"
	"database/sql"
	"encoding/json"
	"time"

	"hm-server/app/main/api/internal/svc"
	"hm-server/app/main/api/internal/types"
	"hm-server/app/main/model"
	"hm-server/common/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreateMenuLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateMenuLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateMenuLogic {
	return &CreateMenuLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateMenuLogic) CreateMenu(req *types.CreateMenuReq) (resp *types.CreateMenuResp, err error) {
	// 1. 参数验证
	if req.Name == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("菜单名称不能为空"), "菜单名称不能为空")
	}
	if req.Type == "menu" && req.Component == "" {
		return nil, errors.Wrapf(xerr.NewErrMsg("组件路径不能为空"), "组件路径不能为空")
	}

	// 2. 检查名称和路径是否重复
	exists, err := l.svcCtx.AdminMenuModel.FindOneByNamePath(l.ctx, req.Name, req.Path)
	if err != nil && !errors.Is(err, model.ErrNotFound) {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询菜单失败, err: %v", err)
	}
	if exists != nil {
		return nil, errors.Wrapf(xerr.NewErrMsg("菜单名称或路径已存在"), "菜单名称或路径已存在")
	}

	// 3. 检查父菜单是否存在（如果不是根菜单）
	if req.Pid > 0 {
		parentMenu, err := l.svcCtx.AdminMenuModel.FindOne(l.ctx, req.Pid)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询父菜单失败, id: %d, err: %v", req.Pid, err)
		}
		if parentMenu == nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "父菜单不存在, id: %d", req.Pid)
		}
	}

	// 4. 将类型标签转换为值
	typeValue, err := l.svcCtx.DictService.GetDictValue(l.ctx, "admin_menu_type", req.Type)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "菜单类型无效: %v", err)
	}

	// 5. 创建菜单记录
	menu := &model.AdminMenu{
		Pid:        req.Pid,
		Name:       req.Name,
		Path:       req.Path,
		Component:  req.Component,
		Redirect:   sql.NullString{String: req.Redirect, Valid: req.Redirect != ""},
		Status:     req.Status,
		Type:       typeValue,
		Sort:       req.Sort,
		CreateTime: time.Now(),
		UpdateTime: time.Now(),
	}

	// 将Meta转换为JSON字符串
	metaJson, err := json.Marshal(req.Meta)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "Meta数据格式错误: %v", err)
	}
	menu.Meta = string(metaJson)

	// 6. 保存到数据库
	_, err = l.svcCtx.AdminMenuModel.Insert(l.ctx, nil, menu)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建菜单失败, err: %v", err)
	}

	return &types.CreateMenuResp{
		Id: menu.Id,
	}, nil
}
