package cygx

import (
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/utils"
	"strings"
)

// 优化建议
type AdviceController struct {
	controllers.BaseAuthController
}

// @Title 优化建议列表
// @Description 优化建议列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   KeyWord   query   string  true       "搜索关键词"
// @Success 200 {object} cygx.AdviceListResp
// @router /advice/list [get]
func (this *AdviceController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyWord := this.GetString("KeyWord")
	keyWord = strings.Trim(keyWord, " ")
	keyWord = strings.Replace(keyWord, "'", "", -1)
	var total int

	resp := new(cygx.AdviceListResp)

	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)
	var condition string
	var pars []interface{}

	if keyWord != "" {
		condition += ` AND (a.mobile LIKE '%` + keyWord + `%' OR a.email LIKE '%` + keyWord + `%' OR a.user_real_name LIKE '%` + keyWord + `%') `
	}

	total, err := cygx.GetAdviceListCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}

	list, err := cygx.GetAdviceList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	if list == nil {
		list = make([]*cygx.CygxAdvice, 0)
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
