package user

import (
	"context"
	"git.i2edu.net/i2/i2-bill-api/model"

	"git.i2edu.net/i2/i2-bill-api/internal/svc"
	"git.i2edu.net/i2/i2-bill-api/internal/types"

	"git.i2edu.net/i2/go-zero/core/logx"
)

type BindMobileLogic struct {
	logx.Logger
	ctx        context.Context
	svcCtx     *svc.ServiceContext
	UserId     int64
	SessionKey string
}

func NewBindMobileLogic(ctx context.Context, svcCtx *svc.ServiceContext) BindMobileLogic {
	return BindMobileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *BindMobileLogic) BindMobile(req types.BindMobileRequest) (*types.Response, error) {
	mobile, err := l.svcCtx.Wechat.DecryptMobile(l.SessionKey, req.EncryptedData, req.Iv)
	if err != nil {
		logx.Error(err)
		return nil, err
	}
	_, err = l.svcCtx.SqlConn.Exec(`update i2bill_user set mobile = ? where id = ?`, mobile, l.UserId)
	tx := l.svcCtx.DB.NewSession()
	tx.Begin()
	_, err = tx.Exec("update i2bill_user set mobile = ? where id = ?", mobile, l.UserId)
	if err != nil {
		tx.Rollback()
		logx.Error(err)
		return nil, err
	}
	//_, err = tx.Exec("update i2bill_mkt_part_time_user set ipone_number = ? where user_id = ?", mobile, l.UserId)
	//if err != nil {
	//	tx.Rollback()
	//	logx.Error(err)
	//	return nil, err
	//}

	//关联兼职
	partUser, err := model.GetPartTimeXormByUserId(l.UserId, l.svcCtx.DB)
	if err != nil {
		tx.Rollback()
		logx.Error(err)
		return nil, err
	}
	if mobile != "" && (partUser == nil || partUser.UserId == 0) {
		partTime := new(model.I2billMktPartTimeXorm)
		_, err = l.svcCtx.DB.Where("ipone_number = ? and del_flag = 0 and user_id = 0", mobile).Get(partTime)
		if err != nil {
			tx.Rollback()
			logx.Error(err)
			return nil, err
		}
		partTime.UserId = l.UserId
		if partTime.Id != 0 {
			_, err := tx.ID(partTime.Id).Update(partTime)
			if err != nil {
				tx.Rollback()
				logx.Error(err)
				return nil, err
			}
		}
	}
	tx.Commit()
	resp := make(map[string]interface{})
	resp["id"] = l.UserId
	resp["mobile"] = mobile
	return &types.Response{
		200, "", resp,
	}, nil
}
