package controllers

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

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

// @Title 专项产业调研列表
// @Description 获取专项产业调研列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码,从1开始"
// @Param   ChartPermissionIds   query   string  false     "行业id 多个用 , 隔开"
// @Param   ActiveState   query   string  false       "活动进行状态 未开始:1、进行中2、已结束3"
// @Param   WhichDay   query   string  false       "哪一天 今天:1、明天:2, 本周:3 上周:4,本月:5上月:6多个用 , 隔开"
// @Success 200 {object} models.GetCygxActivitySpecialDetailListResp
// @router /list [get]
func (this *ActivitySpecialController) 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")
	chartPermissionIds := this.GetString("ChartPermissionIds")
	whichDay := this.GetString("WhichDay")
	activeState := this.GetString("ActiveState")
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	if activeState == "1" {
		activeState = ""
	}
	conditionActivity := services.ActivityLabelSpecialSql(chartPermissionIds, whichDay, activeState)

	list, total, errList := services.GetActivitySpecialList(user, currentIndex, pageSize, "", conditionActivity, activeState)
	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
	}

	if len(list) == 0 {
		list = make([]*models.CygxActivitySpecialDetail, 0)
	}
	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 *ActivitySpecialController) 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
	//}
	var havePower bool
	havePower = true
	//判断有没有对应的权限,如果没有则给出对应的状态码
	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 t.activity_id =  ? AND t.is_cancel = 0 `
		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, popupMsg, err := services.GetUserHasPermission(user)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "判断是否已申请过试用失败,Err:" + err.Error()
			return
		}
		resp.PopupMsg = 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 /trip/add [post]
func (this *ActivitySpecialController) 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
		}
		resp.PopupMsg = popupMsg
		resp.PopupMsg2 = popupMsg2
		resp.SignupStatus = signupStatus

		if signupStatus == 1 {
			total, err := models.GetUserActivitySpecialTripCount(user.UserId, activityId)
			if err != nil {
				br.Msg = "获取信息失败"
				br.ErrMsg = "获取日程数量信息失败,Err:" + err.Error()
				return
			}
			//流水记录表
			itemBill := new(models.CygxActivitySpecialTripBill)
			itemBill.UserId = user.UserId
			itemBill.ActivityId = activityInfo.ActivityId
			itemBill.CreateTime = time.Now()
			itemBill.Mobile = user.Mobile
			itemBill.Email = user.Email
			itemBill.CompanyId = user.CompanyId
			itemBill.CompanyName = user.CompanyName
			itemBill.RealName = user.RealName
			itemBill.Source = 1
			itemBill.DoType = 1
			itemBill.BillDetailed = -1 // 流水减一
			itemBill.RegisterPlatform = 1
			itemBill.ChartPermissionId = activityInfo.ChartPermissionId

			var itemMeeting = new(models.CygxActivitySpecialMeetingDetail)
			itemMeeting.UserId = user.UserId
			itemMeeting.ActivityId = activityId
			itemMeeting.CreateTime = time.Now()
			itemMeeting.Mobile = user.Mobile
			itemMeeting.Email = user.Email
			itemMeeting.CompanyId = user.CompanyId
			itemMeeting.CompanyName = user.CompanyName
			itemMeeting.RealName = user.RealName

			go services.ActivitySpecialUserRmind(user, activityId, 2)
			//判断是删除还是添加
			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
				item.IsValid = 1
				if sellerItem != nil {
					item.SellerName = sellerItem.RealName
				}
				if user.OutboundMobile != "" {
					item.OutboundMobile = user.OutboundMobile
					if user.OutboundCountryCode == "" {
						item.CountryCode = "86"
					} else {
						item.CountryCode = user.OutboundCountryCode
					}
				} else {
					item.OutboundMobile = user.Mobile
					if user.CountryCode == "" {
						item.CountryCode = "86"
					} else {
						item.CountryCode = user.CountryCode
					}
				}
				err = models.AddCygxActivitySpecialTrip(item)
				if err != nil {
					br.Msg = "操作失败"
					br.ErrMsg = "操作失败,Err:" + err.Error()
					return
				}
				//SignupStatus  int    `description:"返回状态:1:成功 、2 :人数已满 、3:调研次数已用完、 4:超时"`
			} else {
				updateParams := make(map[string]interface{})
				updateParams["IsValid"] = 1
				updateParams["CreateTime"] = time.Now()
				updateParams["IsCancel"] = 0
				whereParam := map[string]interface{}{"user_id": user.UserId, "activity_id": activityId}
				err = models.UpdateByExpr(models.CygxActivitySpecialTrip{}, whereParam, updateParams)
				if err != nil {
					br.Msg = "报名失败,"
					br.ErrMsg = "二次报名,更改报名是否有效状态失败,Err:" + err.Error()
					return
				}
				resultTime := utils.StrTimeToTime(activityInfo.ActivityTime)
				//48小时之内的取消也扣除一次参会记录
				if time.Now().Add(+time.Hour * 48).After(resultTime) {
					itemBill.BillDetailed = 0 //48小时之内,取消报名之后二次报名,不扣除流水记录
				}
			}
			userType, tripRemaining, mapChartName, err := services.GetChartPermissionSpecialSurplusByCompany(user.CompanyId)
			if err != nil {
				br.Msg = "获取专项调研剩余次数失败"
				br.ErrMsg = "获取专项调研剩余次数失败,err:" + err.Error()
				return
			}
			if userType == 2 {
				tripRemaining = tripRemaining + itemBill.BillDetailed
				itemBill.Total = strconv.Itoa(tripRemaining) + "次"
			} else {
				for k, num := range mapChartName {
					if activityInfo.ChartPermissionName == k {
						num = num + itemBill.BillDetailed
					}
					itemBill.Total += k + strconv.Itoa(num) + "次+"
				}
				itemBill.Total = strings.TrimRight(itemBill.Total, "+")
			}

			//添加流水记录
			err = models.AddCygxActivitySpecialTripBill(itemBill)
			if err != nil {
				br.Msg = "报名失败,"
				br.ErrMsg = "AddCygxActivitySpecialTripBill,Err:" + err.Error()
				return
			}
			//添加数据到会信息
			err = models.AddCygxActivitySpecialMeetingDetail(itemMeeting)
			if err != nil {
				br.Msg = "报名失败,"
				br.ErrMsg = "AddCygxActivitySpecialMeetingDetail,Err:" + err.Error()
				return
			}
		}
	} else {
		hasPermission, sellerName, sellerMobile, popupMsg, err := services.GetUserHasPermission(user)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "判断是否已申请过试用失败,Err:" + err.Error()
			return
		}
		resp.PopupMsg = 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 *ActivitySpecialController) 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
	}
	//流水记录表
	itemBill := new(models.CygxActivitySpecialTripBill)
	itemBill.UserId = user.UserId
	itemBill.ActivityId = activityInfo.ActivityId
	itemBill.CreateTime = time.Now()
	itemBill.Mobile = user.Mobile
	itemBill.Email = user.Email
	itemBill.CompanyId = user.CompanyId
	itemBill.CompanyName = user.CompanyName
	itemBill.RealName = user.RealName
	itemBill.Source = 1
	itemBill.DoType = 2
	itemBill.BillDetailed = 1 // 流水加一
	itemBill.RegisterPlatform = 1
	itemBill.ChartPermissionId = activityInfo.ChartPermissionId
	resultTime := utils.StrTimeToTime(activityInfo.ActivityTime)
	//48小时之内的取消也扣除一次参会记录
	var isValid int
	if time.Now().Add(+time.Hour * 48).After(resultTime) {
		isValid = 1
		itemBill.BillDetailed = 0 //48小时之内取消的活动扣点不返回
	}
	userType, tripRemaining, mapChartName, err := services.GetChartPermissionSpecialSurplusByCompany(user.CompanyId)
	if err != nil {
		br.Msg = "获取专项调研剩余次数失败"
		br.ErrMsg = "获取专项调研剩余次数失败,err:" + err.Error()
		return
	}
	if userType == 2 {
		tripRemaining += itemBill.BillDetailed
		itemBill.Total = strconv.Itoa(tripRemaining) + "次"
	} else {
		for k, num := range mapChartName {
			if activityInfo.ChartPermissionName == k {
				num += itemBill.BillDetailed
			}
			itemBill.Total += k + strconv.Itoa(num) + "次+"
		}
		itemBill.Total = strings.TrimRight(itemBill.Total, "+")
	}
	err = models.CancelActivitySpecialTripIsValid(isValid, activityInfo.ActivityId, uid)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "CancelActivitySpecialTrip,Err:" + err.Error()
		return
	}
	err = models.CancelCygxActivitySpecialMeetingDetail(uid, activityId)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "CancelCygxActivitySpecialMeetingDetail,Err:" + err.Error()
		return
	}
	go models.AddCygxActivitySpecialTripBill(itemBill)

	br.Ret = 200
	br.Success = true
	br.Msg = "已取消"
}

// @Title 感兴趣、不感兴趣
// @Description 感兴趣、不感兴趣接口
// @Param	request	body models.ActivityIdRep true "type json string"
// @Success Ret=200 {object} models.SignupSpecialStatus
// @router /signup/add [post]
func (this *ActivitySpecialController) SpecialSignupAdd() {
	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
	//}
	var havePower bool
	havePower = true
	//判断有没有对应的权限,如果没有则给出对应的状态码
	if havePower {
		resp.HasPermission = 1
		total, err := models.GetUserCygxActivitySpecialSignup(user.UserId, activityId)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取日程数量信息失败,Err:" + err.Error()
			return
		}
		resp.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.CygxActivitySpecialSignup)
			item.RegisterPlatform = utils.REGISTER_PLATFORM
			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.AddCygxActivitySpecialSignup(item)
			if err != nil {
				br.Msg = "操作失败"
				br.ErrMsg = "操作失败,Err:" + err.Error()
				return
			}
			resp.Status = 1
			resp.PopupMsg = "感谢反馈"
			resp.PopupMsg2 = "此调研具体行程尚未确认,待预报名人数满10人后弘则会确定行程并推送给您活动日期,只有在确认行程中再次报名才完成占位。"
			//给所属销售发送消息
			//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)
			//		}
			//	}
			//}
			// 给芳姐发消息
			actList, _ := models.GetActivityListSpecialByActivityId(activityId)
			if len(actList) == 10 {
				go services.SendWxMsgActivitySpecial10(activityInfo)
			}
			//用户专项调研操作行为,模板消息推送
			//go services.SpecialActivityUserRemind(user, activityInfo, 1)
		} else {
			err = models.DeleteCygxActivitySpecialSignup(user.UserId, activityId)
			if err != nil {
				br.Msg = "操作失败"
				br.ErrMsg = "操作失败,Err:" + err.Error()
				return
			}
			resp.Status = 2
		}
	} else {
		hasPermission, sellerName, sellerMobile, popupMsg, err := services.GetUserHasPermission(user)
		if err != nil {
			br.Msg = "获取信息失败"
			br.ErrMsg = "判断是否已申请过试用失败,Err:" + err.Error()
			return
		}
		resp.PopupMsg = 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.ArticleCollectResp true "type json string"
// @Success 200
// @router /follow [post]
func (this *ActivitySpecialController) SpecialMsg() {
	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
	}
	resp := new(models.ArticleCollectResp)
	count, err := models.GetCygxUserFollowSpecial(user.UserId)
	if err != nil {
		br.Msg = "获取数据失败!"
		br.ErrMsg = "获取客户详情失败,Err:" + err.Error()
		return
	}
	if count == 0 {
		item := new(models.CygxUserFollowSpecial)
		item.UserId = user.UserId
		item.RealName = user.RealName
		item.CreateTime = time.Now()
		item.Mobile = user.Mobile
		item.Email = user.Email
		item.CompanyId = user.CompanyId
		item.CompanyName = user.CompanyName
		item.CreateTime = time.Now()
		err := models.AddUserFollowSpecial(item)
		if err != nil {
			br.Msg = "操作失败!"
			br.ErrMsg = "获取客户详情失败,Err:" + err.Error()
			return
		}
		resp.Status = 1
	} else {
		err := models.DeleteCygxUserFollowSpecial(user.UserId)
		if err != nil {
			br.Msg = "操作失败!"
			br.ErrMsg = "获取客户详情失败,Err:" + err.Error()
			return
		}
		resp.Status = 2
	}
	br.Ret = 200
	br.Data = resp
	br.Success = true
	br.Msg = "操作成功!"
}