use crate::{commons::utils::CONFIG as config, db::models::log::Log};
use chrono::{DateTime, NaiveDate, Utc};
use serde_json::json;

pub struct Game {
    pub wechat_id: String,
    pub nickname: String,
    pub avatar: String,
    /// 游戏项目(1到6)
    pub item_num: i32,
    /// 排序
    pub game_rank: i32,
    /// 得分
    pub score: i32,
    /// 创建时间
    pub create_date: Option<DateTime<Utc>>,
}

impl Game {
    pub async fn insert(&self) -> bool {
        let Some(_) = &config.db else {
            println!("没有配置数据库, return true;");
            return true;
        };
        let res = crate::db::db_query(
            r#"insert into tb_game(wechat_id,nickname,avatar,item_num,game_rank,score,create_date) values(?,?,?,?,?,?,now());"#,
            vec![
                json!(&self.wechat_id),
                json!(&self.nickname),
                json!(&self.avatar),
                json!(&self.item_num),
                json!(&self.game_rank),
                json!(&self.score),
            ],
        )
        .await;
        match res {
            Ok(res) => {
                // dbg!(&res);
                true
            }
            Err(err) => {
                // dbg!(&err);

                let log = Log {
                    id: 0,
                    msg: err,
                    params: json!({
                        "wechat_id": self.wechat_id,
                        "nickname": self.nickname,
                        "avatar": self.avatar,
                        "item_num": self.item_num,
                        "game_rank":self.game_rank,
                        "score": self.score,
                    }),
                    create_date: None,
                };
                log.insert().await;
                false
            }
        }
    }
}
