package models

import (
	"errors"
	"github.com/codinl/go-logger"
	"github.com/gin-gonic/gin"
	orm "go-admin/common/global"
	"net"
	"net/http"
	"strings"
)

type SysSetting struct {
	SettingsId int    `json:"settings_id" gorm:"primary_key;AUTO_INCREMENT"`
	Name       string `json:"name" gorm:"type:varchar(256);"`
	Logo       string `json:"logo" gorm:"type:varchar(256);"`
	BaseModel
}

func (SysSetting) TableName() string {
	return "sys_setting"
}

// 查询
func (s *SysSetting) Get() (create SysSetting, err error) {
	result := orm.Eloquent.Table("sys_setting").First(&create)
	if result.Error != nil {
		err = result.Error
		return
	}
	return create, nil
}

// 修改
func (s *SysSetting) Update() (update SysSetting, err error) {
	if err = orm.Eloquent.Table("sys_setting").Model(&update).Updates(&s).Error; err != nil {
		return
	}
	return
}

type ResponseSystemConfig struct {
	Name string `json:"name" binding:"required"` // 名称
	Logo string `json:"logo" binding:"required"` // 头像
}

const (
	LoggingEventInventoryImport = "inventory_import"
	LoggingEventCreateSupplier  = "create_supplier"
	LoggingEventEditSupplier    = "edit_supplier"
)

type Logging struct {
	Model

	Machine     string `json:"machine"`
	StoreId     uint32 `json:"store_id" gorm:"index"` // 门店id
	StoreName   string `json:"store_name"`
	OperatorUid uint32 `json:"operator_uid" gorm:"index"`
	Operator    string `json:"operator"`
	Function    string `json:"function"`
	Event       string `json:"event"`
	EventName   string `json:"event_name"`
	Ip          string `json:"ip"`
}

func (m *Logging) Create(c *gin.Context) error {
	defer func() {
		if err := recover(); err != nil {
			logger.Error("recover create logging err:", err)
			return
		}
	}()

	go func() {
		if c != nil {
			sysUser, err := GetSysUserByCtx(c)
			if err != nil {
				logger.Error("sys user err:", err)
				//return err
			}
			ip, err := GetIP(c.Request)
			if err != nil {
				logger.Error("get ip err:", err)
			}
			m.Machine = c.Request.UserAgent()
			m.StoreId = sysUser.StoreId
			m.StoreName = sysUser.StoreName
			m.OperatorUid = uint32(sysUser.UserId)
			m.Operator = sysUser.NickName
			m.Ip = ip
		}

		err := orm.Eloquent.Create(m).Error
		if err != nil {
			logger.Error("create logging err:", err)
			return
		}
	}()

	return nil
}

func GetIP(r *http.Request) (string, error) {
	ip := r.Header.Get("X-Real-IP")
	if net.ParseIP(ip) != nil {
		return ip, nil
	}

	ip = r.Header.Get("X-Forward-For")
	for _, i := range strings.Split(ip, ",") {
		if net.ParseIP(i) != nil {
			return i, nil
		}
	}

	ip, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		return "", err
	}

	if net.ParseIP(ip) != nil {
		return ip, nil
	}

	return "", errors.New("no valid ip found")
}
