package user

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"time"

	"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/go-zero/core/logx"
	"git.i2edu.net/i2/go-zero/core/stores/sqlc"
)

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

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

func (l *PunchClockLogic) PunchClock(req types.PunchClockRequest) (*types.Response, error) {
	partTimeUser, err := model.GetPartTimeXormByUserId(l.UserId, l.svcCtx.DB)
	if err != nil {
		logx.Error(err)
		return nil, err
	}
	if partTimeUser.UserId == 0 {
		return nil, errors.New("请先申请成为兼职")
	}
	var aar model.I2billAcquirerAttendanceRecord
	var nowDay = utils.GetTimeYmd()
	err = l.svcCtx.SqlConn.QueryRowPartial(&aar, fmt.Sprintf("select * from i2bill_acquirer_attendance_record where `user_id` = ? and date=?  limit 1"), l.UserId, nowDay)
	if err == sqlc.ErrNotFound {
		aar.DelFlag = sql.NullInt64{Int64: 0, Valid: true}
		aar.UserId = sql.NullInt64{Int64: l.UserId, Valid: true}
		aar.CreateTime = sql.NullTime{Time: time.Now(), Valid: true}
		aar.Date = sql.NullTime{Time: nowDay, Valid: true}
	}
	// 上班卡
	if req.Type == 1 && !utils.ValidTime(aar.StartTime.Time) {
		aar.StartTime = sql.NullTime{Time: time.Now(), Valid: true}
		aar.StartLat = sql.NullString{String: req.Lat, Valid: true}
		aar.StartAddress = sql.NullString{String: req.Address, Valid: true}
	} else if req.Type == 2 && !utils.ValidTime(aar.EndTime.Time) {
		// 下班卡
		aar.EndTime = sql.NullTime{Time: time.Now(), Valid: true}
		aar.EndLat = sql.NullString{String: req.Lat, Valid: true}
		aar.EndAddress = sql.NullString{String: req.Address, Valid: true}
	}
	if aar.Id == 0 {
		_, err = l.svcCtx.SqlConn.Exec(`
		INSERT INTO i2bill_acquirer_attendance_record
		(user_id,start_lat,start_address,end_lat,end_address,start_time,end_time,create_time,del_flag,date)
		VALUES
		(?,?,?,?,?,?,?,?,?,?)`,
			aar.UserId, aar.StartLat, aar.StartAddress, aar.EndLat, aar.EndAddress, aar.StartTime, aar.EndTime, aar.CreateTime, aar.DelFlag, aar.Date)
		if err != nil {
			logx.Error(err)
			return nil, err
		}
	}
	_, err = l.svcCtx.SqlConn.Exec(`update i2bill_acquirer_attendance_record set user_id = ?, start_lat = ?, start_address = ?, end_lat = ?, end_address = ?, start_time = ?, end_time = ?, create_time = ?, del_flag = ? where id = ?`,
		aar.UserId, aar.StartLat, aar.StartAddress, aar.EndLat, aar.EndAddress, aar.StartTime, aar.EndTime, aar.CreateTime, aar.DelFlag, aar.Id)
	if err != nil {
		logx.Error(err)
		return nil, err
	}
	return utils.ReturnHTTPSuccess("ok"), nil
}
