package controllers

import (
	"encoding/json"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/services"
	"hongze/hongze_cygx/utils"
	"strconv"
	"strings"
	"time"
)

// 活动
type ActivitySignCoAntroller struct {
	BaseAuthController
}

// @Title  活动扫码自动签到
// @Description 活动扫码签到接口
// @Param   ActivityId   query   int  true       "活动ID"
// @Success Ret=200 {object} models.CygxActivityResp
// @router /detail [get]
func (this *ActivitySignCoAntroller) Detail() {
	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.CygxActivitySigninDetailResp)
	activityInfo, err := models.GetAddActivityInfoByIdShow(uid, activityId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取活动详情信息失败，Err:" + err.Error()
		return
	}
	if activityInfo == nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，Err:" + "activityId：" + strconv.Itoa(activityId)
		return
	}
	totalMySuccess, err := models.GetActivitySignupCount(uid, activityId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	detail := new(models.CygxActivitySigninResp)
	if totalMySuccess > 0 {
		detail.IsSignup = true
	}
	var condition string
	var pars []interface{}
	condition = " AND  open_id = ?  AND activity_id = ?  "
	pars = append(pars, user.OpenId, activityId)
	total, err := models.GetCygxActivitySigninCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	//判断是否已经申请过
	applyCount, err := models.GetApplyRecordCount(uid)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "判断是否已申请过试用失败，Err:" + err.Error()
		return
	}

	item := new(models.CygxActivitySignin)
	item.ActivityId = activityId
	item.UserId = user.UserId
	item.Mobile = user.Mobile
	item.Email = user.Email
	item.CompanyId = user.CompanyId
	item.RealName = user.RealName
	item.CompanyName = user.CompanyName
	item.IsSignup = totalMySuccess
	item.CountryCode = user.CountryCode
	item.OpenId = user.OpenId
	item.CreateTime = time.Now()
	if total == 0 && (user.Mobile != "" || user.Email != "") && (applyCount > 0 || user.CompanyId > 1) {
		err = models.AddCygxActivitySignin(item)
		if err != nil {
			br.Msg = "签到失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
	}

	//记录签到信息到用户到会表
	if user.CompanyId > 1 {
		pars = make([]interface{}, 0)
		condition = " AND  user_id = ?  AND activity_id = ?  "
		pars = append(pars, user.UserId, activityId)
		totalOfflineMeeting, err := models.GetCygxActivityOfflineMeetingDetailCount(condition, pars)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		if totalOfflineMeeting == 0 {
			itemOfflineMeeting := new(models.CygxActivityOfflineMeetingDetail)
			itemOfflineMeeting.UserId = user.UserId
			itemOfflineMeeting.ActivityId = activityId
			itemOfflineMeeting.CreateTime = time.Now()
			itemOfflineMeeting.Mobile = user.Mobile
			itemOfflineMeeting.CompanyId = user.CompanyId
			itemOfflineMeeting.CompanyName = user.CompanyName
			itemOfflineMeeting.IsMeeting = 1
			err = models.AddCygxActivityOfflineMeetingDetail(itemOfflineMeeting)
			if err != nil {
				br.Msg = "签到失败"
				br.ErrMsg = "获取失败AddCygxActivityOfflineMeetingDetail，Err:" + err.Error()
				return
			}
		}
		//添加日志记录
		services.AddCygxActivitySigninLog(item)

		//把报名信息写入签到到会表
		services.AddCygxActivityOfflineMeetingDetail(activityId, user.UserId)

		//后期扫码签到，处理是否爽约限制
		services.CygxActivityRestrictSignupByuid(user.UserId, activityId)

		//线下调研活动扫码签到给对应销售发模版消息
		services.SendActivitieSignTemplateMsg(user, activityInfo)
		services.SendActivitieSignCategoryTemplateMsg(user, activityInfo)

		//处理用户标签
		services.ActivityUserLabelLogAdd(activityId, []string{user.Mobile})

		{
			//用做后台联系人列表查询
			itemD := new(models.CygxActivityAttendanceDetail)
			itemD.ActivityId = activityId
			itemD.RealName = user.RealName
			itemD.Mobile = user.Mobile
			itemD.CompanyName = user.CompanyName
			itemD.IsMeetingStr = 1
			itemD.CreateTime = time.Now()
			var itemDs []*models.CygxActivityAttendanceDetail
			itemDs = append(itemDs, itemD)
			services.AddctivitySignupDetailByJmcjNew(itemDs, []int{activityId})
		}

	}
	//1，没有签到记录不为潜在客户
	//2,没有签到记录，手机号不为空，没有申请记录
	//3,已经有签到记录的
	if total == 0 && user.CompanyId > 1 || ((user.Mobile != "" || user.Email != "") && applyCount > 0) || total > 0 {
		resp.IsBindingMobile = true
	}
	if user.CompanyId == 1 {
		detail.IsNewUser = true
	}

	//潜在客户提交过申请的显示提交时候的公司
	if applyCount > 0 && (user.Mobile != "" || user.Email != "") && user.CompanyId == 1 {
		detail, err := models.GetCygxApplyRecordByMobile(user.Mobile)
		if err != nil {
			br.Msg = "签到失败"
			br.ErrMsg = "GetCygxApplyRecordByMobile，Err:" + err.Error()
			return
		}
		user.CompanyName = detail.CompanyName
	}
	detail.ActivityId = activityId
	detail.ActivityName = activityInfo.ActivityName
	detail.Mobile = user.Mobile
	if user.Mobile == "" {
		detail.Mobile = user.Email
	}
	detail.RealName = user.RealName
	detail.CompanyName = user.CompanyName

	//用于前端二次回显
	if user.Mobile == "" {
		pars = make([]interface{}, 0)
		condition = " AND  open_id = ?  AND activity_id = ?  "
		pars = append(pars, user.OpenId, activityId)
		signinDetail, err := models.GetCygxActivitySigninDetail(condition, pars)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "签到失败"
			br.ErrMsg = "获取失败GetCygxActivitySigninDetail，Err:" + err.Error()
			return
		}
		if signinDetail != nil {
			detail.BusinessCard = signinDetail.BusinessCard
			detail.Mobile = signinDetail.Mobile
			if signinDetail.Mobile == "" {
				detail.Mobile = signinDetail.Email
			}
			detail.RealName = signinDetail.RealName
			detail.CompanyName = signinDetail.CompanyName
			detail.IsNewUser = true
		}
	}
	resp.Detail = detail
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title  活动扫码手动签到
// @Description 活动扫码手动签到接口
// @Param   ActivityId   query   int  true       "活动ID"
// @Success Ret=200 {object} models.CygxActivityResp
// @router /byHand [post]
func (this *ActivitySignCoAntroller) ByHand() {
	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
	resp := new(models.CygxActivitySigninDetailResp)
	var req models.CygxActivitySigninReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	signinType := req.SigninType
	activityId := req.ActivityId
	CountryCode := req.CountryCode
	Mobile := req.Mobile
	CompanyName := req.CompanyName
	BusinessCard := req.BusinessCard
	RealName := req.RealName
	if activityId < 1 {
		br.Msg = "请输入活动ID"
		return
	}
	user.RealName = RealName
	user.CompanyName = CompanyName
	activityInfo, err := models.GetAddActivityInfoByIdShow(uid, activityId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取活动详情信息失败，Err:" + err.Error()
		return
	}
	if activityInfo == nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，Err:" + "activityId：" + strconv.Itoa(activityId)
		return
	}
	totalMySuccess, err := models.GetActivitySignupCount(uid, activityId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	item := new(models.CygxActivitySignin)

	var condition string
	var pars []interface{}
	condition = " AND  open_id = ?  AND activity_id = ?  "
	pars = append(pars, user.OpenId, activityId)
	total, err := models.GetCygxActivitySigninCount(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	if user.Mobile == "" && user.Email == "" {
		if signinType == 1 {
			if req.Mobile == "" {
				br.Msg = "参数错误"
				br.ErrMsg = "参数错误，手机号为空 为空"
				return
			}
			itemMsgCode, err := models.GetMsgCode(req.Mobile, req.VCode)
			if err != nil {
				if err.Error() == utils.ErrNoRow() {
					br.Msg = "验证码错误,请重新输入"
					br.ErrMsg = "校验验证码失败，Err:" + err.Error()
					return
				} else {
					br.Msg = "验证码错误,请重新输入"
					br.ErrMsg = "校验验证码失败，Err:" + err.Error()
					return
				}
			}
			if itemMsgCode == nil {
				br.Msg = "验证码错误,请重新输入"
				return
			}
			userMobile, err := models.GetWxUserItemByMobile(Mobile)
			if err != nil && err.Error() != utils.ErrNoRow() {
				br.Msg = "签到失败"
				br.ErrMsg = "获取失败，Err:" + err.Error()
				return
			}
			if userMobile != nil {
				user = userMobile
			}
		} else {
			if BusinessCard == "" {
				br.Msg = "签到失败"
				br.ErrMsg = "签到失败名片地址为空，Err:"
				return
			}
			item.BusinessCard = BusinessCard
		}
	} else {
		if signinType == 1 {
			if CompanyName == "" {
				br.Msg = "请输入公司名称"
				return
			}
			if RealName == "" {
				br.Msg = "请输入姓名"
				return
			}
		}
	}
	//如果是用邮箱登录的，就把手机号置空
	if strings.Contains(Mobile, "@") {
		Mobile = ""
	}
	item.ActivityId = activityId
	item.UserId = user.UserId
	item.Mobile = Mobile
	item.CountryCode = CountryCode
	item.Email = user.Email
	item.CompanyId = user.CompanyId
	item.RealName = user.RealName
	item.CompanyName = user.CompanyName
	item.IsSignup = totalMySuccess
	item.BusinessCard = BusinessCard
	item.OpenId = user.OpenId
	item.CreateTime = time.Now()
	if total == 0 {
		err = models.AddCygxActivitySignin(item)
		if err != nil {
			br.Msg = "签到失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
	} else {
		pars = make([]interface{}, 0)
		condition = " AND  open_id = ?  AND activity_id = ?  "
		pars = append(pars, user.OpenId, activityId)
		signinDetail, err := models.GetCygxActivitySigninDetail(condition, pars)
		if err != nil {
			br.Msg = "签到失败"
			br.ErrMsg = "获取失败GetCygxActivitySigninDetail，Err:" + err.Error()
			return
		}
		item.Id = signinDetail.Id
		err = models.UpdateCygxActivitySignin(item)
		if err != nil {
			br.Msg = "签到失败"
			br.ErrMsg = "获取失败，UpdateCygxActivitySignin,Err:" + err.Error()
			return
		}
	}
	detail := new(models.CygxActivitySigninResp)
	if totalMySuccess > 0 {
		detail.IsSignup = true
	}
	//添加日志记录
	go services.AddCygxActivitySigninLog(item)
	if user.CompanyId <= 1 {
		detail.IsNewUser = true
	}
	if user.UserId == 0 {
		detail.IsNewUser = true
	}
	detail.ActivityId = activityId
	detail.ActivityName = activityInfo.ActivityName
	detail.Mobile = Mobile
	detail.RealName = RealName
	detail.CompanyName = CompanyName
	resp.Detail = detail
	resp.IsBindingMobile = true
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title  活动签到到会详情
// @Description 活动签到到会详情接口
// @Param   ActivityId   query   int  true       "活动ID"
// @Success Ret=200 {object} models.CygxActivityResp
// @router /signup/detail [get]
func (this *ActivitySignCoAntroller) SignupDetail() {
	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
	}

	activityId, _ := this.GetInt("ActivityId")
	if activityId < 1 {
		br.Msg = "请输入活动ID"
		return
	}
	resp := new(models.CygxActivityOfflineMeetingDetailResp)
	activityInfo, err := models.GetAddActivityInfoById(activityId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取活动详情信息失败，Err:" + err.Error()
		return
	}
	if !services.GetBelongingRai(user.Mobile) {
		br.Msg = "你暂无查看权限"
		br.ErrMsg = "你暂无查看权限，UserId:" + strconv.Itoa(user.UserId)
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND do_fail_type = 0 AND activity_id  = ?`
	pars = append(pars, activityId)

	listSignup, err := models.GetActivitySignupList(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取信息失败"
		br.ErrMsg = "GetOfflineMeetingListWithUser，UserId:" + strconv.Itoa(user.UserId)
		return
	}
	//获取对应销售所能查看的用户手机号
	UserMobileMap, err := services.GetAdminCheckUserMobileMap(user)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "GetAdminCheckUserMobileMap，UserId:" + strconv.Itoa(user.UserId)
		return
	}
	//获取用户的签到时间
	SigninTimeMap, err := services.GetUserActivitySigninTimeMap(activityId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "GetUserActivitySigninTimeMap，activityId:" + strconv.Itoa(activityId)
		return
	}
	for _, v := range listSignup {
		if _, ok := UserMobileMap[v.Mobile]; ok {
			item := new(models.CygxActivitySignupResp)
			item.RealName = v.RealName
			item.CompanyName = v.CompanyName
			if _, ok := SigninTimeMap[v.UserId]; ok {
				item.IsMeeting = 1
				item.SigninTime = SigninTimeMap[v.UserId]
			}
			resp.List = append(resp.List, item)
		}
	}
	if len(resp.List) == 0 {
		resp.List = make([]*models.CygxActivitySignupResp, 0)
	}
	resp.ActivityId = activityId
	resp.ActivityName = activityInfo.ActivityName
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
