package model

import (
	model2 "cold-delivery/common/model"
	"encoding/json"
	"errors"
	log "gogs.baozhida.cn/zoie/OAuth-core/logger"
	"gogs.baozhida.cn/zoie/OAuth-core/sdk"
	"gogs.baozhida.cn/zoie/OAuth-core/sdk/config"
	"gogs.baozhida.cn/zoie/OAuth-core/storage"
	"time"
)

type SysOperaLog struct {
	model2.Model
	Title         string    `json:"title" gorm:"size:255;comment:操作模块"`
	BusinessType  string    `json:"businessType" gorm:"size:128;comment:操作类型"`
	BusinessTypes string    `json:"businessTypes" gorm:"size:128;comment:BusinessTypes"`
	Method        string    `json:"method" gorm:"size:128;comment:函数"`
	RequestMethod string    `json:"requestMethod" gorm:"size:128;comment:请求方式 GET POST PUT DELETE"`
	OperatorType  string    `json:"operatorType" gorm:"size:128;comment:操作类型"`
	OperaName     string    `json:"operaName" gorm:"size:128;comment:操作者"`
	DeptName      string    `json:"deptName" gorm:"size:128;comment:机构名称"`
	OperaUrl      string    `json:"operaUrl" gorm:"size:255;comment:访问地址"`
	OperaIp       string    `json:"operaIp" gorm:"size:128;comment:客户端ip"`
	OperaLocation string    `json:"operaLocation" gorm:"size:128;comment:访问位置"`
	OperaParam    string    `json:"operaParam" gorm:"text;comment:请求参数"`
	Status        string    `json:"status" gorm:"size:4;comment:操作状态 1:正常 2:关闭"`
	OperaTime     time.Time `json:"operaTime" gorm:"comment:操作时间"`
	JsonResult    string    `json:"jsonResult" gorm:"text;comment:返回数据"`
	Remark        string    `json:"remark" gorm:"size:255;comment:备注"`
	LatencyTime   string    `json:"latencyTime" gorm:"size:128;comment:耗时"`
	UserAgent     string    `json:"userAgent" gorm:"size:255;comment:ua"`
	CreatedAt     time.Time `json:"createdAt" gorm:"comment:创建时间"`
	UpdatedAt     time.Time `json:"updatedAt" gorm:"comment:最后更新时间"`
	model2.ControlBy
}

func (SysOperaLog) TableName() string {
	return "sys_opera_log"
}

func (e *SysOperaLog) Generate() model2.ActiveRecord {
	o := *e
	return &o
}

func (e *SysOperaLog) GetId() interface{} {
	return e.Id
}

// SaveOperaLog 从队列中获取操作日志
func SaveOperaLog(message storage.Messager) (err error) {
	//准备db
	db := sdk.Runtime.GetDbByKey(config.ApplicationConfig.Host)
	if db == nil {
		err = errors.New("db not exist")
		log.Errorf("host[%s]'s %s", config.ApplicationConfig.Host, err.Error())
		// Log writing to the database ignores error
		return nil
	}
	var rb []byte
	rb, err = json.Marshal(message.GetValues())
	if err != nil {
		log.Errorf("json Marshal error, %s", err.Error())
		// Log writing to the database ignores error
		return nil
	}
	var l SysOperaLog
	err = json.Unmarshal(rb, &l)
	if err != nil {
		log.Errorf("json Unmarshal error, %s", err.Error())
		// Log writing to the database ignores error
		return nil
	}
	// 外部调用获取身份信息，操作频繁，不做日志记录
	if l.OperaUrl == "/api/service/userinfo" || l.OperaUrl == "/api/upload" || l.OperaUrl == "/api/waybill/import" || l.OperaUrl == "/api/apk-upload" {
		return nil
	}
	// 超出100个字符返回值截断
	if len(l.JsonResult) > 500 {
		l.JsonResult = l.JsonResult[:500]
	}
	l.OperaTime = time.Now()
	err = db.Create(&l).Error
	if err != nil {
		log.Errorf("db create error, %s", err.Error())
		// Log writing to the database ignores error
		return nil
	}
	return nil
}
