package yb

import (
	"encoding/json"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/yb"
	"hongze/hz_crm_api/models/yb/request"
	ybResp "hongze/hz_crm_api/models/yb/response"
	ybService "hongze/hz_crm_api/services/yb"
	"hongze/hz_crm_api/utils"
	"strings"
	"time"
)

// ActivityController 研报活动模块
type ActivityController struct {
	controllers.BaseAuthController
}

// List
// @Title 获取活动列表
// @Description 获取活动列表
// @Param   Keyword   query   string  false       "搜索关键字"
// @Param   ActivityTypeIds   query   string  false       "活动类别ids,多个用英文逗号分割"
// @Param   ActiveStatus   query   int8  false       "活动进行状态，枚举值：1：未开始；2：进行中；3：已结束"
// @Param   PublishStatus   query   int8  false       "活动发布状态，枚举值：-1：全部；0：未发布；1：已发布"
// @Param   StartDate   query   string  false       "活动开始日期，格式：2021-11-09"
// @Param   EndDate   query   string  false       "活动结束日期，格式：2021-11-10"
// @Success 200 {object} []yb.ListResp
// @router /activity/list [get]
func (this *ActivityController) 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
	}

	keyword := this.GetString("Keyword")
	activityTypeIds := this.GetString("ActivityTypeIds", "")
	activeStatus, _ := this.GetInt("ActiveStatus", 0)
	publishStatus, _ := this.GetInt("PublishStatus", 0)
	startDate := this.GetString("StartDate")
	endDate := this.GetString("EndDate")

	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)

	condition := ""
	pars := make([]interface{}, 0)

	//关键字
	if keyword != "" {
		condition += ` AND activity_name LIKE '%` + keyword + `%' `
	}
	//活动类别ids
	if activityTypeIds != "" {
		condition += ` AND activity_type_id IN (` + activityTypeIds + `)`
	}
	//活动开始与否状态
	order := ""
	if activeStatus > 0 {
		nowTime := time.Now().Format(utils.FormatDateTime)
		//1：未开始；2：进行中；3：已结束"
		switch activeStatus {
		case 1:
			condition += ` AND start_time > ? `
			pars = append(pars, nowTime)
		case 2:
			condition += ` AND start_time <= ? and end_time >= ? `
			pars = append(pars, nowTime, nowTime)
			order = " start_time DESC"
		case 3:
			condition += ` AND end_time < ? `
			pars = append(pars, nowTime)
			order = " start_time DESC"
		}
	}
	//活动是否发布
	if publishStatus >= 0 {
		condition += ` AND publish_status = ? `
		pars = append(pars, publishStatus)
	}
	//活动时间
	if startDate != "" && endDate != "" {
		condition += ` AND start_time >= ? and end_time <= ?`
		pars = append(pars, startDate+" 00:00:00", endDate+" 23:59:59")
	}

	// 获取所有的分类
	total, list, err := yb.GetList(condition, order, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取活动列表失败！"
		br.ErrMsg = "获取活动列表失败，Err:" + err.Error()
		return
	}

	if len(list) > 0 {
		activityIdList := make([]string, 0)
		for _, v := range list {
			activityIdList = append(activityIdList, fmt.Sprint(v.ActivityId))
		}
		//音频文件列表
		voiceList, tmpErr := yb.GetVoiceListByActivityIds(strings.Join(activityIdList, ","))
		if tmpErr != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取音频失败，Err:" + tmpErr.Error()
			return
		}
		activityVoiceMap := make(map[int][]*yb.ActivityVoice)
		for _, voice := range voiceList {
			tmpVoiceList, ok := activityVoiceMap[voice.ActivityId]
			if !ok {
				tmpVoiceList = make([]*yb.ActivityVoice, 0)
			}
			activityVoiceMap[voice.ActivityId] = append(tmpVoiceList, voice)
		}

		//海报文件列表
		posterList, tmpErr := yb.GetPosterListByActivityIds(strings.Join(activityIdList, ","))
		if tmpErr != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取海报失败，Err:" + tmpErr.Error()
			return
		}
		activityPosterMap := make(map[int][]*yb.ActivityPoster)
		for _, poster := range posterList {
			tmpPosterList, ok := activityPosterMap[poster.ActivityId]
			if !ok {
				tmpPosterList = make([]*yb.ActivityPoster, 0)
			}
			activityPosterMap[poster.ActivityId] = append(tmpPosterList, poster)
		}

		//权限文件列表
		permissionList, tmpErr := yb.GetPermissionListByActivityIds(strings.Join(activityIdList, ","))
		if tmpErr != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取海报失败，Err:" + tmpErr.Error()
			return
		}
		activityPermissionMap := make(map[int][]*yb.ActivityPermission)
		for _, activityPermission := range permissionList {
			tmpPermissionList, ok := activityPermissionMap[activityPermission.ActivityId]
			if !ok {
				tmpPermissionList = make([]*yb.ActivityPermission, 0)
			}
			activityPermissionMap[activityPermission.ActivityId] = append(tmpPermissionList, activityPermission)
		}

		for _, activity := range list {
			// 音频文件
			if voiceList, ok := activityVoiceMap[activity.ActivityId]; ok {
				activity.VoiceList = voiceList
			}
			//海报文件
			if posterList, ok := activityPosterMap[activity.ActivityId]; ok {
				activity.PosterList = posterList
			}
			//权限列表
			if permissionList, ok := activityPermissionMap[activity.ActivityId]; ok {
				activity.PermissionList = permissionList
			}
		}
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := ybResp.ListResp{
		List:   list,
		Paging: page,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Add
// @Title 新增活动
// @Description 新增活动接口
// @Param	request	body request.AddActivityReq true "type json string"
// @Success 200 {object} response.AddContractResp
// @router /activity/add [post]
func (this *ActivityController) Add() {
	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 request.AddActivityReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.ActivityTypeId <= 0 {
		br.Msg = "活动类型ID有误!"
		br.ErrMsg = "活动类型ID有误!"
		return
	}
	if req.ActivityName == "" {
		br.Msg = "活动标题不能为空!"
		br.ErrMsg = "活动标题不能为空!"
		return
	}
	if req.Speaker == "" {
		br.Msg = "活动主讲人不能为空!"
		br.ErrMsg = "活动主讲人不能为空!"
		return
	}
	startTime, err := time.ParseInLocation(utils.FormatDateTime, req.StartTime, time.Local)
	if err != nil {
		br.Msg = "活动开始日期转换失败!"
		br.ErrMsg = "活动开始日期转换失败，Err:" + err.Error()
		return
	}
	endTime, err := time.ParseInLocation(utils.FormatDateTime, req.EndTime, time.Local)
	if err != nil {
		br.Msg = "活动结束日期转换失败！"
		br.ErrMsg = "活动结束日期转换失败，Err:" + err.Error()
		return
	}
	/*now := time.Now()
	if now.After(startTime) {
		br.Msg = "活动时间不允许小于当前时间!"
		br.ErrMsg = "活动时间不允许小于当前时间!"
		return
	}*/
	if startTime.After(endTime) {
		br.Msg = "活动结束时间不允许小于开始时间!"
		br.ErrMsg = "活动结束时间不允许小于开始时间!"
		return
	}
	allowEndTime := startTime.Add(30 * time.Minute)
	if allowEndTime.After(endTime) {
		br.Msg = "活动结束时间至少要在开始时间半个小时之后!"
		br.ErrMsg = "活动结束时间至少要在开始时间半个小时之后!"
		return
	}

	activityInfo, err := ybService.AddActivity(req, sysUser.AdminId)
	if err != nil {
		br.Msg = "保存活动失败！"
		br.ErrMsg = "保存活动失败，Err:" + err.Error()
		return
	}
	msg := "添加成功"

	br.Ret = 200
	br.Success = true
	br.Msg = msg
	br.Data = ybResp.AddActivityResp{
		ActivityId: activityInfo.ActivityId,
	}
}

// Edit
// @Title 编辑活动
// @Description 编辑活动接口
// @Param	request	body request.EditActivityReq true "type json string"
// @Success 200 {object} 保存成功
// @router /activity/edit [post]
func (this *ActivityController) Edit() {
	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 request.EditActivityReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ActivityId <= 0 {
		br.Msg = "活动ID异常！"
		br.ErrMsg = "活动ID异常"
		return
	}

	_, err, errMsg := ybService.EditActivity(req)
	if err != nil {
		br.Msg = "保存活动失败！" + errMsg
		br.ErrMsg = "保存活动失败，Err:" + err.Error()
		return
	}
	msg := "保存成功"

	br.Ret = 200
	br.Success = true
	br.Msg = msg
}

// Publish
// @Title 发布活动
// @Description 发布活动接口
// @Param	request	body request.PublishActivityReq true "type json string"
// @Success 200 {object} 发布成功
// @router /activity/publish [post]
func (this *ActivityController) Publish() {
	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 request.PublishActivityReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ActivityId <= 0 {
		br.Msg = "活动ID异常！"
		br.ErrMsg = "活动ID异常"
		return
	}
	_, err, errMsg := ybService.PublishActivity(req.ActivityId)
	if err != nil {
		br.Msg = "发布活动失败！" + errMsg
		br.ErrMsg = "发布活动失败，Err:" + err.Error()
		return
	}
	msg := "发布成功"

	br.Ret = 200
	br.Success = true
	br.Msg = msg
}

// UnPublish
// @Title 取消发布活动
// @Description 取消发布活动接口
// @Param	request	body request.PublishActivityReq true "type json string"
// @Success 200 {object} 取消发布成功
// @router /activity/unpublish [post]
func (this *ActivityController) UnPublish() {
	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 request.PublishActivityReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ActivityId <= 0 {
		br.Msg = "活动ID异常！"
		br.ErrMsg = "活动ID异常"
		return
	}
	_, err, errMsg := ybService.UnPublishActivity(req.ActivityId)
	if err != nil {
		br.Msg = "取消发布活动失败！" + errMsg
		br.ErrMsg = "取消发布活动失败，Err:" + err.Error()
		return
	}
	msg := "取消发布成功"

	br.Ret = 200
	br.Success = true
	br.Msg = msg
}

// DelPublish
// @Title 删除活动
// @Description 删除活动接口
// @Param	request	body request.PublishActivityReq true "type json string"
// @Success 200 {object} 删除成功
// @router /activity/del_publish [post]
func (this *ActivityController) DelPublish() {
	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 request.PublishActivityReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.ActivityId <= 0 {
		br.Msg = "活动ID异常！"
		br.ErrMsg = "活动ID异常"
		return
	}
	_, err, errMsg := ybService.DelActivity(req.ActivityId)
	if err != nil {
		br.Msg = "删除活动失败！" + errMsg
		br.ErrMsg = "删除活动失败，Err:" + err.Error()
		return
	}
	msg := "删除成功"

	br.Ret = 200
	br.Success = true
	br.Msg = msg
}

// ReportList
// @Title 获取报告列表
// @Description 获取报告列表
// @Param   Keyword   query   string  false       "搜索关键字"
// @Param   StartDate   query   string  false       "开始日期"
// @Param   EndDate   query   string  false       "结束日期"
// @Param   ReportType   query   string  false       "报告类型，枚举值：day,week,two_week,month,other"
// @Success 200 {object} yb.ResearchReportListResp
// @router /report/list [get]
func (this *ActivityController) ReportList() {
	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
	}
	keyword := this.GetString("Keyword")
	//startDate := this.GetString("StartDate")
	//endDate := this.GetString("EndDate")
	reportType := this.GetString("ReportType")
	classifyId, _ := this.GetInt("ClassifyId")

	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{}

	// 报告类型: 晨报, 周报, 其他电话会报告
	reportTypeArr := []string{"day", "week", "tel"}
	if !utils.InArrayByStr(reportTypeArr, reportType) {
		br.Msg = "报告类型有误"
		return
	}
	if reportType == "tel" && classifyId == 0 {
		br.Msg = "请选择报告类型"
		return
	}

	total := 0
	list := make([]*models.ResearchReportList, 0)

	// 晨报-查询老报告
	//if reportType == "day" {
	//	if keyword != `` {
	//		condition += ` and research_report_name like '%` + keyword + `%' `
	//	}
	//	if startDate != `` {
	//		condition += ` and created_time >=  ? `
	//		pars = append(pars, startDate+" 00:00:00")
	//	}
	//	if endDate != `` {
	//		condition += ` and created_time <=  ? `
	//		pars = append(pars, endDate+" 23:59:59")
	//	}
	//	if reportType != `` {
	//		condition += ` and type =  ? `
	//		pars = append(pars, reportType)
	//	}
	//	oldTotal, reportList, err := models.GetResearchReportList(condition, pars, startSize, pageSize)
	//	if err != nil {
	//		br.Msg = "获取报告列表失败！"
	//		br.ErrMsg = "获取报告列表失败，Err:" + err.Error()
	//		return
	//	}
	//	total = oldTotal
	//
	//	//环境不同，阅读报告的地址不同
	//	linkUrl := `https://details.hzinsights.com/ficcReportDetail?research_report_id=`
	//	if utils.RunMode == `debug` {
	//		linkUrl = `http://advisoryadmin.brilliantstart.cn/xcx_h5/ficcReportDetail?research_report_id=`
	//	}
	//	for _, report := range reportList {
	//		report.LinkUrl = fmt.Sprint(linkUrl, report.ResearchReportId)
	//	}
	//	list = reportList
	//}

	if keyword != "" {
		condition += ` AND title LIKE '%` + keyword + `%' `
	}
	if reportType == "week" || reportType == "day" {
		condition += ` AND state = 2 AND has_chapter = 1 AND chapter_type = ? AND old_report_id = 0 `
		pars = append(pars, reportType)
	} else {
		// 其他电话会报告暂时支持同步过来的报告
		condition += ` AND state = 2`
		// 此处仅查询二级分类中含电话会的报告, 一级分类可能含非电话会二级分类, 所以不用一级分类作为报告的查询条件
		var telCond, telOrder string
		var telPars []interface{}
		telCond += ` AND parent_id = ? AND has_teleconference = 1`
		telPars = append(telPars, classifyId)
		telList, e := models.GetClassifyByCondition(telCond, telOrder, telPars)
		if e != nil {
			br.Msg = "获取报告列表失败"
			br.ErrMsg = "获取其他报告电话会分类失败, Err: " + e.Error()
			return
		}
		telClassifyIds := make([]int, 0)
		for i := range telList {
			telClassifyIds = append(telClassifyIds, telList[i].Id)
		}
		if len(telClassifyIds) > 0 {
			condition += ` AND classify_id_second IN (` + utils.GetOrmInReplace(len(telClassifyIds)) + `)`
			pars = append(pars, telClassifyIds)
		} else {
			// 无电话会二级分类理应查不出任何数据
			condition += ` AND 1 = 2`
		}
	}

	newTotal, reportList, e := models.GetPageReportList(condition, pars, startSize, pageSize)
	if e != nil {
		br.Msg = "获取新报告列表失败"
		br.ErrMsg = "获取新报告列表失败, Err:" + e.Error()
		return
	}
	total = newTotal

	linkUrl := `https://details.hzinsights.com/xcx_h5/hzyb/report/detail?reportId=`
	if utils.RunMode == `debug` {
		linkUrl = `http://xcxh5test.hzinsights.com/xcx_h5/hzyb/report/detail?reportId=`
	}
	for _, v := range reportList {
		reportDate, e := time.Parse(utils.FormatDateTime, v.PublishTime)
		if e != nil {
			return
		}
		item := &models.ResearchReportList{
			ResearchReportId:   v.Id,
			ResearchReportName: v.Title,
			ResearchReportDate: reportDate,
			Type:               reportType,
			Author:             v.Author,
			ReportVariety:      v.ClassifyNameFirst,
			IsSendedMsg:        int8(v.MsgIsSend),
			Periods:            v.Stage,
			Status:             "report",
			Enabled:            1,
			CreatedTime:        v.CreateTime,
			LastUpdatedTime:    v.ModifyTime,
			LinkUrl:            fmt.Sprint(linkUrl, v.Id),
		}
		list = append(list, item)
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := ybResp.ResearchReportListResp{
		List:   list,
		Paging: page,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Detail
// @Title 活动详情
// @Description 活动详情
// @Param	activityId	query	int  true	"活动ID"
// @Success 200 {object} yb.Activity 获取成功
// @router /activity/detail [get]
func (this *ActivityController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	activityId, _ := this.GetInt("activityId", 0)
	if activityId <= 0 {
		br.Msg = "活动ID异常！"
		br.ErrMsg = "活动ID异常"
		return
	}

	activity, err := yb.GetById(activityId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "活动信息不存在"
			br.ErrMsg = "活动信息不存在"
			return
		}
		br.Msg = "活动详情获取失败"
		br.ErrMsg = "活动详情获取失败，Err：" + err.Error()
		return
	}
	posterList, err := yb.GetPosterListByActivityId(activityId)
	if err != nil {
		br.Msg = "活动海报列表获取失败"
		br.ErrMsg = "活动海报列表获取失败，Err：" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = ybResp.ActivityDetailResp{
		Activity: activity,
		Poster:   posterList,
	}
}
