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"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

type ThsSendController struct {
	controllers.BaseAuthController
}

// @Title 推送客群待发送列表
// @Description 推送客群待发送列表
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   Title   query   string  true       "推送标题"
// @Param   ReportType   query   string  true       "内容类型"
// @Param   CreateTimeStart   query   string  true       "创建时间起始时间"
// @Param   CreateTimeEnd   query   string  true       "创建时间截止时间"
// @Param   PushTimeStart   query   string  true       "待推送时间起始时间"
// @Param   PushTimeEnd   query   string  true       "待推送时间截止时间"
// @Success 200 {object} models.ReportSendThsListResp
// @router /ths_send/list [get]
func (t *ThsSendController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		t.Data["json"] = br
		t.ServeJSON()
	}()
	sysUser := t.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := t.GetInt("PageSize")
	currentIndex, _ := t.GetInt("CurrentIndex")
	title := t.GetString("Title")
	reportType := t.GetString("ReportType")

	createTimeStart := t.GetString("CreateTimeStart")
	createTimeEnd := t.GetString("CreateTimeEnd")

	pushTimeStart := t.GetString("PushTimeStart")
	pushTimeEnd := t.GetString("PushTimeEnd")

	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 title != "" {
		condition += ` AND title LIKE '%` + title + `%' `
	}

	if reportType != "" {
		condition += ` AND report_type = ? `
		pars = append(pars, reportType)
	}

	if createTimeStart != "" {
		condition += ` AND create_time >= ? `
		pars = append(pars, createTimeStart)
	}

	if createTimeEnd != "" {
		tmpDate, err := time.ParseInLocation(utils.FormatDate, createTimeEnd, time.Local)
		if err != nil {
			br.Msg = "截止日期格式错误"
			return
		}
		tmpDate = tmpDate.AddDate(0, 0, 1)
		condition += ` AND create_time < ? `
		pars = append(pars, tmpDate)
	}

	if pushTimeStart != "" {
		condition += ` AND push_time >= ? `
		pars = append(pars, pushTimeStart)
	}

	if pushTimeEnd != "" {
		tmpDate, err := time.ParseInLocation(utils.FormatDate, pushTimeEnd, time.Local)
		if err != nil {
			br.Msg = "待推送截止日期格式错误"
			return
		}
		tmpDate = tmpDate.AddDate(0, 0, 1)
		condition += ` AND push_time < ? `
		pars = append(pars, tmpDate)
	}

	total, err := models.GetWaitReportSendThsCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}
	list := make([]*models.ReportSendThsListItem, 0)
	tmpList, err := models.GetWaitReportSendThsList(condition, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	for _, v := range tmpList {
		tmp := &models.ReportSendThsListItem{
			SendId:     v.SendId,
			ReportId:   v.ReportId,
			ReportType: v.ReportType,
			Status:     v.Status,
			Remark:     v.Remark,
			Title:      v.Title,
			LabelStr:   v.LabelStr,
			Level:      v.Level,
			PushTime:   v.PushTime.Format(utils.FormatDateTime),
			CreateTime: v.CreateTime.Format(utils.FormatDateTime),
		}
		list = append(list, tmp)
	}

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

// Save
// @Title 设置同花顺客群待推送时间
// @Description 设置同花顺客群待推送时间
// @Param	request  body  request.ModifyReportThsSendPushTimeReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /ths_send/modify_push_time [post]
func (t *ThsSendController) ModifyPushTime() {
	br := new(models.BaseResponse).Init()
	br.IsSendEmail = false
	defer func() {
		t.Data["json"] = br
		t.ServeJSON()
	}()
	sysUser := t.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req request.ModifyReportThsSendPushTimeReq
	if err := json.Unmarshal(t.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	if req.SendId == 0 {
		br.Msg = "请选择要修改的记录"
		return
	}
	if req.PushTime == "" {
		br.Msg = "请输入新的推送时间"
		return
	}

	newPushTime, err := time.ParseInLocation(utils.FormatDateTime, req.PushTime, time.Local)
	if err != nil {
		br.Msg = "新的推送时间格式错误"
		return
	}
	if newPushTime.Before(time.Now()) {
		br.Msg = "新的推送时间不能设置成过去时间"
		return
	}
	//查询当前记录是否允许更改
	info, err := models.GetReportSendThsBySendId(req.SendId)
	if err != nil {
		br.Msg = "查询推送记录失败"
		br.ErrMsg = "查询推送记录失败 ErrMsg:" + err.Error()
		return
	}

	if info.Status != 2 {
		br.Msg = "当前状态不是待推送，禁止修改"
		return
	}

	//查询新的推送时间和最近一条待推送的时间是否间隔5分钟以上
	last, err := models.GetLatelyWaitReportSendThs()
	if err != nil {
		br.Msg = "查询最近的待推送记录失败"
		br.ErrMsg = "查询最近的待推送记录失败 ErrMsg:" + err.Error()
		return
	}
	var sub time.Duration
	if last.PushTime.Before(newPushTime) {
		sub = newPushTime.Sub(last.PushTime)
	} else {
		sub = last.PushTime.Sub(newPushTime)
	}
	if sub.Minutes() <= 5 {
		br.Msg = "新的推送时间与最近待推送的时间相隔过近，不允许修改"
		return
	}

	//查询是否存在和设置时间相近的待推送记录
	newPushTimeStart := newPushTime.Add(-5 * time.Minute)
	newPushTimeEnd := newPushTime.Add(5 * time.Minute)
	nearly, e := models.GetNearlyWaitReportSendThsByPushTime(info.SendId, newPushTimeStart, newPushTimeEnd)
	if e != nil && e.Error() != utils.ErrNoRow() {
		br.Msg = "查询最近的待推送记录失败"
		br.ErrMsg = "查询最近的待推送记录失败 ErrMsg:" + e.Error()
		return
	}
	if e == nil && nearly.SendId > 0 {
		br.Msg = "新的推送时间与某条待推送记录时间相隔过近，不允许修改"
		return
	}

	var condition string
	var pars []interface{}
	condition = " and push_time > ?"
	pars = append(pars, req.PushTime)
	//查询
	allList, err := models.GetWaitReportSendThsAll(condition, pars)
	if err != nil {
		br.Msg = "查询推送记录失败"
		br.ErrMsg = "查询推送记录失败 ErrMsg:" + err.Error()
		return
	}

	needChangeSendIds := ""
	multi := ""
	if len(allList) > 0 {
		//整理需要更新推送时间的记录
		n := 0
		for _, v := range allList {
			if v.SendId == req.SendId {
				continue
			}
			n = n + 1
			needChangeSendIds += strconv.Itoa(v.SendId) + ","
			add := time.Duration((n)*40) * time.Minute
			newTime := newPushTime.Add(add).Format(utils.FormatDateTime)
			multi += ` WHEN ` + strconv.Itoa(v.SendId) + ` THEN "` + newTime + `"`
		}
	}
	if needChangeSendIds != "" {
		needChangeSendIds = strings.Trim(needChangeSendIds, ",")
	}

	err = models.MultiUpdateReportSendThsPushTime(req.SendId, req.PushTime, multi, needChangeSendIds)
	if err != nil {
		br.Msg = "设置失败"
		br.ErrMsg = "设置失败 ErrMsg:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
}

// @Title 推送客群待发送类型列表
// @Description 推送客群待发送类型列表
// @Success 200 {object} models.ReportSendThsListResp
// @router /ths_send/report_type [get]
func (t *ThsSendController) ReportTypeList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		t.Data["json"] = br
		t.ServeJSON()
	}()
	sysUser := t.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	list := make([]*models.ReportSendThsTypeListItem, 0)
	/*tmpList, err := models.GetWaitReportSendThsType()
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	for _, v := range tmpList {
		tmp := &models.ReportSendThsTypeListItem{ReportType: v.ReportType}
		list = append(list, tmp)
	}*/
	reportTypes := []string{"研报", "语音播报", "视频社区", "线上路演"}
	for _, v := range reportTypes {
		tmp := &models.ReportSendThsTypeListItem{ReportType: v}
		list = append(list, tmp)
	}

	resp := new(models.ReportSendThsTypeListResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ThsSentConfList
// @Title 推送客户群设置-产品优先列表
// @Description 推送客户群设置-产品优先列表
// @Param   SortParam   query   string  false       "排序字段参数，用来排序的字段， 枚举值：'level':优先类型"
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Success 200 {object} models.ReportSendThsListResp
// @router /ths_send/config/list [get]
func (t *ThsSendController) ThsSentConfList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		t.Data["json"] = br
		t.ServeJSON()
	}()
	sysUser := t.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	pageSize, _ := t.GetInt("PageSize")
	currentIndex, _ := t.GetInt("CurrentIndex")
	sortParam := t.GetString("SortParam")
	sortType := t.GetString("SortType")

	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{}
	sortStr := ``
	if sortParam != `` {
		sortStr = fmt.Sprintf("%s %s,modify_time desc ", sortParam, sortType)
	} else {
		sortStr = " modify_time desc,config_id desc "
	}

	total, err := models.GetReportSendThsConfigCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据总数失败，Err:" + err.Error()
		return
	}
	list := make([]*models.ReportSendThsConfigListItem, 0)
	tmpList, err := models.GetReportSendThsConfigList(condition, pars, startSize, pageSize, sortStr)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	for _, v := range tmpList {
		tmp := &models.ReportSendThsConfigListItem{
			ConfigId:     v.ConfigId,
			ConfigType:   v.ConfigType,
			ClassifyId:   v.ClassifyId,
			ClassifyName: v.ClassifyName,
			Level:        v.Level,
			ModifyTime:   v.ModifyTime.Format(utils.FormatDateTime),
			CreateTime:   v.CreateTime.Format(utils.FormatDateTime),
		}
		list = append(list, tmp)
	}

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

// AddThsSentConf
// @Title 推送客户群设置-添加产品优先配置
// @Description 推送客户群设置-添加产品优先配置
// @Param	request  body  request.AddThsSentConfReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /ths_send/config/add [post]
func (t *ThsSendController) AddThsSentConf() {
	br := new(models.BaseResponse).Init()
	defer func() {
		t.Data["json"] = br
		t.ServeJSON()
	}()
	sysUser := t.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req request.AddThsSentConfReq
	if err := json.Unmarshal(t.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	req.ConfigType = utils.TrimStr(req.ConfigType)
	if req.ConfigType == "" {
		br.Msg = "请选择产品类型"
		br.IsSendEmail = false
		return
	}
	if req.ClassifyId == 0 && req.ConfigType != "线上路演" && req.ConfigType != "视频社区" {
		br.Msg = "请选择产品"
		br.IsSendEmail = false
		return
	}
	intervalTime := 40 //间隔时间
	switch req.Level {
	case 1:
		intervalTime = 0
	case 2:
		intervalTime = 20
	case 3:
		intervalTime = 40
	default:
		br.Msg = "错误的优先类型"
		br.IsSendEmail = false
		return
	}

	item := &models.ReportSendThsConfig{
		//ConfigId:     0,
		ConfigType:   req.ConfigType,
		ClassifyId:   req.ClassifyId,
		ClassifyName: "",
		Level:        req.Level,
		Time:         intervalTime,
		SysUserId:    sysUser.AdminId,
		SysRealName:  sysUser.RealName,
		ModifyTime:   time.Now(),
		CreateTime:   time.Now(),
	}

	//研报、语音播报、视频社区、线上路演
	switch req.ConfigType {
	case "研报":
		classifyName := ``
		secondInfo, err := models.GetClassifyById(req.ClassifyId)
		if err != nil {
			br.Msg = "查询研报二级分类信息异常"
			br.ErrMsg = "查询研报二级分类信息异常,err:" + err.Error()
			return
		}
		classifyName = secondInfo.ClassifyName
		if secondInfo.ParentId > 0 {
			firstInfo, err := models.GetClassifyById(secondInfo.ParentId)
			if err != nil {
				br.Msg = "查询研报一级分类信息异常"
				br.ErrMsg = "查询研报一级分类信息异常,err:" + err.Error()
				return
			}
			classifyName += "/" + firstInfo.ClassifyName
		}
		item.ClassifyName = classifyName
	case "语音播报":
		voiceSection, err := yb.GetVoiceSectionById(req.ClassifyId)
		if err != nil {
			br.Msg = "查询语音播报版块信息异常"
			br.ErrMsg = "查询语音播报版块信息异常,err:" + err.Error()
			return
		}
		item.ClassifyName = voiceSection.SectionName
	case "视频社区", "线上路演":
		item.ClassifyName = req.ConfigType
	default:
		br.Msg = "错误的产品类型"
		br.IsSendEmail = false
		return
	}

	count, err := models.GetCountReportSendThsConfigByClassifyId(req.ConfigType, req.ClassifyId)
	if err != nil {
		br.Msg = "添加配置异常"
		br.ErrMsg = "查询现有的配置异常,err:" + err.Error()
		return
	}

	if count > 0 {
		br.Msg = "该产品已配置，请不要重复配置"
		br.IsSendEmail = false
		return
	}
	err = models.AddReportSendThsConfig(item)
	if err != nil {
		br.Msg = "添加配置失败"
		br.ErrMsg = "添加配置失败,err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "配置成功"
}

// EditThsSentConf
// @Title 推送客户群设置-编辑产品优先配置
// @Description 推送客户群设置-编辑产品优先配置
// @Param	request  body  request.EditThsSentConfReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /ths_send/config/edit [post]
func (t *ThsSendController) EditThsSentConf() {
	br := new(models.BaseResponse).Init()
	defer func() {
		t.Data["json"] = br
		t.ServeJSON()
	}()
	sysUser := t.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req request.EditThsSentConfReq
	if err := json.Unmarshal(t.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.ConfigId < 0 {
		br.Msg = "请选择配置"
		br.IsSendEmail = false
		return
	}
	configInfo, err := models.GetReportSendThsConfigByConfigId(req.ConfigId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "不存在该配置信息"
			br.IsSendEmail = false
			return
		}
		br.Msg = "查询配置信息异常"
		br.ErrMsg = "查询现有的配置异常,err:" + err.Error()
		return
	}
	configInfo.Level = req.Level
	configInfo.ModifyTime = time.Now()
	err = configInfo.Update([]string{"Level", "ModifyTime"})
	if err != nil {
		br.Msg = "添加配置失败"
		br.ErrMsg = "添加配置失败,err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "修改成功"
}

// DeleteThsSentConf
// @Title 推送客户群设置-删除产品优先配置
// @Description 推送客户群设置-删除产品优先配置
// @Param	request  body  request.EditThsSentConfReq  true  "type json string"
// @Success 200 string "操作成功"
// @router /ths_send/config/delete [post]
func (t *ThsSendController) DeleteThsSentConf() {
	br := new(models.BaseResponse).Init()
	defer func() {
		t.Data["json"] = br
		t.ServeJSON()
	}()
	sysUser := t.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req request.EditThsSentConfReq
	if err := json.Unmarshal(t.Ctx.Input.RequestBody, &req); err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.ConfigId < 0 {
		br.Msg = "请选择配置"
		br.IsSendEmail = false
		return
	}
	err := models.DeleteReportSendThsConfigByConfigId(req.ConfigId)
	if err != nil {
		br.Msg = "删除配置信息失败"
		br.ErrMsg = "删除配置信息失败,err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "删除成功"
}
