package WorkPhone

import (
	"context"
	"fmt"
	"github.com/imroc/req/v3"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"strconv"
	"time"
	"wechat-api/ent"
	"wechat-api/ent/wx"
	"wechat-api/internal/utils/dberrorhandler"

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

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

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

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

func (l *WxRefreshLogic) WxRefresh() (resp *types.BaseMsgResp, err error) {
	var result types.WorkPhoneGetWeChatsResp
	client := req.C().DevMode()
	client.SetCommonRetryCount(2).
		SetCommonRetryBackoffInterval(1*time.Second, 5*time.Second).
		SetCommonRetryFixedInterval(2 * time.Second).SetTimeout(30 * time.Second)
	res, err := client.R().SetSuccessResult(&result).Post("http://chat.gkscrm.com:13086/pc/GetWeChatsReq?id=13")

	if err != nil {
		return
	}
	if !res.IsSuccessState() {
		err = fmt.Errorf("GetWeChats failed with status code %d", res.StatusCode)
		return
	}

	for _, account := range result.Data {
		if account.Wechatid == "" {
			continue
		}
		wxinfo, err := l.svcCtx.DB.Wx.Query().
			Where(
				wx.Or(
					wx.WxidEQ(account.Wechatid),
					wx.PortEQ(account.Deviceid),
				),
			).
			Only(l.ctx)

		if err != nil && !ent.IsNotFound(err) {
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, account)
		}
		var status uint8
		if account.Isonline == 0 {
			status = 1
		} else {
			status = 0
		}
		if wxinfo != nil {
			err = l.svcCtx.DB.Wx.UpdateOneID(wxinfo.ID).
				SetServerID(0).
				SetPort(account.Deviceid).
				SetProcessID(strconv.FormatInt(account.Cid, 10)).
				SetAccount(account.Wechatno).
				SetNickname(account.Wechatnick).
				SetHeadBig(account.Avatar).
				SetStatus(status).
				Exec(l.ctx)

			if err != nil {
				return nil, dberrorhandler.DefaultEntError(l.Logger, err, account)
			}
		} else {
			l.Debug("wxinfo is nil")
			_, err := l.svcCtx.DB.Wx.Create().
				SetServerID(0).
				SetPort(account.Deviceid).
				SetProcessID(strconv.FormatInt(account.Cid, 10)).
				SetWxid(account.Wechatid).
				SetAccount(account.Wechatno).
				SetHeadBig(account.Avatar).
				SetNickname(account.Wechatnick).
				SetStatus(status).
				SetAllowList([]string{}).SetBlockList([]string{}).SetGroupAllowList([]string{}).SetGroupBlockList([]string{}).
				Save(l.ctx)
			l.Error("wxinfo save", err)
			if err != nil {
				return nil, dberrorhandler.DefaultEntError(l.Logger, err, account)
			}
		}
	}

	l.svcCtx.Rds.Del(l.ctx, "crontask_wx_server_info")

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

	return
}
