package cases

import (
	"errors"
	"spaceofcheng/services/models"
	"spaceofcheng/services/models/cases"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/models/system"
	"spaceofcheng/services/service"
	"spaceofcheng/services/utils"

	"github.com/astaxie/beego"
)

// CaseServ 系统处理
type CaseServ struct {
	ctx     *utils.Context
	dao     *cases.CaseDAO
	userdao *system.UserDAO
}

// NewCaseServ 初始化
func NewCaseServ(ctx *utils.Context) *CaseServ {
	return &CaseServ{
		ctx:     ctx,
		dao:     cases.NewCaseDAO(ctx),
		userdao: system.NewUserDAO(ctx),
	}
}

// GetCases 获取案场列表
func (s *CaseServ) GetCases(caseids, casename string, page, pageSize int) (map[string]interface{}, error) {
	if pageSize == 0 {
		pageSize = service.PAGENUM
	}
	if page == 0 {
		page = 1
	}
	cases, err := s.dao.GetCaseList(caseids, casename, page, pageSize)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	total, err := s.dao.GetCaseCount(caseids, casename)
	if err != nil {
		beego.Error(err)
		return nil, err
	}

	return map[string]interface{}{
		"list":     cases,
		"pagesize": pageSize,
		"pagenum":  total,
		"page":     page,
	}, err
}

// GetCaseByID 根据案场id获取案场
func (s *CaseServ) GetCaseByID(caseid string) (*model.SysCase, error) {
	caseinfo, err := s.dao.GetCaseByID(caseid)
	return caseinfo, err
}

// SaveCase 保存案场
func (s *CaseServ) SaveCase(caseinfo model.SysCase) (*model.SysCase, error) {
	var newInfo *model.SysCase
	var err error
	if caseinfo.CaseName == "" {
		return nil, utils.LogError("案场名称不能为空！")
	}
	if caseinfo.Coordinate == "" {
		return nil, utils.LogError("案场经纬度不能为空！")
	}

	if caseinfo.CaseId == "" {
		newInfo, err = s.dao.AddCase(caseinfo)
		if err != nil {
			return nil, err
		}
		// 新增之后保存用户对应案场
		var userCase = model.SysUserCase{
			CaseId:    newInfo.CaseId,
			UserId:    newInfo.CreateUser,
			CaseName:  newInfo.CaseName,
			IsBelong:  0,
			IsCreated: 1,
		}
		err = s.userdao.SaveUserCase(userCase)
	} else {
		err = s.dao.UpdateCase(caseinfo)
		newInfo = &caseinfo
	}
	return newInfo, err
}

// DelCase 删除案场
func (s *CaseServ) DelCase(caseid string) error {
	err := s.dao.DelCase(caseid)
	return err
}

// GetAllCasesAndSales 获取所有案场
func (s *CaseServ) GetAllCasesAndSales(org string) (map[string]interface{}, error) {
	cs, err := s.dao.GetCaseByOrg(org)
	if err != nil {
		utils.LogError("获取案场列表失败: " + err.Error())
		return nil, errors.New("获取案场列表失败")
	}

	csIDs := []string{}
	for _, c := range cs {
		csIDs = append(csIDs, c.CaseId)
	}

	users, err := s.dao.GetCaseUserByType(csIDs, models.USERTYPE_SALES)
	if err != nil {
		utils.LogError("获取案场销售失败: " + err.Error())
		return nil, errors.New("获取案场销售失败")
	}

	return map[string]interface{}{
		"cases": cs,
		"sales": users,
	}, nil
}
