package controllers

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/services"
	"hongze/hongze_cygx/utils"
	"strconv"
	"strings"
	"time"
)

type ChartController struct {
	BaseAuthController
}

type BaseChartController struct {
	BaseCommonController
}

// @Title 图表标签分类
// @Description 图表标签分类接口
// @Success 200 {object} models.ChartPtagResp
// @router /patg [get]
func (this *BaseChartController) Patg() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	list, err := services.GetChartPtagByApi()
	if err != nil {
		br.Msg = "获取图表分类失败！"
		br.ErrMsg = "获取图表分类失败 Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// @Title 我的收藏列表
// @Description 我的收藏列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success 200 {object} models.HomeChartListItem
// @router /my/collection [get]
func (this *ChartController) Collection() {
	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
	}
	mobile := user.Mobile
	uid := user.UserId
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	resp := new(models.HomeChartListItem)
	if mobile == "" {
		page := paging.GetPaging(currentIndex, pageSize, 0)
		resp.Paging = page
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		resp.IsBindingMobile = false
		return
	} else {
		resp.IsBindingMobile = true
	}
	var listCollection []*models.HomeChartListResp
	var total int
	//var err error
	chartUserTokenByMobile, _ := services.GetUserTokenByMobile(mobile)
	if chartUserTokenByMobile != "" {
		list, err, _ := services.GetChartCollectionByApi(mobile, 9999, 0)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取我的收藏失败！"
			br.ErrMsg = "获取图表分类失败 Err:" + err.Error()
			return
		}
		var chartIds string
		var condition string
		var pars []interface{}
		if len(list) > 0 {
			for _, v := range list {
				chartIds += strconv.Itoa(v.ChartId) + ","
			}
		}
		chartIds = strings.TrimRight(chartIds, ",")
		if chartIds == "" {
			chartIds = "0"
		}
		condition = ` AND a.chart_id IN (` + chartIds + `) `
		total, err = models.GetChartCollentCount(condition, pars)
		if err != nil {
			br.Msg = "获取信息失败"
			br.Msg = "获取帖子总数失败，Err:" + err.Error()
			return
		}
		listCollection, err = models.GetChartListCollection(chartIds, uid, startSize, pageSize)
		if err != nil {
			br.Msg = "获取信息失败"
			br.Msg = "获取信息失败，GetChartListCollection Err:" + err.Error()
			return
		}
	} else {
		var err error
		total, err = models.GetChartCountByUser(uid)
		if err != nil {
			br.Msg = "获取信息失败"
			br.Msg = "获取总数失败，Err:" + err.Error()
			return
		}
		listCollection, err = models.GetChartListCollectionWithCygx(uid, startSize, pageSize)
		if err != nil {
			br.Msg = "获取信息失败"
			br.Msg = "获取信息失败，GetChartListCollection Err:" + err.Error()
			return
		}
	}
	for k, v := range listCollection {
		if v.NumTop > 0 {
			listCollection[k].IsTop = true
		}
		listCollection[k].Source = 2
		if v.PtagName != "" {
			listCollection[k].CtagNamePc = v.PtagName
		}
		if v.CtagName != "" {
			listCollection[k].CtagNamePc += "," + v.CtagName
		}
		if v.PtagNameTwo != "" {
			listCollection[k].CtagNamePc += "," + v.PtagNameTwo
		}
		if v.CtagNameTwo != "" {
			listCollection[k].CtagNamePc += "," + v.CtagNameTwo
		}
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.List = listCollection
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 图表详情
// @Description 我的收藏接口
// @Param   ChartId   query   int  true       "图表ID"
// @Success 200 {object} models.CygxChartDetail
// @router /detail [get]
func (this *ChartController) Detail() {
	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
	}
	mobile := user.Mobile
	if mobile == "" {
		br.Msg = "请绑定手机号！"
		return
	}
	chartId, _ := this.GetInt("ChartId")
	if chartId <= 0 {
		br.Msg = "图表信息不存在！"
		return
	}
	detail, err := models.GetChartDetailById(chartId, user.UserId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取信息失败,Err:" + err.Error()
		return
	}
	chartUserTokenByMobile, _ := services.GetUserTokenByMobile(mobile)
	if chartUserTokenByMobile != "" {
		GetIsCollectionChart, err := services.GetIsCollectionChart(mobile, chartId)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取三方关注信息失败,Err:" + err.Error()
			return
		}
		detail.IsCollection = GetIsCollectionChart
		detail.HttpUrl = utils.CHART_INFO_HTTP_URL + strconv.Itoa(chartId) + "?token=" + chartUserTokenByMobile
		//if !detail.IsCollection {
		//	err = models.RemoveChartCollect(user.UserId, chartId)
		//}
	} else {
		if detail.CollectionNum > 0 {
			detail.IsCollection = true
		}
	}
	go services.ServerAddCygxChartRecord(user, chartId)                  //用户阅读图表，添加浏览记录
	go services.KeyChartWxUserRaiLabelRedisAdd(chartId, user.UserId, "") //用户阅读图表，添加浏览记录
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = detail
}

