package controllers

import (
	"encoding/json"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/services"
	"strings"
	"time"
)

type ConfigController struct {
	BaseAuthController
}

type BaseConfigController struct {
	BaseCommonController
}

// @Title 获取搜索推荐词
// @Description 获取搜索推荐词
// @Success 200 {object} models.ConfigResp
// @router /detail [get]
func (this *ConfigController) BrowseHistoryList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	resp := new(models.ConfigResp)
	detail := new(models.CygxConfig)
	//configCode := "hot_search"
	//detail, err := models.GetConfigByCode(configCode)
	hotSearch, err := models.GetHotSearch()
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	chartList, err := models.GetChartListConfig()
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
		return
	}
	for _, v := range chartList {
		item := new(models.KeyWord)
		item.KeyWord = v.Title
		resp.List = append(resp.List, item)
	}
	var condition string
	var pars []interface{}
	currentTime := time.Now()
	starTime := currentTime.AddDate(0, 0, -8).Format("2006-01-02") + " 00:00:00"
	endTime := currentTime.AddDate(0, 0, -1).Format("2006-01-02") + " 23:59:59"
	condition += ` AND create_time < ` + "'" + endTime + "'" + `AND create_time > ` + "'" + starTime + "'"
	hotList, err := models.GetSearchKeyWordTop(condition, pars)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取用户信息失败,Err:" + err.Error()
		return
	}
	for _, v := range hotList {
		item := new(models.KeyWord)
		item.KeyWord = v.KeyWord
		resp.ListHot = append(resp.ListHot, item)
	}
	detail.ConfigValue = hotSearch
	resp.Item = detail
	br.Msg = "获取成功！"
	br.Ret = 200
	br.Success = true
	br.Data = resp
}

// @Title 页面访问统计
// @Description 上传页面访问统计
// @Param	request	body models.CygxPageHistoryRecordRep true "type json string"
// @Success Ret=200 新增成功
// @router /pageHistory [post]
func (this *ConfigController) PageHistory() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req models.CygxPageHistoryRecordRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	pageType := req.PageType
	var havePageType bool
	PageType := []string{"Summary", "SummarySearch", "Report", "ReportSearch", "IndustryList", "Activit", "ActivitSearch", "ActivitParticulars", "ReportParticulars", "MySchedule", "LabelMore", "ArticleCopy"}
	for _, v := range PageType {
		if pageType == v {
			havePageType = true
		}
	}
	if !havePageType {
		br.Msg = "新增失败"
		br.ErrMsg = "PageType参数类型错误：" + pageType
		return
	}
	item := new(models.CygxPageHistoryRecord)
	item.UserId = user.UserId
	item.CreateTime = time.Now()
	item.Mobile = user.Mobile
	item.Email = user.Email
	item.CompanyId = user.CompanyId
	item.CompanyName = user.CompanyName
	item.DetailId = req.DetailId
	item.ChartPermissionId = req.ChartPermissionId
	item.IndustrialManagementId = req.IndustrialManagementId
	item.PageType = req.PageType
	_, err = models.AddCygxPageHistoryRecord(item)
	if err != nil {
		br.Msg = "新增访问记录失败"
		br.ErrMsg = "新增访问记录失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "新增成功"
}

// @Title 获取研选说明
// @Description 获取研选说明接口
// @Success 200 {object} models.ConfigResp
// @router /descriptionOfResearch [get]
func (this *ConfigController) DescriptionOfResearch() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	configCode := "description_of_research"
	detail, err := models.GetConfigByCode(configCode)
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	resp := new(models.ConfigResp)
	resp.Item = detail
	br.Msg = "获取成功！"
	br.Ret = 200
	br.Success = true
	br.Data = resp
}

// @Title 获取搜索推荐词（无需token）
// @Description 获取搜索推荐词（无需token）
// @Success 200 {object} models.ConfigResp
// @router /detailPublic [get]
func (this *BaseConfigController) HotDetail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	detail := new(models.CygxConfig)
	hotSearch, err := models.GetHotSearch()
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	detail.ConfigValue = hotSearch
	resp := new(models.ConfigResp)
	resp.Item = detail
	br.Msg = "获取成功！"
	br.Ret = 200
	br.Success = true
	br.Data = resp
}

// @Title 用户搜索记录统计
// @Description 用户搜索记录统计
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Success Ret=200 新增成功
// @router /user/search/keyWordLog [post]
func (this *ConfigController) KeyWordLog() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req models.CygxSearchKeyWordLogRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	keyWord := req.KeyWord
	if keyWord == "" {
		br.Msg = "搜索内容不能为空"
		return
	}
	user := this.User
	if user == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	if keyWord != "" {
		go services.AddUserSearchLog(user, keyWord, 1)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "新增成功"
}

// @Title 关于我们浏览记录
// @Description 关于我们浏览记录接口
// @Success 200
// @router /aboutUs/addHistory [post]
func (this *ConfigController) AboutUsAdd() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请重新登录"
		br.Ret = 408
		return
	}
	go services.AddCygxAboutUsVideoHistory(user)

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功！"
}

// @Title 买方研选产品介绍（无需token）
// @Description 买方研选产品介绍接口（无需token）
// @Success 200 {object} models.ConfigImgListResp
// @router /research/introduce [get]
func (this *BaseConfigController) ResearchIntroduce() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	conf, err := models.GetConfigByCode("research_introduce_img_url")
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "买方研选产品介绍信息失败，Err:" + err.Error()
		return
	}
	if conf.ConfigValue == "" {
		br.Msg = "获取失败"
		br.ErrMsg = "买方研选产品介绍信息失败"
		return
	}
	list := new(*models.ConfigImgListResp)
	if err = json.Unmarshal([]byte(conf.ConfigValue), &list); err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "买方研选产品介绍信配置值解析失败, Err: " + err.Error()
		return
	}
	br.Msg = "获取成功！"
	br.Ret = 200
	br.Success = true
	br.Data = list
}

// @Title 买方研选报价单（无需token）
// @Description 买方研选报价单（无需token）
// @Success 200 {object} models.ConfigImgListResp
// @router /research/quotation [get]
func (this *BaseConfigController) ResearchQuotation() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	conf, err := models.GetConfigByCode("research_quotation_img_url")
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "买方研选产品介绍信息失败，Err:" + err.Error()
		return
	}
	if conf.ConfigValue == "" {
		br.Msg = "获取失败"
		br.ErrMsg = "买方研选产品介绍信息失败"
		return
	}
	list := new(*models.ConfigImgListResp)
	if err = json.Unmarshal([]byte(conf.ConfigValue), &list); err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "买方研选产品介绍信配置值解析失败, Err: " + err.Error()
		return
	}
	br.Msg = "获取成功！"
	br.Ret = 200
	br.Success = true
	br.Data = list
}

// @Title 买方研选升级新资源海报（无需token）
// @Description 买方研选升级新资源海报（无需token）
// @Success 200 {object} models.ConfigImgListResp
// @router /research/hb [get]
func (this *BaseConfigController) ResearchHb() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	detail, err := models.GetConfigByCode("research_hb_img_url")
	if err != nil {
		br.Msg = "获取数据失败"
		br.ErrMsg = "买方研选升级新资源海报信息失败，Err:" + err.Error()
		return
	}
	resp := new(models.ConfigImgHbResp)
	list := strings.Split(detail.ConfigValue, "{|}")
	if len(list) == 0 {
		list = make([]string, 0)
	}
	resp.HbImg = list[0]
	resp.ButtonImg = list[len(list)-1]
	br.Msg = "获取成功！"
	br.Ret = 200
	br.Success = true
	br.Data = resp
}
