<?php

namespace Lib;

/**
 * db
 * @author:dc
 * @time 2023/2/13 15:03
 * Class Db
 * @package Lib
 */
class Db {

    use DbQuery;

    /**
     * @var \Lib\Db
     */
    static $instance;


    /**
     * @return mixed
     * @author:dc
     * @time 2023/2/13 9:12
     */
    public function getClient(){
        if(!$this->client){
            $this->connect();
        }

        try {
            // 判断是否链接中
            if($this->client->getAttribute(\PDO::ATTR_CONNECTION_STATUS)===false){
                $this->connect();
            }
        }catch (\Throwable $e){
            $this->connect();
        }

        return $this->client;
    }


    public function __construct()
    {

//        $this->connect();

    }

    /**
     * 连接sql
     * @author:dc
     * @time 2023/3/23 9:14
     */
    public function connect(){

        $tryNum = 0;

        DBPOOLCONNECTFOR:
        try {
            $this->client = new \PDO(
                'mysql:charset=utf8mb4;dbname='.DB_DATABASE.';host='.DB_HOST.';port='.DB_PORT,
                DB_USER,
                DB_PASSWORD,
                [
                    \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
                    \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8mb4'",
                    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
                ]
            );
        }catch (\Throwable $e){
            // 重新链接3次
            if($tryNum < 3){
                $tryNum++;
                goto DBPOOLCONNECTFOR;
            }

            logs($e->getMessage().$e->getTraceAsString());
        }



    }




    /**
     * @return Db
     * @author:dc
     * @time 2023/2/13 9:39
     */
    public static function instance(){
        if(empty(static::$instance)){
            static::$instance = new Db();
        }

//        if(!static::$instance->ping()){
//            static::$instance->close();
//
//            static::$instance = new Db();
//        }

        return static::$instance;
    }


    /**
     * 结束
     */
    public function __destruct(){
        $this->close();
    }


    public function close(){
        $this->client = null;
    }



}