package utilities

import (
	"os"
	"time"
)
type Error struct{
	msg string
}

var err *Error

func NewError()*Error{
	err = &Error{}
	return err
}

func (e *Error)GetMsg()string{
	return e.msg
}

func todayFilename()string{
	today := time.Now().Format("2006-01-02")
	return today + ".log"
}
// 创建打开文件
func getLogFile(content string){
	path, _ := os.Getwd()
	logsPath := path+"/logs"
	if !isExist(logsPath) {
		err := os.Mkdir(logsPath,os.ModePerm)
		if err != nil {
			panic(err)
		}
	}
	filename := logsPath+"/"+todayFilename()
	log,err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	defer log.Close()
	if err != nil {
		panic(err)
	}
	str := []byte(content)
	// 写入文件
	n, err := log.Write(str)
	if err == nil && n != len(str) {
		println(`错误代码：`, n)
		panic(err)
	}
}

func WriteLog(content string, grade string ){
	grade = "["+grade+"]"
	createTime := time.Now().Format("15:04:05")
	getLogFile("\n"+grade+"   "+createTime+"\n"+"   "+content)
	err.msg = content
}

func isExist(f string) bool {
	_, err := os.Stat(f)
	return err == nil || os.IsExist(err)
}
