package cygx

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/utils"
	"time"
)

// 问卷调查
type QuestionnaireController struct {
	controllers.BaseAuthController
}

// @Title 新增、修改问卷内容
// @Description  新增、修改问卷内容接口
// @Param	request	body cygx.AddCygxQuestionnaireReq true "type json string"
// @Success 200 {object} "保存成功"
// @router /questionnaire/preserveAndEdit [post]
func (this *QuestionnaireController) PreserveAndPublish() {
	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
	}

	var req cygx.AddCygxQuestionnaireReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	endTime := utils.StrDateToDate(req.EndTime) //时间字符串格式转时间格式
	questionnaireId := req.QuestionnaireId
	activityTypeId := req.ActivityTypeId
	content := req.Content
	maxChooseTotal := req.MaxChooseTotal
	listTheme := req.ListTheme

	activityTypeInfo, errType := cygx.GetActivityTypeDetailById(activityTypeId)
	if errType != nil {
		br.Msg = "请选择活动类型"
		br.ErrMsg = "获取活动类型信息失败,Err:" + errType.Error()
		return
	}
	item := new(cygx.CygxQuestionnaire)
	item.QuestionnaireId = req.QuestionnaireId
	item.ActivityTypeId = activityTypeId
	item.ActivityTypeName = activityTypeInfo.ActivityTypeName
	item.Content = content
	item.EndTime = endTime
	item.PublishTime = time.Now()
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	item.AdminId = sysUser.AdminId
	item.MaxChooseTotal = maxChooseTotal

	if questionnaireId == 0 {
		newId, err := cygx.AddCygxQuestionnaire(item, listTheme)
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = "保存失败,Err:" + err.Error()
			return
		}
		//投票发布时，给所有开通买方研选正式试用的客户，推送模板消息
		go cygxService.SendWxMsgCygxQuestionnaire(int(newId))

	} else {
		err = cygx.EditCygxQuestionnaire(item, listTheme)
		if err != nil {
			br.Msg = "保存失败"
			br.ErrMsg = "保存失败,Err:" + err.Error()
			return
		}
	}

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

// @Title 列表
// @Description 列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success Ret=200 {object} cygx.GetCygxQuestionnaireResp
// @router /questionnaire/list [get]
func (this *QuestionnaireController) 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
	}
	resp := new(cygx.GetCygxQuestionnaireResp)
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

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

	total, err := cygx.GetCygxQuestionnaireCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	condition += "	ORDER BY art.publish_time DESC  "
	list, err := cygx.GetCygxQuestionnaireList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	for _, v := range list {
		endTime := utils.StrTimeToTime(v.EndTime + " 23:59:59") //时间字符串格式转时间格式
		if endTime.Before(time.Now()) {
			v.State = "已截止"
		} else {
			v.State = "发布中"
		}
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 详情
// @Description 详情接口
// @Param   QuestionnaireId   query   int  true       "问卷ID"
// @Success Ret=200 {object} cygx.GetCygxTacticsTimeLineResp
// @router /questionnaire/detail [get]
func (this *QuestionnaireController) Detail() {
	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
	}
	resp := new(cygx.GetCygxQuestionnaireDetailResp)
	questionnaireId, _ := this.GetInt("QuestionnaireId")
	detail, err := cygx.GetCygxQuestionnaireDetail(questionnaireId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，GetCygxQuestionnaireDetail Err:" + err.Error()
		return
	}

	ListTheme, err := cygx.GetCygxQuestionnaireThemeListByQuestionnaireId(questionnaireId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，GetCygxQuestionnaireThemeListByQuestionnaireId Err:" + err.Error()
		return
	}
	detail.ListTheme = ListTheme
	resp.Detail = detail
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 投票结果
// @Description 投票结果接口
// @Param   QuestionnaireId   query   int  true       "问卷ID"
// @Success Ret=200 {object} cygx.CygxQuestionnaireVoteListResp
// @router /questionnaire/vote_detail [get]
func (this *QuestionnaireController) VoteDetail() {
	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
	}
	resp := new(cygx.CygxQuestionnaireVoteListResp)
	questionnaireId, _ := this.GetInt("QuestionnaireId")

	listTheme, err := cygx.GetCygxQuestionnaireThemeListByQuestionnaireId(questionnaireId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，GetCygxQuestionnaireThemeListByQuestionnaireId Err:" + err.Error()
		return
	}

	listVote, err := cygx.GetCygxCygxQuestionnaireVoteListByQuestionnaireId(questionnaireId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，GetCygxCygxQuestionnaireVoteListByQuestionnaireId Err:" + err.Error()
		return
	}
	//计算每个主题的投票数量
	mapVoteTotal := make(map[int]int)
	for _, v := range listVote {
		mapVoteTotal[v.QuestionnaireThemeId] += 1
	}

	for _, v := range listTheme {
		item := new(cygx.AddCygxQuestionnaireThemeReq)
		item.QuestionnaireThemeId = v.QuestionnaireThemeId
		item.ActivityTheme = v.ActivityTheme
		item.VoteTotal = mapVoteTotal[v.QuestionnaireThemeId]
		resp.List = append(resp.List, item)
	}
	if len(resp.List) == 0 {
		resp.List = make([]*cygx.AddCygxQuestionnaireThemeReq, 0)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 票数明细
// @Description 票数明细接口
// @Param   QuestionnaireThemeId   query   int  true       "主题问卷ID"
// @Success Ret=200 {object} cygx.GetCygxTacticsTimeLineResp
// @router /questionnaire/vote_list [get]
func (this *QuestionnaireController) VoteList() {
	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
	}
	resp := new(cygx.CygxCygxQuestionnaireVoteListResp)
	questionnaireThemeId, _ := this.GetInt("QuestionnaireThemeId")
	listVote, err := cygx.GetCygxQuestionnaireVoteListByQuestionnaireThemeId(questionnaireThemeId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，GetCygxQuestionnaireVoteListByQuestionnaireThemeId Err:" + err.Error()
		return
	}
	resp.List = listVote
	if len(resp.List) == 0 {
		resp.List = make([]*cygx.CygxQuestionnaireVoteResp, 0)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 其余主题投票结果
// @Description 其余主题投票结果接口
// @Param   QuestionnaireId   query   int  true       "问卷ID"
// @Success Ret=200 {object} cygx.CygxQuestionnaireVoteListResp
// @router /questionnaire/vote_other [get]
func (this *QuestionnaireController) VoteOther() {
	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
	}
	resp := new(cygx.CygxQuestionnaireVoteOtherThemeListResp)
	questionnaireId, _ := this.GetInt("QuestionnaireId")

	listOther, err := cygx.GetCygxQuestionnaireVoteOtherThemeListByQuestionnaireId(questionnaireId)
	if err != nil {
		br.Msg = "详情不存在"
		br.ErrMsg = "获取失败，GetCygxCygxQuestionnaireVoteListByQuestionnaireId Err:" + err.Error()
		return
	}
	resp.List = listOther
	if len(resp.List) == 0 {
		resp.List = make([]*cygx.CygxQuestionnaireVoteOtherThemeResp, 0)
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