// @Title 收藏、取消收藏
// @Description 收藏、取消收藏
// @Param	request	body models.ChartCollectReq true "type json string"
// @Success 200 {object} models.FontsCollectResp
// @router /collect [post]
func (this *ChartController) ChartCollect() {
	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
	}
	uid := user.UserId
	mobile := user.Mobile
	var req models.ChartCollectReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	resp := new(models.ArticleCollectResp)
	count, err := models.GetChartCountByUserId(uid, req.ChartId)
	if err != nil {
		br.Msg = "获取数据失败！"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	chartUserTokenByMobile, _ := services.GetUserTokenByMobile(mobile)
	if chartUserTokenByMobile != "" {
		GetIsCollectionChart, err := services.GetIsCollectionChart(mobile, req.ChartId)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取三方关注信息失败,Err:" + err.Error()
			return
		}
		if !GetIsCollectionChart {
			if count <= 0 {
				item := new(models.CygxChartCollect)
				item.ChartId = req.ChartId
				item.UserId = uid
				item.RealName = user.RealName
				item.CreateTime = time.Now()
				item.Mobile = user.Mobile
				item.Email = user.Email
				item.CompanyId = user.CompanyId
				item.CompanyName = user.CompanyName
				_, err = models.AddCygxChartCollect(item)
				if err != nil {
					br.Msg = "收藏失败"
					br.ErrMsg = "收藏失败,Err:" + err.Error()
					return
				}
			}
			br.Msg = "收藏成功"
			resp.Status = 1
		} else {
			err = models.RemoveChartCollect(uid, req.ChartId)
			if err != nil {
				br.Msg = "取消收藏失败"
				br.ErrMsg = "取消收藏失败,Err:" + err.Error()
				return
			}
			br.Msg = "已取消收藏"
			resp.Status = 2
		}
		//如果存在就取消收藏、反之添加收藏
		if GetIsCollectionChart {
			go services.DeleteCollectionChart(mobile, req.ChartId)
		} else {
			go services.AddCollectionChart(mobile, req.ChartId)
		}
	} else {
		if count <= 0 {
			item := new(models.CygxChartCollect)
			item.ChartId = req.ChartId
			item.UserId = uid
			item.RealName = user.RealName
			item.CreateTime = time.Now()
			item.Mobile = user.Mobile
			item.Email = user.Email
			item.CompanyId = user.CompanyId
			item.CompanyName = user.CompanyName
			_, err = models.AddCygxChartCollect(item)
			if err != nil {
				br.Msg = "收藏失败"
				br.ErrMsg = "收藏失败,Err:" + err.Error()
				return
			}
			br.Msg = "收藏成功"
			resp.Status = 1
		} else {
			err = models.RemoveChartCollect(uid, req.ChartId)
			if err != nil {
				br.Msg = "取消收藏失败"
				br.ErrMsg = "取消收藏失败,Err:" + err.Error()
				return
			}
			br.Msg = "已取消收藏"
			resp.Status = 2
		}
	}
	br.Ret = 200
	br.Success = true
	br.Data = resp
}

