package model

import (
	"errors"
	"fmt"
	"time"

	"git.jiaxianghudong.com/go/logs"
	"git.jiaxianghudong.com/webs/pkg/dbx"
	"github.com/go-sql-driver/mysql"
)

const LUCKREDPACKETTABLE = "`lucky`.`luck_red_packet`"

type LuckRedPacket struct {
	ID           int64  `sql:"id" json:"id"`
	UserId       int    `sql:"user_id" json:"user_id"`
	ShareUserId  int64  `sql:"share_user_id" json:"share_user_id"`
	ShareTime    int64  `sql:"share_time" json:"share_time"`
	Date         string `sql:"date" json:"date"`
	PropData     string `sql:"prop_data" json:"prop_data"`
	CreationTime string `sql:"creation_time" json:"creation_time"`
}

//添加
func (l *LuckRedPacket) Add() (int64, error) {
	var last int64
	var err error
	sqlQuery := fmt.Sprintf("INSERT INTO %s (`user_id`,`share_user_id`,`share_time`,`date`,`prop_data`) VALUE(?,?,?,?,?)", LUCKREDPACKETTABLE)
	last, err = dbx.MySQL.Insert(sqlQuery, l.UserId, l.ShareUserId, l.ShareTime, time.Now().Format("2006-01-02"), l.PropData)
	if err != nil {
		if driverErr, ok := err.(*mysql.MySQLError); ok {
			logs.Errorf("err : %v", err)
			if driverErr.Number == 1062 {
				return 0, errors.New("今日已领取！")
			}
		}
		logs.Error(fmt.Sprintf("[%s] param:%#v err:%v", LUCKREDPACKETTABLE, l, err))
		return 0, err
	}

	return last, nil
}

func (l *LuckRedPacket) GetUserAward() []LuckRedPacket {
	var err error
	var luckRedPacket []LuckRedPacket
	sqlQuery := fmt.Sprintf("SELECT user_id,share_user_id,share_time,date,prop_data,creation_time FROM %s WHERE user_id = ? ORDER BY creation_time DESC", LUCKREDPACKETTABLE)
	err = dbx.MySQL.Query2(sqlQuery, &luckRedPacket, l.UserId)
	if err != nil {
		logs.Errorf("err:%v", err)
	}
	return luckRedPacket
}
