package log

import (
	"errors"
	"gorm.io/gorm"
	"log-server/global"
	"log-server/model/log"
	"log-server/model/log/request"
	"log-server/model/log/response"
	"time"
)

type ServiceLogEnv struct {
}

func (s *ServiceLogEnv) CreateEnv(env log.EnvLog) (err error) {
	env.CreateTime = time.Now().Format("2006-01-02 15:04:05")
	env.UpdateTime = time.Now().Format("2006-01-02 15:04:05")
	if !errors.Is(global.GVA_DB.Where("coding = ?", env.Coding).First(&log.EnvLog{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在相同coding")
	}
	return global.GVA_DB.Create(&env).Error
}

func (s *ServiceLogEnv) UpdateEnv(requestCoding request.EnvLogRequest) (err error) {
	logCoding := new(log.EnvLog)
	err = global.GVA_DB.Where("id = ?", requestCoding.Id).First(logCoding).Error
	if err != nil {
		return err
	}
	var coding = make(map[string]interface{})
	coding["coding"] = requestCoding.Coding
	coding["describe"] = requestCoding.Describe
	coding["update_time"] = time.Now().Format("2006-01-02 15:04:05")
	err = global.GVA_DB.Model(&log.CodingLog{}).Where("id", requestCoding.Id).Updates(coding).Error
	return err
}

func (s *ServiceLogEnv) GetEnvById(id int) (coding response.EnvLogReply, err error) {
	var api log.EnvLog
	err = global.GVA_DB.Where("id = ?", id).First(&api).Error
	if err != nil {
		return
	}
	coding.Id = api.Id
	coding.Coding = api.Coding
	coding.Describe = api.Describe
	coding.UpdateTime = api.UpdateTime
	coding.CreateTime = api.CreateTime
	return
}

func (s *ServiceLogEnv) GetEnvList(order string, desc bool) (list interface{}, total int64, err error) {
	db := global.GVA_DB.Model(&log.EnvLog{})
	var apiList []log.EnvLog
	err = db.Count(&total).Error
	if err != nil {
		return apiList, total, err
	} else {
		if order != "" {
			var OrderStr string
			// 设置有效排序key 防止sql注入
			// 感谢 Tom4t0 提交漏洞信息
			orderMap := make(map[string]bool, 4)
			orderMap["id"] = true
			if orderMap[order] {
				if desc {
					OrderStr = order + " desc"
				} else {
					OrderStr = order
				}
			} else { // didn't matched any order key in `orderMap`
				//global.GVA_LOG.Error(fmt.Sprintf("非法的排序字段: %v", order))
				return apiList, total, err
			}

			err = db.Order(OrderStr).Find(&apiList).Error
		} else {
			err = db.Order("id").Find(&apiList).Error
		}
	}
	var apisReply []*response.EnvLogReply
	if len(apiList) != 0 {
		for _, apiInfo := range apiList {
			coding := new(response.EnvLogReply)
			coding.Id = apiInfo.Id
			coding.Coding = apiInfo.Coding
			coding.Describe = apiInfo.Describe
			coding.UpdateTime = apiInfo.UpdateTime
			coding.CreateTime = apiInfo.CreateTime
			apisReply = append(apisReply, coding)
		}
	}
	return apisReply, total, err
}
