package controllers

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

//专项调研活动
type ActivitySpecialCoAntroller struct {
	BaseAuthController
}

// @Title 专项产业调研列表
// @Description 获取专项产业调研列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
// @Success 200 {object} models.GetCygxActivitySpecialDetailListResp
// @router /list [get]
func (this *ActivitySpecialCoAntroller) SpecialList() {
	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"
		return
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	list, total, errList := services.GetActivitySpecialList(user, currentIndex, pageSize, "")
	if errList != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + errList.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := new(models.GetCygxActivitySpecialDetailListResp)
	count, err := models.GetCygxUserFollowSpecial(user.UserId)
	if err != nil {
		br.Msg = "获取数据失败!"
		br.ErrMsg = "获取客户详情失败,Err:" + err.Error()
		return
	}
	if count == 1 && user.UserId > 0 {
		resp.IsFollow = true
	}
	if user.Mobile != "" {
		resp.IsBindingMobile = true
	}
	resp.List = list
	resp.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title  专项产业调研详情
// @Description 获取专项产业调研详情接口
// @Param   ActivityId   query   int  true       "活动ID"
// @Success Ret=200 {object} models.CygxActivitySpecialResp
// @router /detail [get]
func (this *ActivitySpecialCoAntroller) SpecialDetail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,用户信息为空"
		br.Ret = 408
		return
	}
	uid := user.UserId
	activityId, _ := this.GetInt("ActivityId")
	if activityId < 1 {
		br.Msg = "请输入活动ID"
		return
	}
	resp := new(models.CygxActivitySpecialResp)
	activityInfo, err := models.GetCygxActivitySpecialDetailById(uid, activityId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "活动ID错误,Err:" + "activityId:" + strconv.Itoa(activityId)
		return
	}
	if activityInfo == nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误,Err:" + "activityId:" + strconv.Itoa(activityId)
		return
	}
	havePower, err := services.GetSpecialDetailUserPower(user, activityInfo)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "判断是否已申请过试用失败,Err:" + err.Error()
		return
	}
	//判断有没有对应的权限,如果没有则给出对应的状态码
	if havePower {
		resp.HasPermission = 1
		count, err := models.GetCygxUserFollowSpecial(user.UserId)
		if err != nil {
			br.Msg = "获取数据失败!"
			br.ErrMsg = "获取客户详情失败,Err:" + err.Error()
			return
		}
		if count == 1 {
			resp.IsFollow = true
		}
		activityInfo, err := services.HandleActivitySpecialShow(activityInfo, user)
		if err != nil {
			br.Msg = "获取数据失败!"
			br.ErrMsg = "HandleActivitySpecialShow,Err:" + err.Error()
			return
		}
		var condition string
		var pars []interface{}

		condition += ` AND activity_id =  ? `
		pars = append(pars, activityInfo.ActivityId)

		tripTota, err := models.GetActivitySpecialTripCountByActivityId(condition, pars)
		if err != nil {
			br.Msg = "获取数据失败!"
			br.ErrMsg = "GetActivitySpecialTripCountByActivityId,Err:" + err.Error()
			return
		}
		activityInfo.TripNum = tripTota
		activityInfo.ActivityTypeName = "专项调研"
		resp.Detail = activityInfo
		resp.Detail = activityInfo
	} else {
		hasPermission, sellerName, sellerMobile, err := services.GetUserHasPermission(user)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "判断是否已申请过试用失败,Err:" + err.Error()
			return
		}
		resp.PopupMsg = "您暂无权限参加此活动,若想参加可以申请开通对应的试用权限"
		resp.HasPermission = hasPermission
		resp.SellerName = sellerName
		resp.SellerMobile = sellerMobile
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title报名
// @Description 报名
// @Param	request	body models.ActivityIdRep true "type json string"
// @Success Ret=200 {object} models.SignupSpecialStatus
// @router /add [post]
func (this *ActivitySpecialCoAntroller) SpecialTripAdd() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,用户信息为空"
		br.Ret = 408
		return
	}
	uid := user.UserId
	var req models.ActivityIdRep
	resp := new(models.SignupSpecialStatus)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	activityId := req.ActivityId
	activityInfo, errInfo := models.GetCygxActivitySpecialDetail(activityId)
	if activityInfo == nil {
		br.Msg = "操作失败"
		br.ErrMsg = "活动ID错误,不存在activityId:" + strconv.Itoa(activityId)
		return
	}
	if errInfo != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + errInfo.Error()
		return
	}

	havePower, err := services.GetSpecialDetailUserPower(user, activityInfo)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "判断是否已申请过试用失败,Err:" + err.Error()
		return
	}

	//判断有没有对应的权限,如果没有则给出对应的状态码
	if havePower {
		resp.HasPermission = 1
		signupStatus, popupMsg, popupMsg2, err := services.SpecialTripPopupMsg(activityInfo, user)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "SpecialTripPopupMsg,Err:" + err.Error()
			return
		}
		total, err := models.GetUserActivitySpecialTripCount(user.UserId, activityId)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取日程数量信息失败,Err:" + err.Error()
			return
		}
		resp.PopupMsg = popupMsg
		resp.PopupMsg2 = popupMsg2
		resp.SignupStatus = signupStatus
		if signupStatus == 1 {
			//判断是删除还是添加
			if total == 0 {
				//获取销售信息
				sellerItem, err := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
				if err != nil {
					br.Msg = "操作失败"
					br.ErrMsg = "获取销售信息失败,Err:" + err.Error()
					return
				}
				item := new(models.CygxActivitySpecialTrip)
				item.UserId = uid
				item.RealName = user.RealName
				item.ActivityId = activityId
				item.CreateTime = time.Now()
				item.Mobile = user.Mobile
				item.Email = user.Email
				item.CompanyId = user.CompanyId
				item.CompanyName = user.CompanyName
				if sellerItem != nil {
					item.SellerName = sellerItem.RealName
				}
				err = models.AddCygxActivitySpecialTrip(item)
				if err != nil {
					br.Msg = "操作失败"
					br.ErrMsg = "操作失败,Err:" + err.Error()
					return
				}
				//SignupStatus  int    `description:"返回状态:1:成功 、2 :人数已满 、3:调研次数已用完、 4:超时"`

				////给所属销售发送消息
				//if sellerItem.Mobile != "" {
				//	openIpItem, _ := models.GetUserRecordByMobile(4, sellerItem.Mobile)
				//	if openIpItem != nil && openIpItem.OpenId != "" {
				//		if sellerItem != nil {
				//			go services.SendSpecialTemplateMsg(user.RealName+"【"+user.CompanyName+"】", time.Now().Format(utils.FormatDateTime), user.Mobile, activityInfo.ResearchTheme, "sale", openIpItem)
				//		}
				//	}
				//}

				// 给芳姐发消息
				//cnf, _ := models.GetConfigByCode("tpl_msg")
				//if cnf != nil {
				//	openIpItem, _ := models.GetUserRecordByMobile(4, cnf.ConfigValue)
				//	if openIpItem != nil && openIpItem.OpenId != "" {
				//		actList, _ := models.GetActivityListSpecialAll(activityId)
				//		if len(actList) == 5 {
				//			var companyName string
				//			for _, v := range actList {
				//				companyName += "【" + v.CompanyName + "】"
				//			}
				//			go services.SendSpecialTemplateMsg(companyName, "", "", activityInfo.ResearchTheme, "", openIpItem)
				//		}
				//	}
				//}
				////用户专项调研操作行为,模板消息推送
				//go services.SpecialActivityUserRemind(user, activityInfo, 1)
			}
		}
	} else {
		hasPermission, sellerName, sellerMobile, err := services.GetUserHasPermission(user)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "判断是否已申请过试用失败,Err:" + err.Error()
			return
		}
		resp.PopupMsg = "您暂无权限参加此活动,若想参加可以申请开通对应的试用权限"
		resp.HasPermission = hasPermission
		resp.SellerName = sellerName
		resp.SellerMobile = sellerMobile
	}
	resp.ActivityId = activityId
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.Data = resp
}

// @Title 取消报名
// @Description 取消报名
// @Param	request	body models.ActivityIdRep true "type json string"
// @Success Ret=200 {object} models.SignupStatus
// @router /trip/cancel [post]
func (this *ActivitySpecialCoAntroller) Tripcancel() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	user := this.User
	if user == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,用户信息为空"
		br.Ret = 408
		return
	}
	uid := user.UserId
	var req models.ActivityIdRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	activityId := req.ActivityId
	activityInfo, errInfo := models.GetCygxActivitySpecialDetailById(uid, activityId)
	if activityInfo == nil {
		br.Msg = "操作失败"
		br.ErrMsg = "活动ID错误,不存在activityId:" + strconv.Itoa(activityId)
		return
	}
	if errInfo != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + errInfo.Error()
		return
	}
	err = models.CancelActivitySpecialTrip(uid, activityInfo)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "CancelActivitySpecialTrip,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "会议提醒已取消"
}