package cases

import (
	"errors"
	"spaceofcheng/services/controllers"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/service/cases"
)

// CaseController 信息
type CaseController struct {
	dao *cases.CaseServ
	controllers.BaseController
}

// Constructor 初始化 Controller
// @Title Constructor
// @Description 初始化 Controller, 系统自动调用
func (c *CaseController) Constructor() {
	c.dao = cases.NewCaseServ(c.Context)
}

// GetCaseList 获取案场列表
func (c *CaseController) GetCaseList() {
	cases := c.Context.Get("cases").([]model.SysUserCase)
	caseIDs := c.GetCaseIDs(cases)
	page, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("pagesize")
	casename := c.GetString("name")

	list, err := c.dao.GetCases(caseIDs, casename, page, pageSize)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON(list)
}

// GetCaseByID 根据ID获取案场信息
func (c *CaseController) GetCaseByID() {
	caseid := c.GetString(":id")
	info, err := c.dao.GetCaseByID(caseid)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON(info)
}

// SaveCase 保存案场信息
func (c *CaseController) SaveCase() {
	info := model.SysCase{}
	if err := c.ParseForm(&info); err != nil {
		c.ResponseError(err)
	}
	newinfo, err := c.dao.SaveCase(info)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON(newinfo)
}

//DelCase 删除案场信息
func (c *CaseController) DelCase() {
	caseid := c.GetString(":id")
	err := c.dao.DelCase(caseid)
	if err != nil {
		c.ResponseError(err)
	}
	c.ResponseJSON("删除成功！")
}

// GetOrgCases 获取机构案场
func (c *CaseController) GetOrgCases() {
	org := c.GetString("org")
	if org == "" {
		c.ResponseError(errors.New("未确定机构"))
	}

	res, err := c.dao.GetAllCasesAndSales(org)
	if err != nil {
		c.ResponseError(err)
	}

	c.ResponseJSON(res)
}
