package mkt_part_time_user

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

	"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 PartTimeUserAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *PartTimeUserAddLogic) PartTimeUserAdd(req types.PartTimeUserAddRequest) (*types.Response, error) {
	// todo: add your logic here and delete this line
	userId := l.svcCtx.GetUserIdByJwt(l.ctx)
	var bean = new(model.I2billMktPartTimeUser)
	_, err := l.svcCtx.DB.Where("user_id = ? and del_flag = 0", userId).Get(bean)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{Code: 500, Msg: err.Error(), Data: nil}, nil
	}
	if bean.Id != 0 {
		if bean.CheckState == 54 {
			return &types.Response{Code: 500, Msg: "你的申请兼职人员的个人信息已提交，请等待审核！", Data: nil}, nil
		}
		if bean.CheckState == 58 {
			return &types.Response{Code: 500, Msg: "你的申请兼职人员的个人信息不通过原因：" + bean.CheckDesc, Data: nil}, nil
		}
		if bean.CheckState == 57 {
			return &types.Response{Code: 500, Msg: "你已经是兼职人员：", Data: nil}, nil
		}
		return &types.Response{Code: 500, Msg: "你已经是兼职人员：", Data: nil}, nil
	}
	mkid := req.MkId
	if len(req.MkId) >= 32 {
		mkid = fmt.Sprintf("%s-%s-%s-%s-%s", mkid[0:8], mkid[8:12], mkid[12:16], mkid[16:20], mkid[20:])
	}

	erpRes, err := model.GetErpUser("", mkid, l.svcCtx.Transformer, l.ctx)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{Code: 500, Msg: err.Error(), Data: nil}, nil
	}
	if erpRes == nil {
		return &types.Response{Code: 500, Msg: "二维码已失效", Data: nil}, nil
	}
	bean = &model.I2billMktPartTimeUser{
		CreateTime:     time.Now(),
		LastUpdateTime: time.Now(),
		DelFlag:        0,
		MkId:           req.MkId,
		CheckState:     54,
		CheckDesc:      "",
		CityId:         req.CityId,
		IponeNumber:    req.IponeNumber,
		Sex:            req.Sex,
		Target:         0,
		UserId:         userId,
		Name:           req.Name,
	}
	res, err := model.NewI2billMktPartTimeUserModel(l.svcCtx.SqlConn).Insert(*bean)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{Code: 500, Msg: err.Error(), Data: nil}, nil
	}
	id, _ := res.LastInsertId()
	return &types.Response{Code: 200, Msg: "", Data: id}, nil
}