// @Title 置顶、取消置顶
// @Description  置顶、取消置顶
// @Param	request	body models.ChartCollectReq true "type json string"
// @Success 200 {object} models.FontsCollectResp
// @router /top [post]
func (this *ChartController) ChartTop() {
	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
	}
	uid := user.UserId
	var req models.ChartCollectReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	count, err := models.GetChartTopCountByUserId(uid, req.ChartId)
	if err != nil {
		br.Msg = "获取数据失败！"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	resp := new(models.ArticleCollectResp)
	if count <= 0 {
		item := new(models.CygxChartTop)
		item.ChartId = req.ChartId
		item.UserId = uid
		item.RealName = user.RealName
		item.CreateTime = time.Now()
		item.Mobile = user.Mobile
		item.Email = user.Email
		item.CompanyId = user.CompanyId
		item.CompanyName = user.CompanyName
		_, err = models.AddCygxChartTop(item)
		if err != nil {
			br.Msg = "置顶失败"
			br.ErrMsg = "收置顶失败,Err:" + err.Error()
			return
		}
		br.Msg = "置顶成功"
		resp.Status = 1
	} else {
		err = models.RemoveChartTop(uid, req.ChartId)
		if err != nil {
			br.Msg = "取消置顶失败"
			br.ErrMsg = "取消置顶失败,Err:" + err.Error()
			return
		}
		br.Msg = "已取消置顶"
		resp.Status = 2
	}
	br.Ret = 200
	br.Success = true
	br.Data = resp
}

// @Title 季度列表
// @Description 季度列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success 200 {object} models.HomeChartListItem
// @router /jidu [get]
func (this *ChartController) Jidu() {
	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
	}
	mobile := user.Mobile
	uid := user.UserId
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = paging.StartIndex(currentIndex, pageSize)

	resp := new(models.HomeChartListItem)
	if mobile == "" {
		page := paging.GetPaging(currentIndex, pageSize, 0)
		resp.Paging = page
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		br.Data = resp
		resp.IsBindingMobile = false
		return
	} else {
		resp.IsBindingMobile = true
	}
	var listCollection []*models.HomeChartListResp
	var total int
	var err error
	chartUserTokenByMobile, _ := services.GetUserTokenByMobile(mobile)
	chartIds := "5424,5587,5423,5589"
	if chartUserTokenByMobile != "" {
		var condition string
		var pars []interface{}
		condition = ` AND a.chart_id IN (` + chartIds + `) `
		total, err = models.GetChartCollentCount(condition, pars)
		if err != nil {
			br.Msg = "获取信息失败"
			br.Msg = "获取帖子总数失败，Err:" + err.Error()
			return
		}
		listCollection, err = models.GetChartListCollection(chartIds, uid, startSize, pageSize)
		if err != nil {
			br.Msg = "获取信息失败"
			br.Msg = "获取信息失败，GetChartListCollection Err:" + err.Error()
			return
		}
	} else {
		total, err = models.GetChartCountByUser(uid)
		if err != nil {
			br.Msg = "获取信息失败"
			br.Msg = "获取总数失败，Err:" + err.Error()
			return
		}
		listCollection, err = models.GetChartListCollectionWithCygx(uid, startSize, pageSize)
		if err != nil {
			br.Msg = "获取信息失败"
			br.Msg = "获取信息失败，GetChartListCollection Err:" + err.Error()
			return
		}
	}
	for k, v := range listCollection {
		if v.NumTop > 0 {
			listCollection[k].IsTop = true
		}
		listCollection[k].Source = 2
		if v.PtagName != "" {
			listCollection[k].CtagNamePc = v.PtagName
		}
		if v.CtagName != "" {
			listCollection[k].CtagNamePc += "," + v.CtagName
		}
		if v.PtagNameTwo != "" {
			listCollection[k].CtagNamePc += "," + v.PtagNameTwo
		}
		if v.CtagNameTwo != "" {
			listCollection[k].CtagNamePc += "," + v.CtagNameTwo
		}
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.List = listCollection
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
