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

	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
		}

		imgMap := services.GetActivitySpecialImgMap([]*models.CygxActivitySpecialDetail{activityInfo})
		if imgMap[activityId] != nil {
			activityInfo.ImgUrl = imgMap[activityId].ImgUrl
		}
		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 /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
		}
		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 = utils.REGISTER_PLATFORM
			itemBill.ChartPermissionId = activityInfo.ChartPermissionId
			itemBill.ChartPermissionName = activityInfo.ChartPermissionName

			if utils.InArrayByStr(utils.ACTIVITY_SPECIAL_TRIP_PERMISSION_NAME_OTHER, activityInfo.ChartPermissionName) {
				//如果是策略、固收、周期行业,把代扣行业信息放入流水表,取消报名的时候,返点使用
				maxChartPermissionId, maxChartPermissionName, err := services.GetSpecialBillMaxChartPermissionId(user)
				if err != nil {
					br.Msg = "操作失败"
					br.ErrMsg = "获取销售信息失败,GetSpecialBillMaxChartPermissionId Err:" + err.Error()
					return
				}
				itemBill.ChartPermissionId = maxChartPermissionId
				itemBill.ChartPermissionName = maxChartPermissionName
			}

			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)
			go services.ActivitySpecialUserAddTrip(user, activityId)
			//判断是删除还是添加
			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 = services.DeductTripRemainingtimesByUser(user, activityInfo) //扣除用户专项调研剩余次数
				if err != nil {
					br.Msg = "操作失败"
					br.ErrMsg = "操作失败,Err:" + err.Error()
					return
				}

				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小时之内,取消报名之后二次报名,不扣除流水记录
				} else {
					err = services.DeductTripRemainingtimesByUser(user, activityInfo) //扣除用户专项调研剩余次数
					if err != nil {
						br.Msg = "操作失败"
						br.ErrMsg = "操作失败,Err:" + err.Error()
						return
					}
				}
			}
			//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, "+")
			//}

			totalText, err := services.HandleActivitySpecialTripBillTotalText(user.CompanyId)
			if err != nil {
				br.Msg = "报名失败,"
				br.ErrMsg = "二次报名,更改报名是否有效状态失败,Err:" + err.Error()
				return
			}
			itemBill.Total = totalText

			//添加流水记录
			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 *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
	total, err := models.GetUserActivitySpecialTripCount(user.UserId, activityId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取日程数量信息失败,Err:" + err.Error()
		return
	}
	if total == 0 {
		br.Msg = "已取消报名!"
		return
	}
	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 = utils.REGISTER_PLATFORM
	itemBill.ChartPermissionId = activityInfo.ChartPermissionId
	itemBill.ChartPermissionName = activityInfo.ChartPermissionName
	resultTime := utils.StrTimeToTime(activityInfo.ActivityTime)

	if utils.InArrayByStr(utils.ACTIVITY_SPECIAL_TRIP_PERMISSION_NAME_OTHER, activityInfo.ChartPermissionName) {
		//如果是策略、固收、周期行业,把代扣行业信息放入流水表,取消报名的时候,返点使用
		lastTripBill, err := models.GetCygxActivitySpecialTripBillLastDetialByActivityId(activityInfo.ActivityId, user.UserId)
		if err != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "获取销售信息失败,GetSpecialBillMaxChartPermissionId Err:" + err.Error()
			return
		}
		itemBill.ChartPermissionId = lastTripBill.ChartPermissionId
		itemBill.ChartPermissionName = lastTripBill.ChartPermissionName
	}
	//48小时之内的取消也扣除一次参会记录
	var isValid int
	if time.Now().Add(+time.Hour * 48).After(resultTime) {
		isValid = 1
		itemBill.BillDetailed = 0 //48小时之内取消的活动扣点不返回
	} else {
		err = services.RebateTripRemainingtimesByUser(user, activityInfo) // 返点
		if err != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "操作失败,RebateTripRemainingtimesByUserErr:" + err.Error()
			return
		}
	}
	//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, "+")
	//}

	totalText, err := services.HandleActivitySpecialTripBillTotalText(user.CompanyId)
	if err != nil {
		br.Msg = "操作失败,"
		br.ErrMsg = "HandleActivitySpecialTripBillTotalText,Err:" + err.Error()
		return
	}
	itemBill.Total = totalText
	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 = "已取消"
}