package utils

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/config"
)

type RTLogStruct struct {
	ActionName string `json:"ty,omitempty"`
	Date       string `json:"date,omitempty"`
	Event      string `json:"cnt,omitempty"`
}
type RespondData struct {
	Code    int    `json:"Code,omitempty"`
	Message string `json:"Message,omitempty"`
}

func GetCurrentDirectory() string {
	file, err := exec.LookPath(os.Args[0])
	if err != nil {
		return ""
	}
	path, err := filepath.Abs(file)
	if err != nil {
		return ""
	}
	i := strings.LastIndex(path, "/")
	if i < 0 {
		i = strings.LastIndex(path, "\\")
	}
	if i < 0 {
		return ""
	}
	return string(path[0 : i+1])
}

// StringToInt string to int
func StringToInt(itf interface{}) int {
	str, _ := itf.(string)
	i, _ := strconv.Atoi(str)
	return i
}
func StringToInt64(itf interface{}) int64 {
	str, _ := itf.(string)
	i, _ := strconv.ParseInt(str, 10, 64)
	return i
}
func StringToFloat(itf interface{}) float64 {
	str, _ := itf.(string)
	i, _ := strconv.ParseFloat(str, 64)
	return i
}

// IntToString int to string
func IntToString(number int) string {
	return strconv.Itoa(number)
}
func Int64ToString(number int64) string {
	return fmt.Sprintf("%d", number)
}

// 项目
var project string

func InitProject() {
	project = beego.AppConfig.String("project")
}
func GetProject() string {
	return project
}

// 配置文件
func GetConfigFile() string {
	project := GetProject()
	configFile := fmt.Sprintf("conf/%s/cfg.conf", project)
	if beego.AppConfig.String("runmode") == "test" {
		configFile = fmt.Sprintf("conf/%s/cfg_test.conf", project)
	}

	return configFile
}

// GetConf config
func GetConf(key string, file string) string {
	iniconf, err := config.NewConfig("ini", file)
	if err != nil {
		fmt.Println(err.Error())
	}
	return iniconf.String(key)
}

// 获取配置参数
func GetKeyConf(key string, subKey string) string {
	configFile := GetConfigFile()
	host := GetConf(fmt.Sprintf("%s::%s", key, subKey), configFile)
	return host
}

// 获取天开始时间
func GetTimeDayStartTime(ti int) int {
	if ti == 0 {
		ti = int(time.Now().Unix())
	}
	str := time.Unix(int64(ti), 0).Format("2006-01-02") + " 00:00:00"

	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation("2006-01-02 15:04:05", str, loc)
	if err == nil {
		return int(theTime.Unix())
	} else {
		return 0
	}
}

// 获取时间间隔天数
func GetDiffDays(t1 int, t2 int) int {
	st1 := GetTimeDayStartTime(t1)
	st2 := GetTimeDayStartTime(t2)
	secs := 0
	if st2 > st1 {
		secs = st2 - st1
	} else {
		secs = st1 - st2
	}
	return secs / 86400
}
func IsSameDay(t1 int, t2 int) bool {
	deltaDays := GetDiffDays(t1, t2)
	if deltaDays == 0 {
		return true
	}
	return false
}

func GetTime(timeStr string) int {
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation("2006-01-02 15:04:05", timeStr, loc)
	if err == nil {
		return int(theTime.Unix())
	} else {
		return 0
	}
}

func GetTime64(timeStr string) int64 {
	loc, _ := time.LoadLocation("Local")
	theTime, err := time.ParseInLocation("2006-01-02 15:04:05", timeStr, loc)
	if err == nil {
		return theTime.Unix()
	}
	return int64(0)
}

// SendAndRecvHTTP send
func SendAndRecvHTTP(method string, url string, body string) ([]byte, error) {
	client := &http.Client{}
	req, err1 := http.NewRequest(method, url, strings.NewReader(body))
	if err1 != nil {
		return nil, err1
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Content-Length", IntToString(len(body)))
	req.Header.Set("Connection", "close")

	resp, err2 := client.Do(req)
	if err2 != nil {
		return nil, err2
	}
	defer resp.Body.Close()

	return ioutil.ReadAll(resp.Body)
}

// 写埋点日志
func WriteLog(action *RTLogStruct) {
	path := GetKeyConf("events", "path")
	if err := os.MkdirAll(path, 0766); err != nil {
		log.Printf("创建路径 [%s] 失败", path)
		return
	}

	fileName := fmt.Sprintf("%s/%s-%s.log", GetKeyConf("events", "path"), action.ActionName, action.Date)
	file, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		log.Printf("打开文件 %s 失败", fileName)
		return
	}
	defer file.Close()
	file.WriteString(action.Event + "\n")
}

// InSlice 判断字符串是否在 slice 中。
func InSlice(items []string, item string) bool {
	for _, eachItem := range items {
		if eachItem == item {
			return true
		}
	}
	return false
}

// Strtomd5 md5
func Strtomd5(s string) string {
	h := md5.New()
	h.Write([]byte(s))
	rs := hex.EncodeToString(h.Sum(nil))
	return rs
}
