package user

import (
	"context"
	"fmt"
	"git.i2edu.net/i2/i2-bill-api/internal/svc"
	"git.i2edu.net/i2/i2-bill-api/internal/types"
	"git.i2edu.net/i2/i2-bill-api/internal/utils"
	"git.i2edu.net/i2/i2-bill-api/model"
	"git.i2edu.net/i2/i2-bill-erp/transform"
	"strings"

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

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

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

func (l *GetUserLogic) GetUser() (*types.InfoResponse, error) {
	var user model.User
	info := &types.InfoResponse{}
	err := l.svcCtx.SqlConn.QueryRowPartial(&user, "select id, erp_id, avatar, birthday, username, nickname, gender, mobile from i2bill_user where `id` = ? limit 1", l.UserId)
	if err != nil {
		logx.Error(err)
		return nil, err
	}
	// 每次都去查找, 暂时没有绑定 erp mk
	// resp, err := l.svcCtx.Transformer.GetUser(l.ctx, &transform.UserRequest{Id: user.ErpId, Phone: user.Mobile})
	resp, err := l.svcCtx.Transformer.GetUser(l.ctx, &transform.UserRequest{Phone: user.Mobile})
	if err != nil {
		logx.Error(err)
		return nil, err
	}
	if resp.ErpRoleType != 1 {
		//是不是 兼职
		res, err := l.svcCtx.DB.SQL("select * from i2bill_mkt_part_time_user where del_flag = 0 and user_id = ? and check_state = ?", l.UserId, 57).Query().List()
		if err != nil {
			logx.Error(err)
			return nil, err
		}
		if len(res) > 0 {
			//兼职信息
			resp.UserName, _ = res[0]["name"].(string)
			cityId, _ := res[0]["city_id"].(int64)
			cityNodes, err := l.svcCtx.GetErpCity(l.ctx)
			if err != nil {
				logx.Error(err)
				return nil, err
			}
			var idPath, namePath string
			if utils.TreePath(cityNodes, cityId, &idPath, &namePath) {
				cityNames := strings.Split(namePath, ",")
				if len(cityNames) > 0 {
					resp.CityName = cityNames[len(cityNames)-1]
				}
			}
			for _, node := range cityNodes {
				if node.Id == cityId {
					resp.CityName = node.Text
					break
				}
			}
			resp.Gender = res[0]["sex"].(int64)
			resp.ErpRoleType = 2
		} else {
			resp.ErpRoleType = 0
		}
	} else {
		user.ErpId = resp.Id
		l.svcCtx.DB.Table("i2bill_user").Where("id = ?", user.Id).Cols("erp_id").Update(map[string]interface{}{"erp_id": user.ErpId})
	}
	if !strings.HasPrefix(user.Avatar, "http") && user.Avatar != "" {
		domain := strings.TrimRight(l.svcCtx.Config.AliYunOss.FileUrl, "/")
		filePath := strings.TrimLeft(user.Avatar, "/")
		user.Avatar = fmt.Sprintf("%s/%s", domain, filePath)
	}
	info.ID = user.Id
	info.Avatar = user.Avatar
	info.Birthday = user.Birthday
	info.NickName = user.Nickname
	info.Mobile = user.Mobile
	info.UserName = resp.UserName
	info.Gender = resp.Gender
	info.CityName = resp.CityName
	info.ErpRoleType = resp.ErpRoleType
	return info, nil
}
