package dao

import (
	"context"
	_ "dubbo.apache.org/dubbo-go/v3/imports"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/alibaba/sentinel-golang/logging"
	"github.com/fonchain/fonchain-artistinfo/cmd/model"
	"github.com/fonchain/fonchain-artistinfo/pb/account"
	"github.com/fonchain/fonchain-artistinfo/pb/artist"
	"github.com/fonchain/fonchain-artistinfo/pb/artistInfoUser"
	db "github.com/fonchain/fonchain-artistinfo/pkg/db"
	"github.com/fonchain/fonchain-artistinfo/pkg/m"
	"github.com/fonchain/fonchain-artistinfo/pkg/service"
	"github.com/fonchain/fonchain-artistinfo/pkg/util/stime"
	"go.uber.org/zap"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
	"time"
)

func RegisterUser(req *artistInfoUser.RegisterUserRequest) (rep *artistInfoUser.RegisterUserRespond, err error) {

	var user = model.User{
		MgmtAccId:     req.MgmtAccId,
		TelNum:        req.TelNum,
		MgmtArtistId:  req.MgmtArtistId,
		MgmtArtistUid: req.MgmtArtistUid,
		InviteCode:    req.UserInviteCode,
		Account:       req.Account,
	}
	if err = db.DB.Create(&user).Error; err != nil {
		zap.L().Error("register user err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return nil, err
	}
	return
}

func CreateUserInfo(req *artistInfoUser.CreateUserInfoRequest) (rep *artistInfoUser.CreateUserInfoRespond, err error) {
	var user model.User
	//找到用户
	fmt.Println("req.Id:", req.Id)
	fmt.Println("第三处")
	err = db.DB.Where("id = ?", req.Id).First(&user).Error
	if err != nil {
		fmt.Println("第四处")
		fmt.Println(err.Error())
		zap.L().Error("CreateUserInfo err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return nil, err
	}
	fmt.Println(11)
	var realNameFind model.RealName
	err = db.DB.Where("id_num = ?", req.IdCard).First(&realNameFind).Error
	if err == nil {
		fmt.Println("第五处")
		fmt.Println(12)
		if realNameFind.ID != 0 {
			fmt.Println("第六处")
			zap.L().Error("register user err", zap.Error(err))
			err = errors.New("此身份证已实名认证")
			return nil, err
		}
	}
	fmt.Println("第四处")
	fmt.Println(12)
	var realname = model.RealName{
		Name:        req.RealName,
		IdNum:       req.IdCard,
		TelNum:      req.TelNum,
		IdCardFront: req.IdCardFront,
		IdCardBack:  req.IdCardBack,
	}
	err = db.DB.Save(&realname).Error
	if err != nil {
		fmt.Println("第九处")
		zap.L().Error("CreateUserInfo err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return nil, err
	}

	fmt.Println(13)
	err = db.DB.Where("id_num=?", realname.IdNum).First(&realname).Error
	if err != nil {
		zap.L().Error("CreateUserInfo err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return nil, err
	}

	fmt.Println(14)
	user.ID = req.Id
	// todo 下面部分信息需要转存至画家服务和账号服务
	//user.Name = req.RealName
	//user.PenName = req.PenName
	//user.RealNameID = int32(realname.ID)
	//user.StageName = req.StageName
	//user.Age = int32(utils.IdCardTurnAge(realname.IDNum))
	//user.Sex = req.Sex
	//user.JoinAssoTime = req.JoinAssoTime
	//user.CertificateNum = req.CertificateNum
	//conAddessByte, err := json.Marshal(req.ConAddress)
	//if err != nil {
	//	zap.L().Error("CreateUserInfo err", zap.Error(err))
	//	err = errors.New(m.ERROR_SELECT)
	//	return nil, err
	//}
	//user.ConAddress = string(conAddessByte)
	//user.CreatedAt = time.Now()
	//user.Photo = req.Photo
	//user.WxAccount = req.WxAccount
	//user.CertificateImg = req.CertificateImg
	//user.Video = req.Video
	user.IsRealName = 1
	var invite model.Invite

	err = db.DB.Where("user_id = ?", user.ID).First(&invite).Error
	if err != nil {
		logging.Info(err.Error())
		if err.Error() == "record not found" {

		} else {
			zap.L().Error("CreateUserInfo err", zap.Error(err))
			err = errors.New(m.ERROR_SELECT)
			return nil, err
		}
	}
	if invite.ID == 0 {
		InvitedId, err := CheckInvitedCodes(req.InvitedCode)
		if err == nil {
			var invite InviteService
			invite.UserId = uint(req.Id)
			invite.InvitedId = InvitedId
			Createinvite(invite)
		}
	}

	fmt.Printf("%+v\n", user)
	user.ID = req.Id
	err = db.DB.Save(&user).Error
	if err != nil {
		zap.L().Error("CreateUserInfo err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return nil, err
	}

	return

}

type InvitedCodeService struct {
	InvitedCode string `form:"invitedCode" json:"invitedCode"`
}
type InviteService struct {
	Id        uint `json:"id"`
	UserId    uint `form:"userId" json:"userId"`
	InvitedId uint `form:"invitedId" json:"invitedId"`
}

func Createinvite(service InviteService) {

	var invite model.Invite
	invite.UserId = int32(service.UserId)
	invite.InvitedId = int32(service.InvitedId)
	db.DB.Create(&invite)

}

func CheckInvitedCodes(invitedCode string) (uint, error) {

	var user model.User
	//找到用户
	if err := db.DB.Where("invited_code =?", invitedCode).Find(&user).Error; err != nil {
		return 0, err
	}
	if user.ID == 0 {
		return 0, errors.New("邀请码无效")
	}
	return uint(user.ID), nil
}

func GetUser(req *artistInfoUser.GetUserRequest) (rep *artistInfoUser.GetUserRespond, err error) {
	rep = &artistInfoUser.GetUserRespond{}
	// service := &artist.UserUpdateInfoService{}
	var user model.User
	if err = db.DB.Where("tel_num = ?", req.TelNum).First(&user).Error; err != nil {
		zap.L().Error("get user info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return nil, err
	}
	// rep.
	fmt.Println(user)
	rep.Id = user.ID
	rep.MgmtAccId = user.MgmtAccId
	rep.MgmtArtistUid = user.MgmtArtistUid
	rep.MgmtArtistId = user.MgmtArtistId
	rep.TelNum = user.TelNum
	rep.FddState = user.FddState
	rep.IsRealName = user.IsRealName
	//rep.Ruler = user.Ruler
	// service.QrCodeImg = fmt.Sprintf("https://cdn.fontree.cn/artistmgmt/static/qrcode/%v.png", user.InvitedCode)

	// service.QrCodeImgDownload = fmt.Sprintf("https://cdn.fontree.cn/artistmgmt/static/qrcode/%v-2.png", user.InvitedCode)
	// rep.Data = service
	return rep, nil
}

func GetUserById(req *artistInfoUser.GetUserByIdRequest) (rep *artistInfoUser.GetUserByIdRespond, err error) {
	rep = &artistInfoUser.GetUserByIdRespond{}
	fmt.Println("id:", req.Id)
	fmt.Println("123")
	zap.L().Info("!!!!")
	fmt.Println("456")
	// service := &artist.UserUpdateInfoService{}
	var user model.User
	fmt.Println("666")
	if err = db.DB.Where("id = ?", req.Id).First(&user).Error; err != nil {
		zap.L().Info("!!!!3")
		zap.L().Error("get user info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return
	}
	fmt.Printf("%+v\n", user)
	fmt.Println("6666")
	zap.L().Info("!!!!5")
	// rep.
	fmt.Println("777")
	rep.Id = user.ID
	rep.MgmtAccId = user.MgmtAccId
	rep.MgmtArtistUid = user.MgmtArtistUid
	rep.MgmtArtistId = user.MgmtArtistId
	rep.TelNum = user.TelNum
	rep.FddState = user.FddState
	rep.IsRealName = user.IsRealName
	//rep.Ruler = user.Ruler
	return rep, nil
}

func FinishVerify(req *artistInfoUser.FinishVerifyRequest) (rep *artistInfoUser.FinishVerifyRespond, err error) {
	var user model.User
	user.ID = req.Id
	if err = db.DB.Model(&user).Update("isfdd", 2).Error; err != nil {
		zap.L().Error("get user info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return nil, err
	}
	return rep, nil
}

func ArtistSupplyList(req *artistInfoUser.ArtistSupplyListRequest) (rep *artistInfoUser.ArtistSupplyListRespond, err error) {
	var artistList = make([]artistInfoUser.ArtistArtworkSupplyListResponseData, 0)
	var args []interface{}
	sql := `select cc.* from (SELECT a.id,a.name,a.pen_name,a.is_import,a.tel_num,a.sex,a.age,b.id_num,a.invited_code,a.certificate_num,a.con_address,b.idcard_front,b.idcard_back,a.photo,a.video,a.created_at,a.updated_at,a.is_lock,a.certificate_img,min(d.created_at) as dd  from user a inner join real_name b on a.real_name_id = b.id left join bank c on  a.id = c.user_id left join supply_info d on a.id = d.user_id where (d.types = 1 or d.types = 4 or d.types = 2 or d.types = 3 or d.types =6) and a.is_real_name = true   `
	sqlWhere := ` `
	sqlGroup := ` group by a.id order by min(d.created_at) desc ) cc inner join supply_info f where dd >0 and dd = f.created_at and cc.id = f.user_id group by cc.id,dd `
	var count int64
	tx := db.DB.Raw("select count(*) from (" + sql + sqlWhere + sqlGroup + ") cc").Scan(&count)
	if tx.Error != nil {
		zap.L().Error("get user info err", zap.Error(tx.Error))
		err = errors.New(m.ERROR_SELECT)
		return nil, err
	}
	rep.Count = count
	var sqlLimit = " limit ?,? "
	args = append(args, (req.Page-1)*req.PageSize)
	args = append(args, req.PageSize)
	err = db.DB.Raw(sql + sqlWhere + sqlGroup + sqlLimit).Scan(&artistList).Error
	if err != nil {
		zap.L().Error("get user info err", zap.Error(tx.Error))
		err = errors.New(m.ERROR_SELECT)
		return nil, err
	}
	for _, v := range artistList {
		rep.Data = append(rep.Data, &v)
	}
	return rep, nil
}

func UserLock(req *artistInfoUser.UserLockRequest) (rep *artistInfoUser.UserLockRespond, err error) {
	var tx = db.DB.Model(model.User{}).Begin()
	switch {
	case req.Id != 0:
		tx = tx.Where("id = ?", req.Id)
	case req.AccId != 0:
		tx = tx.Where("mgmt_acc_id = ?", req.AccId)
	case req.ArtistUid != "":
		tx = tx.Where("mgmt_artist_uid = ?", req.ArtistUid)
	default:
		err = errors.New(m.ERROR_DATA_NOT_EXISTS)
		zap.L().Error("get user info err", zap.Error(err))
		return
	}
	var now string
	if req.IsLock {
		now = stime.TimeToString(time.Now(), stime.Format_Normal_YMDhms)
	}
	if err = tx.Update("is_lock", req.IsLock).Update("latest_lock_time", now).Error; err != nil {
		zap.L().Error("get user info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return nil, err
	}
	rep.LockTime = now

	if !req.IsLock {
		// 解锁时与另外4个模块联动
		if err = db.DB.Model(model.ArtworkLockRecord{}).Where("artist_uid = ? AND status =2 ", req.ArtistUid).Update("status", 3).Error; err != nil {
			return nil, err
		}
		if err = db.DB.Model(model.ArtshowArtistSupplement{}).Where("artist_uid = ? AND status =2 ", req.ArtistUid).Update("status", 3).Error; err != nil {
			return nil, err
		}
		if err = db.DB.Model(model.ArtshowArtistIndex{}).Where("artist_uid = ? AND status =2 ", req.ArtistUid).Update("status", 3).Error; err != nil {
			return nil, err
		}
		if err = db.DB.Model(model.ArtshowVideoRecord{}).Where("artist_uid = ? AND status =2 ", req.ArtistUid).Update("status", 3).Error; err != nil {
			return nil, err
		}
	}
	tx.Commit()

	return rep, nil
}

func CheckInvitedCode(req *artistInfoUser.CheckInvitedCodeRequest) (rep *artistInfoUser.GetUserRespond, err error) {
	rep = &artistInfoUser.GetUserRespond{}
	// service := &artist.UserUpdateInfoService{}
	var user model.User
	if err = db.DB.First(&user, "invited_code = ?", req.InvitedCode).Error; err != nil {
		zap.L().Error("get user info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return nil, err
	}
	// rep.
	rep.Id = user.ID
	rep.MgmtAccId = user.MgmtAccId
	rep.MgmtArtistUid = user.MgmtArtistUid
	rep.TelNum = user.TelNum
	rep.FddState = user.FddState
	rep.IsRealName = user.IsRealName
	//rep.Ruler = user.Ruler
	// service.QrCodeImg = fmt.Sprintf("https://cdn.fontree.cn/artistmgmt/static/qrcode/%v.png", user.InvitedCode)

	// service.QrCodeImgDownload = fmt.Sprintf("https://cdn.fontree.cn/artistmgmt/static/qrcode/%v-2.png", user.InvitedCode)
	// rep.Data = service
	return rep, nil
}

func UnFinishList(req *artistInfoUser.UnFinishListRequest) (rep *artistInfoUser.UnFinishListRespond, err error) {
	rep = &artistInfoUser.UnFinishListRespond{}
	var user model.User
	if err := db.DB.Where("id = ? ", req.Id).First(&user).Error; err != nil {
		zap.L().Error("get user info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return nil, err

	}

	// todo
	//var realName model.RealName
	//if err := db.DB.Where("id = ? ", user.RealNameID).First(&realName).Error; err != nil {
	//	zap.L().Error("get user info err", zap.Error(err))
	//	err = errors.New(m.ERROR_SELECT)
	//	return nil, err
	//}
	//var contract model.Contract
	//var contractCount int64
	//if err := db.DB.Model(&contract).Where("state = ? and (user_id = ? or card_id = ?) and (type =1 or type = 2 or type = 3)", "1", user.ID, realName.IDNum).Count(&contractCount).Error; err != nil {
	//	err = errors.New(m.ERROR_SELECT)
	//	return nil, err
	//}
	//rep.ContractList = contractCount
	//var accountStateCount int64
	//fmt.Println(realName.IDNum)
	//if err := db.DB.Model(&contract).Where("state = ? and (user_id = ? or card_id = ?) and type = 4", "1", user.ID, realName.IDNum).Count(&accountStateCount).Error; err != nil {
	//	zap.L().Error("get user info err", zap.Error(err))
	//	err = errors.New(m.ERROR_SELECT)
	//	return nil, err
	//}
	//rep.AccountStateList = accountStateCount
	//var supplyInfo model.SupplyInfo
	//var supplyInfoCount int64
	//if err := db.DB.Model(&supplyInfo).Where("types = ? and user_id = ? ", "1", user.ID).Count(&supplyInfoCount).Error; err != nil {
	//	zap.L().Error("get user info err", zap.Error(err))
	//	err = errors.New(m.ERROR_SELECT)
	//	return nil, err
	//}
	//rep.SupplyInfoList += supplyInfoCount
	//var exhVideo model.ExhVideo
	//var exhVideoCount int64
	//if err := db.DB.Model(&exhVideo).Where("types = ? and user_id = ? ", "1", user.ID).Count(&exhVideoCount).Error; err != nil {
	//	zap.L().Error("get user info err", zap.Error(err))
	//	err = errors.New(m.ERROR_SELECT)
	//	return nil, err
	//}
	//rep.SupplyInfoList += exhVideoCount
	//var exhExam model.ExhExam
	//var exhExamCount int64
	//if err := db.DB.Model(&exhExam).Where("types = ? and user_id = ? ", "1", user.ID).Count(&exhExamCount).Error; err != nil {
	//	zap.L().Error("get user info err", zap.Error(err))
	//	err = errors.New(m.ERROR_SELECT)
	//	return nil, err
	//}
	//rep.SupplyInfoList += exhExamCount

	return rep, nil
}

func GetUserMsg(req *artistInfoUser.GetUserMsgRequest) (rep *artistInfoUser.GetUserMsgRespond, err error) {
	var user model.User

	err = db.DB.Where("id = ?", req.Id).First(&user).Error
	if err != nil {
		zap.L().Error("get user info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return nil, err
	}
	userByte, err := json.Marshal(user)
	if err != nil {
		zap.L().Error("1get user info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return nil, err
	}
	fmt.Println(string(userByte))
	var re = new(artistInfoUser.GetUserMsgRespond)
	err = json.Unmarshal(userByte, re)
	if err != nil {
		zap.L().Error("1get user info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return nil, err
	}
	rep = re
	return rep, nil
}

func FindUser(req *artistInfoUser.FindUserRequest) (rep *artistInfoUser.UserInfo, err error) {
	rep = &artistInfoUser.UserInfo{}
	var data = model.User{}
	var tx = db.DB.Model(model.User{}).Preload("RealNameInfo").Preload("InvitedBy.UserInfo.RealNameInfo")
	if req.MgmtAccId != 0 {
		tx = tx.Where("mgmt_acc_id = ?", req.MgmtAccId)
	}
	if req.MgmtArtistId != 0 {
		tx = tx.Where("mgmt_artist_id = ?", req.MgmtArtistId)
	}
	if req.InvitedCode != "" {
		tx = tx.Where("invited_code = ?", req.InvitedCode)
	}
	if req.MgmtArtistUid != "" {
		tx = tx.Where("mgmt_artist_uid = ?", req.MgmtArtistUid)
	}
	err = tx.First(&data).Error
	if err != nil {
		return
	}
	if data.RealNameInfo == nil {
		data.RealNameInfo = &model.RealName{}
	}
	if data.InvitedBy == nil {
		data.InvitedBy = &model.Invite{}
	}
	var invitedName string
	if data.InvitedBy != nil && data.InvitedBy.UserInfo != nil && data.InvitedBy.UserInfo.RealNameInfo != nil {
		invitedName = data.InvitedBy.UserInfo.RealNameInfo.Name
	}
	rep = &artistInfoUser.UserInfo{
		Id:            data.ID,
		DeletedAt:     int64(data.DeletedAt),
		UpdatedAt:     data.UpdatedAt.Unix(),
		CreatedAt:     data.CreatedAt.Unix(),
		MgmtAccId:     data.MgmtAccId,
		MgmtArtistId:  data.MgmtArtistId,
		MgmtArtistUid: data.MgmtArtistUid,
		TelNum:        data.TelNum,
		InvitedCode:   data.InvitedBy.InviteCode, //邀请人的邀请码，不是用户个人邀请码
		InvitedName:   invitedName,               //邀请人没有实名则为空字符串
		IsRealName:    data.IsRealName,
		RealNameId:    data.RealNameId,
		RealName: &artistInfoUser.RealNameInfo{
			Name:        data.RealNameInfo.Name,
			IdNum:       data.RealNameInfo.IdNum,
			IdCardFront: data.RealNameInfo.IdCardFront,
			IdCardBack:  data.RealNameInfo.IdCardBack,
			Age:         int32(data.RealNameInfo.Age),
			Sex:         string(data.RealNameInfo.Sex),
			Birthday:    data.RealNameInfo.Birthday,
			Address:     data.RealNameInfo.Address,
			Id:          data.RealNameInfo.ID,
		},
		FddState:       data.FddState,
		CustomerId:     data.CustomerId,
		OpenId:         data.OpenId,
		IsRead:         data.IsRead,
		IsLock:         data.IsLock,
		Account:        data.Account,
		CertificateNum: data.CertificateNum,
		CertificateImg: data.CertificateImg,
		Photo:          data.Photo,
		HtmlType:       data.Htmltype,
		EnvType:        data.Envtype,
		InviteCode:     data.InviteCode,
		LatestLockTime: data.LatestLockTime,
	}

	return rep, nil
}

func FindUserList(req *artistInfoUser.FindUsersRequest) (rep []*artistInfoUser.UserInfo, total int64, err error) {
	//todo 待修改，邀请人的关联信息不显示
	var (
		datas = []model.User{}
		tx    = db.DB.Model(model.User{}).
			Joins("LEFT JOIN real_name rn ON rn.id  = sys_user.real_name_id").
			Preload("RealNameInfo").Preload("InvitedBy.UserInfo.RealNameInfo").Where("sys_user.mgmt_artist_uid!=''")
	)
	if req.InvitedCode != "" {
		tx = tx.Where("invited_code = ?", req.InvitedCode)
	}
	if req.MgmtArtistUid != "" {
		tx = tx.Where("mgmt_artist_uid = ?", req.MgmtArtistUid)
	}
	if req.MgmtArtistUids != nil {
		tx = tx.Where("mgmt_artist_uid in ?", req.MgmtArtistUids)
	}
	if req.InviterName != "" {
		tx = tx.Clauses(clause.Like{
			Column: "rn.name",
			Value:  "%" + req.InviterName + "%",
		})
	}
	if req.IsArtist {
		tx = tx.Where("mgmt_artist_uid !='' ")
	}
	if req.IsLock {
		tx = tx.Where("is_lock=true")
	}
	if req.ArtistRealName != "" {
		tx = tx.Where("").Clauses(clause.Like{
			Column: "rn.name",
			Value:  "%" + req.ArtistRealName + "%",
		})
	}

	err = tx.Count(&total).Scopes(db.Pagination(req.Page, req.PageSize)).Find(&datas).Error
	if err != nil {
		return
	}
	for _, v := range datas {
		if v.RealNameInfo == nil {
			v.RealNameInfo = &model.RealName{}
		}
		if v.InvitedBy == nil {
			v.InvitedBy = &model.Invite{}
		}
		var invitedName string
		if v.InvitedBy != nil && v.InvitedBy.UserInfo != nil && v.InvitedBy.UserInfo.RealNameInfo != nil {
			invitedName = v.InvitedBy.UserInfo.RealNameInfo.Name
		} else {
			invitedName = "无"
		}
		rep = append(rep, &artistInfoUser.UserInfo{
			Id:            v.ID,
			DeletedAt:     int64(v.DeletedAt),
			UpdatedAt:     v.UpdatedAt.Unix(),
			CreatedAt:     v.CreatedAt.Unix(),
			MgmtAccId:     v.MgmtAccId,
			MgmtArtistId:  v.MgmtArtistId,
			MgmtArtistUid: v.MgmtArtistUid,
			TelNum:        v.TelNum,
			InvitedCode:   v.InvitedBy.InviteCode, //邀请人的邀请码，不是用户个人邀请码
			InvitedName:   invitedName,            //邀请人没有实名则为空字符串
			IsRealName:    v.IsRealName,
			RealNameId:    v.RealNameId,
			RealName: &artistInfoUser.RealNameInfo{
				Name:        v.RealNameInfo.Name,
				IdNum:       v.RealNameInfo.IdNum,
				IdCardFront: v.RealNameInfo.IdCardFront,
				IdCardBack:  v.RealNameInfo.IdCardBack,
				Age:         int32(v.RealNameInfo.Age),
				Sex:         string(v.RealNameInfo.Sex),
				Birthday:    v.RealNameInfo.Birthday,
				Address:     v.RealNameInfo.Address,
				Id:          v.RealNameInfo.ID,
			},
			FddState:       v.FddState,
			CustomerId:     v.CustomerId,
			OpenId:         v.OpenId,
			IsRead:         v.IsRead,
			IsLock:         v.IsLock,
			Account:        v.Account,
			CertificateNum: v.CertificateNum,
			CertificateImg: v.CertificateImg,
			Photo:          v.Photo,
			HtmlType:       v.Htmltype,
			EnvType:        v.Envtype,
			InviteCode:     v.InviteCode,
			LatestLockTime: v.LatestLockTime,
		})
	}
	return
}

func GetViewUserList(req *artistInfoUser.FindUsersRequest) (resp []model.UserView, total int64, err error) {
	resp = []model.UserView{}
	var (
		tx = db.DB.Model(model.UserView{}).Order("created_at desc")
	)
	if req.InvitedCode != "" {
		tx = tx.Where("invited_code = ?", req.InvitedCode)
	}
	if req.MgmtArtistUid != "" {
		tx = tx.Where("mgmt_artist_uid = ?", req.MgmtArtistUid)
	} else if req.MgmtArtistUids != nil {
		tx = tx.Where("mgmt_artist_uid in ?", req.MgmtArtistUids)
	}
	if req.InviterName != "" {
		tx = tx.Where("inviter_real_name LIKE '%?%'", req.InviterName)
	}
	if req.IsArtist {
		tx = tx.Where("mgmt_artist_uid !='' ")
	}

	err = tx.Count(&total).Scopes(db.Pagination(req.Page, req.PageSize)).Find(&resp).Error
	return
}

func UpdateUserData(req *artistInfoUser.UserInfo) (rep *artistInfoUser.CommonNoParams, err error) {
	var (
		preUpdateData    model.User
		tx               = db.DB.Begin().Preload("RealNameInfo")
		needUpdateMobile bool
	)
	if req.Id != 0 {
		tx = tx.Where("id = ?", req.Id)
	} else if req.MgmtAccId != 0 {
		tx = tx.Where("mgmt_acc_id = ?", req.MgmtAccId)
	} else {
		return nil, errors.New("Id或mgmt_acc_id不能为0")
	}
	if err = tx.Find(&preUpdateData).Error; err != nil {
		return nil, err
	}
	//判断需要更新内容
	if req.MgmtArtistId != 0 {
		preUpdateData.MgmtArtistId = req.MgmtArtistId
	}
	if req.MgmtArtistUid != "" {
		preUpdateData.MgmtArtistUid = req.MgmtArtistUid
	}
	if req.TelNum != "" && req.TelNum != preUpdateData.TelNum {
		needUpdateMobile = true
		preUpdateData.TelNum = req.TelNum
	}
	if req.InviteCode != "" {
		preUpdateData.InviteCode = req.InviteCode
	}
	if req.IsRealName != 0 {
		preUpdateData.IsRealName = req.IsRealName
	}
	if req.RealNameId != 0 {
		preUpdateData.RealNameId = req.RealNameId
	}
	if req.FddState != 0 {
		preUpdateData.FddState = req.FddState
	}
	if req.CustomerId != "" {
		preUpdateData.CustomerId = req.CustomerId
	}
	if req.OpenId != "" {
		preUpdateData.OpenId = req.OpenId
	}
	if req.IsRead != 0 {
		preUpdateData.IsRead = req.IsRead
	}
	if req.IsLock {
		preUpdateData.IsLock = req.IsLock
	}
	if req.Account != "" {
		preUpdateData.Account = req.Account
	}
	if req.CertificateNum != "" {
		preUpdateData.CertificateNum = req.CertificateNum
	}
	if req.CertificateImg != "" {
		preUpdateData.CertificateImg = req.CertificateImg
	}
	if req.Photo != "" {
		preUpdateData.Photo = req.Photo
	}
	if req.HtmlType != "" {
		preUpdateData.Htmltype = req.HtmlType
	}
	if req.EnvType != "" {
		preUpdateData.Envtype = req.EnvType
	}
	//var updateData = model.User{
	//	Model: model.Model{
	//		ID:        req.Id,
	//		CreatedAt: time.Unix(req.CreatedAt, 0),
	//		UpdatedAt: time.Unix(req.UpdatedAt, 0),
	//		DeletedAt: soft_delete.DeletedAt(req.DeletedAt),
	//	},
	//	MgmtAccId:      req.MgmtAccId,
	//	MgmtArtistId:   req.MgmtArtistId,
	//	TelNum:         req.TelNum,
	//	InviteCode:     req.InvitedCode,
	//	IsRealName:     req.IsRealName,
	//	RealNameId:     req.RealNameId,
	//	FddState:       req.FddState,
	//	CustomerId:     req.CustomerId,
	//	OpenId:         req.OpenId,
	//	IsRead:         req.IsRead,
	//	IsLock:         req.IsLock,
	//	Account:        req.Account,
	//	CertificateNum: req.CertificateNum,
	//	CertificateImg: req.CertificateImg,
	//	Photo:          req.Photo,
	//	Htmltype:       req.Htmltype,
	//	Envtype:        req.Envtype,
	//}
	err = tx.Save(&preUpdateData).Error
	//更新实名信息
	if req.RealName != nil {
		var realName = model.RealName{}
		if preUpdateData.RealNameInfo != nil {
			realName = *preUpdateData.RealNameInfo
		}
		if req.RealName.Name != "" {
			realName.Name = req.RealName.Name
		}
		if req.RealName.IdNum != "" {
			realName.IdNum = req.RealName.IdNum
		}
		if req.RealName.TelNum != "" {
			realName.TelNum = req.RealName.TelNum
		}
		if req.RealName.IdCardFront != "" {
			realName.IdCardFront = req.RealName.IdCardFront
		}
		if req.RealName.IdCardBack != "" {
			realName.IdCardBack = req.RealName.IdCardBack
		}
		if req.RealName.Age != 0 {
			realName.Age = int(req.RealName.Age)
		}
		if req.RealName.Sex != "" {
			realName.Sex = model.SexType(req.RealName.Sex)
		}
		if req.RealName.Birthday != "" {
			realName.Birthday = req.RealName.Birthday
		}
		if req.RealName.Address != "" {
			realName.Address = req.RealName.Address
		}
		err = db.DB.Save(&realName).Error
	}

	//更新手机号码
	if needUpdateMobile {
		// 更新账号服务中手机号
		if _, err = service.AccountProvider.UpdateTelNum(context.Background(), &account.SendNewTelNumMsgRequest{
			Domain:    req.Domain,
			ID:        uint64(preUpdateData.MgmtAccId),
			NewTelNum: preUpdateData.TelNum,
			Code:      req.VerCode,
			Project:   "",
		}); err != nil {
			fmt.Println("错误1-needUpdateMobile-AccountImpl.UpdateTelNum:", err.Error())
			tx.Rollback()
			return
		}
		//更新画家服务中的手机号
		if _, err = service.GrpcArtistImpl.UpdateProfile(context.Background(), &artist.ProfileRequest{Uid: preUpdateData.MgmtArtistUid, Phone: preUpdateData.TelNum}); err != nil {
			fmt.Println("错误2-needUpdateMobile-rpcArtistImpl.UpdateProfile:", err.Error())
			tx.Rollback()
			return
		}
	}
	tx.Commit()
	return nil, nil
}

func PreSaveArtistInfo(in *artistInfoUser.PreSaveArtistInfoData) (rep *artistInfoUser.CommonNoParams, err error) {
	var data = model.TempArtistInfo{}
	err = db.DB.Where("mgmt_acc_id = ?", in.MgmtAccId).Find(&data).Error
	if err != nil {
		return
	}
	var tx = db.DB
	data = model.TempArtistInfo{
		MgmtAccId:   in.MgmtAccId,
		Name:        in.Name,
		CardId:      in.CardId,
		Gender:      in.Gender,
		Age:         in.Age,
		NativePlace: in.NativePlace,
		PenName:     in.PenName,
		Phone:       in.Phone,
		Address:     in.Address,
		StageName:   in.StageName,
		CaaCertNum:  in.CaaCertNum,
		CaaJoinTime: in.CaaJoinTime,
		JoinShow:    in.JoinShow,
	}
	if data.MgmtAccId == 0 {
		err = tx.Create(&data).Error
	} else {
		err = tx.Where("mgmt_acc_id = ?", in.MgmtAccId).Save(&data).Error
	}
	return
}

func GetPreSaveArtistInfo(in *artistInfoUser.GetPreSaveArtistInfoRequest) (res *artistInfoUser.PreSaveArtistInfoData, err error) {
	var data = model.TempArtistInfo{}
	err = db.DB.Where("mgmt_acc_id = ?", in.MgmtAccId).Find(&data).Error
	res = &artistInfoUser.PreSaveArtistInfoData{
		MgmtAccId:   data.MgmtAccId,
		Name:        data.Name,
		CardId:      data.CardId,
		Gender:      data.Gender,
		Age:         data.Age,
		NativePlace: data.NativePlace,
		PenName:     data.PenName,
		Phone:       data.Phone,
		Address:     data.Address,
		StageName:   data.StageName,
		CaaCertNum:  data.CaaCertNum,
		CaaJoinTime: data.CaaJoinTime,
		JoinShow:    data.JoinShow,
	}
	return
}
func CheckUserLock(id int64) (err error) {
	var user model.User
	if err = db.DB.Where("id = ? ", id).First(&user).Error; err != nil {
		zap.L().Error("get user info err", zap.Error(err))
		err = errors.New(m.ERROR_SELECT)
		return
	}
	fmt.Printf("%+v\n", user)
	if user.IsLock {
		fmt.Println(user.IsLock)
		fmt.Println("22222")
		zap.L().Error("user is lock")
		return errors.New(m.ERROR_ISLOCK)
	}
	fmt.Println("333333")
	return nil
}
func CheckUserLockByArtistUid(artistUid string) (err error) {
	var user model.User
	if err = db.DB.Where("mgmt_artist_uid = ?", artistUid).First(&user).Error; err != nil {
		zap.L().Error("get user info err", zap.Error(err))
		if err == gorm.ErrRecordNotFound {
			return errors.New(m.ARTIST_NOT_EXISTS)
		}
		err = errors.New(m.ERROR_SELECT)
		return
	}
	if user.IsLock {
		return errors.New(m.ERROR_ISLOCK)
	}
	return nil
}
