package admin_menu

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

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

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

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

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

func (l *UpdateMenuLogic) UpdateMenu(req *types.UpdateMenuReq) (resp *types.UpdateMenuResp, err error) {
	// 1. 检查菜单是否存在
	menu, err := l.svcCtx.AdminMenuModel.FindOne(l.ctx, req.Id)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询菜单失败, id: %d, err: %v", req.Id, err)
	}
	if menu == nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "菜单不存在, id: %d", req.Id)
	}

	// 2. 将类型标签转换为值
	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)
	}

	// 3. 检查父菜单是否存在（如果不是根菜单）
	if req.Pid != nil && *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: %s, err: %v", *req.Pid, err)
		}
		if parentMenu == nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "父菜单不存在, id: %s", *req.Pid)
		}
	}

	// 4. 检查名称和路径是否重复
	if req.Name != menu.Name || req.Path != menu.Path {
		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 && exists.Id != req.Id {
			return nil, errors.Wrapf(xerr.NewErrMsg("菜单名称或路径已存在"), "菜单名称或路径已存在")
		}
	}

	// 5. 更新菜单信息

	menu.Pid = sql.NullString{String: *req.Pid, Valid: req.Pid != nil}
	menu.Name = req.Name
	menu.Path = req.Path
	menu.Component = req.Component
	menu.Redirect = sql.NullString{String: req.Redirect, Valid: req.Redirect != ""}
	menu.Status = req.Status
	menu.Type = typeValue
	menu.Sort = req.Sort

	// 将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.Update(l.ctx, nil, menu)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "更新菜单失败, err: %v", err)
	}

	return &types.UpdateMenuResp{
		Success: true,
	}, nil
}
