package service

import (
	"iot_manager_service/app/system/dao"
	"iot_manager_service/app/system/model"
	"iot_manager_service/util/common"
	"iot_manager_service/util/logger"
	"strconv"
	"time"
)

// 操作记录服务
var OperationHisService = new(operationHisService)

type operationHisService struct{}

func (s *operationHisService) Save(userId int64, tenantId string, handleType, handleModuleType, deviceType int,
	handleObject string, handleResult int) {
	operation := dao.OperationHistory{
		OperationType: handleType,
		ModuleType:    handleModuleType,
		DeviceType:    deviceType,
		Object:        handleObject,
		Result:        handleResult,
		HandleUserId:  userId,
		HandleTime:    time.Now(),
		TenantId:      tenantId,
	}
	err := operation.Create()
	if err != nil {
		logger.Logger.Errorf("Operation save err =%v \n", err)
	}
}

func (s *operationHisService) List(tenantId string, handleContent, operationType, moduleType string, current,
	size int) ([]model.OperationHisDetail, int64, *common.Errors) {
	his := dao.OperationHistory{
		Object: handleContent,
	}
	if operationType != "" {
		operation, err := strconv.Atoi(operationType)
		if err != nil {
			return nil, 0, common.FailResponse(err.Error(), nil)
		}
		his.OperationType = operation
	}
	if moduleType != "" {
		module, err := strconv.Atoi(moduleType)
		if err != nil {
			return nil, 0, common.FailResponse(err.Error(), nil)
		}
		his.ModuleType = module
	}

	offset := (current - 1) * size
	limit := size
	list, counts, err := his.GetHistories(offset, limit)
	if err != nil {
		return nil, 0, common.FailResponse(err.Error(), nil)
	}
	var details []model.OperationHisDetail
	for _, his := range list {
		detail := model.OperationHisDetail{
			OperationHistory: his,
		}
		detail.HandleName = UserService.GetUserName(tenantId, his.HandleUserId)
		detail.OperationTypeName = DictService.GetControlType(tenantId, his.OperationType)
		detail.ModuleTypeName = DictService.GetModuleName(tenantId, his.ModuleType)
		details = append(details, detail)
	}
	return details, counts, nil
}
