package Wx

import (
	"context"
	"errors"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent"
	agentModel "wechat-api/ent/agent"
	"wechat-api/ent/wx"
	"wechat-api/hook"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

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

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

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

func (l *CheckWxLogic) CheckWx(req *types.WxInfo) (resp *types.BaseMsgResp, err error) {
	//isAdmin := l.ctx.Value("isAdmin").(bool)
	//if !isAdmin {
	//	l.Error("没有权限，请联系管理员", nil)
	//	return nil, nil
	//}

	// 获取服务器信息
	server, err := l.svcCtx.DB.Server.Get(l.ctx, *req.ServerId)
	if err != nil {
		l.Error("获取服务器信息失败", err)
		return nil, err
	}

	hook := hook.NewHook(server.PrivateIP, server.AdminPort, *req.Port)

	//  判断端口是否被占用
	portOccupied, err := hook.GetPortOccupiedInfo(*req.Port)
	if err != nil {
		l.Error("获取端口占用信息失败", err)
		return nil, err
	}

	if portOccupied.Occupied != "1" {
		l.Error("端口未使用，请重新扫码登陆", err)
		return nil, err
	}

	// 判断所选模式是否可用
	if req.AgentId != nil {
		agent, err := l.svcCtx.DB.Agent.Query().Where(agentModel.Status(1), agentModel.ID(*req.AgentId)).First(l.ctx)
		if err != nil && ent.IsNotFound(err) || agent == nil {
			return nil, errors.New("所选模式不存在或者已被禁用，请选择其他模式")
		}
	}

	loginStatus, err := hook.IsLoginStatus()
	if err != nil {
		return nil, err
	}

	if loginStatus.Onlinestatus == "3" {
		selfInfo, err := hook.GetSelfLoginInfo()
		if err != nil {
			return nil, err
		}

		wxInfo, err := l.svcCtx.DB.Wx.Query().Where(wx.ServerIDEQ(server.ID)).Where(wx.PortEQ(*req.Port)).Limit(1).Only(l.ctx)
		if err != nil && !ent.IsNotFound(err) {
			l.Error("查询微信信息失败", err)
			return nil, err
		}

		if req.Callback != nil && *req.Callback != "" {
			_ = hook.ConfigureMsgRecive("1", *req.Callback)
		}

		var dbErr error
		if ent.IsNotFound(err) {
			l.Error("账号不存在，请联系管理员", err)
			return nil, err
		} else {
			_, dbErr = l.svcCtx.DB.Wx.UpdateOneID(wxInfo.ID).
				SetNotNilProcessID(&selfInfo.ProcessID).
				SetNotNilCallback(req.Callback).
				SetNotNilWxid(&selfInfo.Wxid).
				SetNotNilAccount(&selfInfo.Account).
				SetNotNilNickname(&selfInfo.Nickname).
				SetNotNilTel(&selfInfo.Tel).
				SetNotNilHeadBig(&selfInfo.HeadBig).
				SetStatus(1).
				Save(l.ctx)

			data := map[string]interface{}{
				"nickname":         selfInfo.Nickname,
				"server_id":        wxInfo.ServerID,
				"port":             wxInfo.Port,
				"api_base":         wxInfo.APIBase,
				"api_key":          wxInfo.APIKey,
				"agent_id":         wxInfo.AgentID,
				"allow_list":       wxInfo.AllowList,
				"group_allow_list": wxInfo.GroupAllowList,
				"block_list":       wxInfo.BlockList,
				"group_block_list": wxInfo.GroupBlockList,
			}
			l.svcCtx.Rds.HSet(l.ctx, "wx_info", selfInfo.Wxid, data)
			l.svcCtx.Rds.HDel(l.ctx, "crontask_wx_server_info", selfInfo.Wxid)
		}
		if dbErr != nil {
			return nil, dberrorhandler.DefaultEntError(l.Logger, dbErr, req)
		}
	} else {
		l.Error("微信未登录", "loginStatus", loginStatus)
		return nil, errorx.NewDefaultError("微信未登陆，当前登陆状态：" + loginStatus.Onlinestatus + "，" + loginStatus.Msg)
	}

	return &types.BaseMsgResp{Msg: errormsg.Success}, nil
}
