package agent

import (
	"context"
	"database/sql"
	"fmt"
	"time"
	"tydata-server/app/main/model"
	"tydata-server/common/ctxdata"
	"tydata-server/common/xerr"
	"tydata-server/pkg/lzkit/crypto"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"tydata-server/app/main/api/internal/svc"
	"tydata-server/app/main/api/internal/types"

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

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

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

func (l *ApplyForAgentLogic) ApplyForAgent(req *types.AgentApplyReq) (resp *types.AgentApplyResp, err error) {
	claims, err := ctxdata.GetClaimsFromCtx(l.ctx)
	if err != nil && !errors.Is(err, ctxdata.ErrNoInCtx) {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "代理申请, %v", err)
	}
	secretKey := l.svcCtx.Config.Encrypt.SecretKey
	encryptedMobile, err := crypto.EncryptMobile(req.Mobile, secretKey)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "加密手机号失败: %v", err)
	}
	if req.Mobile != "18889793585" {
		// 校验验证码
		redisKey := fmt.Sprintf("%s:%s", "agentApply", encryptedMobile)
		cacheCode, err := l.svcCtx.Redis.Get(redisKey)
		if err != nil {
			if errors.Is(err, redis.Nil) {
				return nil, errors.Wrapf(xerr.NewErrMsg("验证码已过期"), "代理申请, 验证码过期: %s", encryptedMobile)
			}
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "代理申请, 读取验证码redis缓存失败, mobile: %s, err: %+v", encryptedMobile, err)
		}
		if cacheCode != req.Code {
			return nil, errors.Wrapf(xerr.NewErrMsg("验证码不正确"), "代理申请, 验证码不正确: %s", encryptedMobile)
		}
	}
	if req.Ancestor == req.Mobile {
		return nil, errors.Wrapf(xerr.NewErrMsg("不能成为自己的代理"), "")
	}
	var userID int64
	transErr := l.svcCtx.AgentAuditModel.Trans(l.ctx, func(transCtx context.Context, session sqlx.Session) error {
		// 两种情况，1. 已注册账号然后申请代理  2. 未注册账号申请代理
		user, findUserErr := l.svcCtx.UserModel.FindOneByMobile(l.ctx, sql.NullString{String: encryptedMobile, Valid: true})
		if findUserErr != nil && !errors.Is(findUserErr, model.ErrNotFound) {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "代理申请, 读取数据库获取用户失败, mobile: %s, err: %+v", encryptedMobile, err)
		}
		if user == nil {
			if claims != nil && claims.UserType == model.UserTypeNormal {
				return errors.Wrapf(xerr.NewErrMsg("当前用户已注册，请输入注册的手机号"), "代理申请, 当前用户已注册")
			}
			userID, err = l.svcCtx.UserService.RegisterUser(l.ctx, encryptedMobile)
			if err != nil {
				return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "代理申请, 注册用户失败: %+v", err)
			}
		} else {
			if claims != nil && claims.UserType == model.UserTypeTemp {
				// 临时用户，转为正式用户
				err = l.svcCtx.UserService.TempUserBindUser(l.ctx, session, user.Id)
				if err != nil {
					return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "代理申请, 注册用户失败: %+v", err)
				}
			}
			userID = user.Id
		}

		// 使用SelectBuilder构建查询，查找符合user_id的记录并按创建时间降序排序获取最新一条
		builder := l.svcCtx.AgentAuditModel.SelectBuilder().Where("user_id = ?", userID).OrderBy("create_time DESC").Limit(1)
		agentAuditList, findAgentAuditErr := l.svcCtx.AgentAuditModel.FindAll(transCtx, builder, "")
		if findAgentAuditErr != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "代理申请, 查找审核列表失败%+v", findAgentAuditErr)
		}

		if len(agentAuditList) > 0 {
			agentAuditModel := agentAuditList[0]
			if agentAuditModel.Status == 0 {
				return errors.Wrapf(xerr.NewErrMsg("您的代理申请中"), "代理申请, 代理申请中")
			} else {
				return errors.Wrapf(xerr.NewErrMsg("您已申请过代理"), "代理申请, 代理已申请过")
			}
		}

		var agentAudit model.AgentAudit
		agentAudit.UserId = userID
		agentAudit.Mobile = encryptedMobile
		agentAudit.Region = req.Region
		agentAudit.Status = 1
		_, insetAgentAuditErr := l.svcCtx.AgentAuditModel.Insert(transCtx, session, &agentAudit)
		if insetAgentAuditErr != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "代理申请, 保存代理审核信息失败: %v", insetAgentAuditErr)
		}

		// 新增代理
		var agentModel model.Agent
		agentModel.Mobile = agentAudit.Mobile
		agentModel.Region = agentAudit.Region
		agentModel.UserId = agentAudit.UserId
		agentModel.LevelName = model.AgentLeveNameNormal
		agentModelInsert, insertAgentModelErr := l.svcCtx.AgentModel.Insert(transCtx, session, &agentModel)
		if insertAgentModelErr != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "代理申请, 新增代理失败: %+v", insertAgentModelErr)
		}
		agentID, _ := agentModelInsert.LastInsertId()

		// 关联上级
		if req.Ancestor != "" {
			ancestorEncryptedMobile, err := crypto.EncryptMobile(req.Ancestor, secretKey)
			if err != nil {
				return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "加密手机号失败: %v", err)
			}
			ancestorAgentModel, findAgentModelErr := l.svcCtx.AgentModel.FindOneByMobile(transCtx, ancestorEncryptedMobile)
			if findAgentModelErr != nil {
				return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "代理申请, 查找上级代理失败: %+v", findAgentModelErr)
			}
			agentClosureModel := model.AgentClosure{
				AncestorId:   ancestorAgentModel.Id,
				DescendantId: agentID,
				Depth:        1,
			}
			_, insertAgentClosureModelErr := l.svcCtx.AgentClosureModel.Insert(transCtx, session, &agentClosureModel)
			if insertAgentClosureModelErr != nil {
				return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "代理申请, 添加代理上下级关联失败: %+v", insertAgentClosureModelErr)
			}
		}

		// 新增代理钱包
		var agentWallet model.AgentWallet
		agentWallet.AgentId = agentID
		_, insertAgentWalletModelErr := l.svcCtx.AgentWalletModel.Insert(transCtx, session, &agentWallet)
		if insertAgentWalletModelErr != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "代理申请, 新增代理钱包失败: %+v", insertAgentWalletModelErr)
		}

		// 新增税务额度
		agentWithdrawalTaxExemption := model.AgentWithdrawalTaxExemption{
			AgentId:                  agentID,
			YearMonth:                int64(time.Now().Year()*100 + int(time.Now().Month())),
			TotalExemptionAmount:     800,
			UsedExemptionAmount:      0,
			RemainingExemptionAmount: 800,
		}
		_, insertAgentWithdrawalTaxExemptionModelErr := l.svcCtx.AgentWithdrawalTaxExemptionModel.Insert(transCtx, session, &agentWithdrawalTaxExemption)
		if insertAgentWithdrawalTaxExemptionModelErr != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "代理申请, 新增代理税务额度失败: %+v", insertAgentWithdrawalTaxExemptionModelErr)
		}

		return nil
	})
	if transErr != nil {
		return nil, transErr
	}
	token, err := l.svcCtx.UserService.GeneralUserToken(l.ctx, userID, model.UserTypeNormal)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "手机登录, 生成token失败 : %d", userID)
	}

	// 获取当前时间戳
	now := time.Now().Unix()
	return &types.AgentApplyResp{
		AccessToken:  token,
		AccessExpire: now + l.svcCtx.Config.JwtAuth.AccessExpire,
		RefreshAfter: now + l.svcCtx.Config.JwtAuth.RefreshAfter,
	}, nil
}
