package service

import (
	"context"
	"fmt"
	log "github.com/sirupsen/logrus"
	"youngee_b_api/db"
	"youngee_b_api/model/http_model"
)

var BUserInfo *bUserInfo

type bUserInfo struct {
}

// FindBUserInfoByToken 根据Token查询商家端用户信息
func (*bUserInfo) FindBUserInfoByToken(ctx context.Context, token string) (*http_model.GetUserInfoData, error) {
	if token != "" {
		if auth, err := LoginAuth.AuthToken(ctx, token); err == nil {
			var userInfo *http_model.GetUserInfoData
			userInfo = &http_model.GetUserInfoData{
				EnterpriseId: auth.EnterpriseID,
				UserId:       auth.ID,
				Role:         auth.Role,
			}
			if auth.Role == "3" {
				fmt.Println("EnterpriseUser")
				userInfo.JobName = "主账号无岗位名称"
				userInfo.CooperatePermission = "1"
				userInfo.WorkshopPermission = "1"
				userInfo.FinancialPermission = "1"
				userInfo.TaskcenterPermission = "1"
			} else if auth.Role == "4" {
				subaccountInfo, subaccountErr := db.FindSubAccountByPhone(ctx, auth.Phone)
				if subaccountErr != nil {
					return nil, subaccountErr
				}
				userInfo.SubAccountId = subaccountInfo.SubAccountId
				jobInfo, jonErr := db.FindJobByJobId(ctx, subaccountInfo.JobId)
				if jonErr != nil {
					return nil, jonErr
				}
				userInfo.JobName = jobInfo.JobName
				userInfo.CooperatePermission = jobInfo.CooperatePermission
				userInfo.WorkshopPermission = jobInfo.WorkshopPermission
				userInfo.FinancialPermission = jobInfo.FinancialPermission
				userInfo.TaskcenterPermission = jobInfo.TaskcenterPermission
			}
			return userInfo, nil
		} else {
			log.Infof("[LoginAuthMiddleware] auth fail,err:%+v", err)
			return nil, err
		}
	}
	return nil, nil
}
