package controllers

import (
	"errors"
	"github.com/kataras/iris/v12"
	"sparrow/pkg/models"
	"sparrow/services/knowoapi/services"
)

// SceneHisController api
type SceneHisController struct {
	Ctx     iris.Context
	Service services.SceneHisService
	Token   Token
}

// Post 创建场景执行历史记录
// POST /scene_his
func (a *SceneHisController) Post() {
	ptl := new(models.SceneHis)
	if err := parseBody(a.Ctx, ptl); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	err := a.Service.Create(ptl)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, ptl)
}

// Delete delete
// DELETE /scene_his
func (a *SceneHisController) Delete() {
	sceneHis := new(models.SceneHis)
	if err := parseBody(a.Ctx, sceneHis); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	if err := a.Service.Delete(sceneHis); err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, "删除成功")
}

// Put 更新
// PUT /scene_his
func (a *SceneHisController) Put() {
	params := new(models.SceneHis)
	if err := parseBody(a.Ctx, params); err != nil {
		badRequest(a.Ctx, err)
		return
	}
	if err := a.Service.Update(params); err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, "已保存")
}

// Get 分页查询场景执行历史
// GET /scene_his?pi=&ps=&scene_id=
func (a *SceneHisController) Get() {
	pi, err := a.Ctx.URLParamInt("pi")
	if err != nil {
		badRequest(a.Ctx, err)
		return
	}
	ps, err := a.Ctx.URLParamInt("ps")
	if err != nil {
		badRequest(a.Ctx, err)
		return
	}
	sceneId := a.Ctx.URLParam("scene_id")

	datas, total, err := a.Service.Query(pi, ps, sceneId)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}

	done(a.Ctx, map[string]interface{}{
		"list":  datas,
		"total": total,
	})
}

// GetBySceneId 根据场景ID获取历史记录列表
// GET /scene_his/{scene_id:string}
func (a *SceneHisController) GetBySceneId(sceneId string) {
	if sceneId == "" {
		badRequest(a.Ctx, errors.New("scene_id不能为空"))
		return
	}
	datas, err := a.Service.GetBySceneId(sceneId)
	if err != nil {
		responseError(a.Ctx, ErrDatabase, err.Error())
		return
	}
	done(a.Ctx, map[string]interface{}{
		"list":  datas,
		"total": len(datas),
	})
}
