package cygx

import (
	"encoding/json"
	"fmt"
	"github.com/tealeg/xlsx"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/models/system"
	"hongze/hz_crm_api/services"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// 专项调研行程
type ActivitySpecialTripCoAntroller struct {
	controllers.BaseAuthController
}

// @Title 新增报名
// @Description 新增报名接口
// @Param	request	body cygx.AddMeetingReminderReq true "type json string"
// @Success 200 操作成功
// @router /special/trip/addUser [post]
func (this *ActivitySpecialTripCoAntroller) AddUser() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	var req cygx.AddMeetingReminderReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	roleTypeCode := AdminUser.RoleTypeCode
	var items []*cygx.CygxActivitySpecialTrip
	var itemsBill []*cygx.CygxActivitySpecialTripBill
	var itemsMeet []*cygx.CygxActivitySpecialMeetingDetail
	activityIds := req.ActivityIds
	uidList := req.List
	if activityIds == "" {
		br.Msg = "请选择活动"
		br.ErrMsg = "活动ID不能为空"
		return
	}
	activityIdList := strings.Split(activityIds, ",")
	var uids string
	for _, v := range uidList {
		uids += strconv.Itoa(v.UserId) + ","
	}
	uids = strings.TrimRight(uids, ",")
	for _, v := range uidList {
		uid := v.UserId
		wxUser, userErr := models.GetWxUserByUserId(uid)
		if userErr != nil {
			br.Msg = "编辑失败！查询用户信息失败"
			br.ErrMsg = "查询用户信息失败，Err:" + userErr.Error() + "用户UID：" + strconv.Itoa(uid) + "不存在"
			return
		}
		for _, vact := range activityIdList {
			activityId, _ := strconv.Atoi(vact)
			activityInfo, err := cygx.GetAddActivityInfoSpecialById(activityId)
			if err != nil {
				br.Msg = "活动不存在"
				br.ErrMsg = "活动ID错误，Err:activityId：" + strconv.Itoa(activityId)
				return
			}
			limitPeopleNum := activityInfo.LimitPeopleNum
			if limitPeopleNum > 0 {
				if AdminUser.RoleTypeCode != "admin" {
					havePower, err := cygxService.GetSpecialDetailUserPower(wxUser, activityInfo)
					if err != nil {
						br.Msg = "用户权限校验失败！"
						br.ErrMsg = "GetActivityDetailUserPower，Err:" + err.Error() + fmt.Sprint("UserId", wxUser.UserId, "ActivityId:", activityInfo.ActivityId)
						return
					}
					if !havePower {
						br.Msg = "当前活动对该客户不可见，无法报名"
						br.ErrMsg = "活动ID：" + strconv.Itoa(activityId) + "活动名称：" + activityInfo.ResearchTheme + "用户ID：" + strconv.Itoa(int(wxUser.UserId))
						return
					}
				}
				//获取这个活动已经报名的用户数量
				totalSignup, errSignup := cygx.GetActivitySpecialTripCountByActivityId(activityId)
				if errSignup != nil {
					br.Msg = "获取失败"
					br.ErrMsg = "获取失败，Err:" + errSignup.Error()
					return
				}
				//获取这个活动中输入的这些用户的报名数量
				totalThisUser, errThisUser := cygx.GetActivitySpecialTripCountByThisUser(activityId, uids)
				if errThisUser != nil {
					br.Msg = "获取失败"
					br.ErrMsg = "获取失败，Err:" + errThisUser.Error()
					return
				}
				//如果是限制人数的就做报名人数限制判断
				if limitPeopleNum < totalSignup+len(uidList)-totalThisUser {
					br.Msg = "新增失败，活动人数超限"
					br.ErrMsg = "当前活动报名人数已满,活动：" + activityInfo.ResearchTheme
					return
				}
			}
			//total, errtotal := cygx.GetActivitySpecialTripCount(uid, activityId)
			//if errtotal != nil {
			//	br.Msg = "获取失败"
			//	br.ErrMsg = "获取失败，Err:" + errtotal.Error()
			//	return
			//}
			infoUser, err := cygx.GetUserAndCompanyNameList(uid)
			if err != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取数据失败，Err:" + err.Error()
				return
			}
			//if total == 0 {
			totalAll, err := cygx.GetUserActivitySpecialTripCount(uid, activityId)
			if err != nil {
				br.Msg = "获取信息失败"
				br.ErrMsg = "获取日程数量信息失败,Err:" + err.Error()
				return
			}
			if totalAll > 0 {
				continue
			}
			//流水记录表
			itemBill := new(cygx.CygxActivitySpecialTripBill)
			itemBill.UserId = infoUser.UserId
			itemBill.ActivityId = activityInfo.ActivityId
			itemBill.CreateTime = time.Now()
			itemBill.Mobile = infoUser.Mobile
			itemBill.Email = infoUser.Email
			itemBill.CompanyId = infoUser.CompanyId
			itemBill.CompanyName = infoUser.CompanyName
			itemBill.RealName = infoUser.RealName
			itemBill.Source = 2
			itemBill.DoType = 1
			itemBill.BillDetailed = -1 // 流水减一
			itemBill.RegisterPlatform = 3
			itemBill.ChartPermissionId = activityInfo.ChartPermissionId
			itemBill.ChartPermissionName = activityInfo.ChartPermissionName
			itemBill.AdminId = AdminUser.AdminId

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

			if totalAll == 0 {
				item := new(cygx.CygxActivitySpecialTrip)
				item.UserId = infoUser.UserId
				item.RealName = infoUser.RealName
				item.SellerName = infoUser.SellerName
				item.ActivityId = activityId
				item.CreateTime = time.Now()
				item.Mobile = infoUser.Mobile
				item.Email = infoUser.Email
				item.CompanyId = infoUser.CompanyId
				item.CompanyName = infoUser.CompanyName
				item.AdminId = AdminUser.AdminId
				item.Source = 2
				//优先绑定用户修改过的外呼手机号
				if infoUser.OutboundMobile != "" {
					item.OutboundMobile = infoUser.OutboundMobile
					if infoUser.OutboundCountryCode == "" {
						item.CountryCode = "86"
					} else {
						item.CountryCode = infoUser.OutboundCountryCode
					}
				} else {
					item.OutboundMobile = infoUser.Mobile
					if infoUser.CountryCode == "" {
						item.CountryCode = "86"
					} else {
						item.CountryCode = infoUser.CountryCode
					}
				}
				items = append(items, item)
				err = cygxService.DeductTripRemainingtimesByUser(infoUser, activityInfo, roleTypeCode) //扣除用户专项调研剩余次数
				if err != nil {
					br.Msg = "操作失败"
					br.ErrMsg = "操作失败,Err:" + err.Error()
					return
				}
			} else {
				err = cygx.UpdateSpecialTrip(1, 0, uid, activityId)
				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 = cygxService.DeductTripRemainingtimesByUser(infoUser, activityInfo, roleTypeCode) //扣除用户专项调研剩余次数
					if err != nil {
						br.Msg = "操作失败"
						br.ErrMsg = "操作失败,Err:" + err.Error()
						return
					}
				}
			}
			//userType, tripRemaining, mapChartName, err := cygxService.GetChartPermissionSpecialSurplusByCompany(infoUser.CompanyId)
			//if err != nil {
			//	br.Msg = "获取专项调研剩余次数失败"
			//	br.ErrMsg = "获取专项调研剩余次数失败,err:" + err.Error()
			//	return
			//}
			//if userType == 2 {
			//	tripRemaining = tripRemaining + itemBill.BillDetailed - i
			//	itemBill.Total = strconv.Itoa(tripRemaining) + "次"
			//} else {
			//	for k, num := range mapChartName {
			//		if activityInfo.ChartPermissionName == k {
			//			num = num + itemBill.BillDetailed - i
			//		}
			//		itemBill.Total += k + strconv.Itoa(num) + "次+"
			//	}
			//	itemBill.Total = strings.TrimRight(itemBill.Total, "+")
			//}
			totalText, err := cygxService.HandleActivitySpecialTripBillTotalText(infoUser.CompanyId)
			if err != nil {
				br.Msg = "报名失败，"
				br.ErrMsg = "二次报名，更改报名是否有效状态失败，Err:" + err.Error()
				return
			}
			itemBill.Total = totalText
			itemsBill = append(itemsBill, itemBill)
			//}

			var itemMeeting = new(cygx.CygxActivitySpecialMeetingDetail)
			itemMeeting.UserId = v.UserId
			itemMeeting.ActivityId = activityId
			itemMeeting.CreateTime = time.Now()
			itemMeeting.Mobile = infoUser.Mobile
			itemMeeting.Email = infoUser.Email
			itemMeeting.CompanyId = infoUser.CompanyId
			itemMeeting.CompanyName = infoUser.CompanyName
			itemMeeting.RealName = infoUser.RealName
			itemsMeet = append(itemsMeet, itemMeeting)
		}
	}
	err = cygx.AddCygxActivitySpecialTrip(items, itemsBill, itemsMeet)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "新增用户失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}

// @Title 报名列表
// @Description 报名列表接口
// @Param   ActivityId   query   int  true     "活动ID"
// @Param   IsExport   query   bool  false       "是否导出excel，默认是false"
// @Success 200 {object} cygx.GetAppointmentSpecialListRsep
// @router /special/tripList [get]
func (this *ActivitySpecialTripCoAntroller) TripList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	isExport, _ := this.GetBool("IsExport", false)
	activityId, _ := this.GetInt("ActivityId")
	if activityId < 1 {
		br.Msg = "活动不存在"
		return
	}
	respList := new(cygx.GetAppointmentSpecialListRsep)
	activityInfo, _ := cygx.GetAddActivityInfoSpecialById(activityId)
	if activityInfo == nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，Err:activityId：" + strconv.Itoa(activityId)
		return
	}
	//超级管理员和权益管理员、权益研究员可以下载所有客户，销售组长能下载本组客户，销售只能下载本人名下客户
	resp := new(cygx.CanDownload)
	adminInfo, errAdmin := system.GetSysUserById(sysUser.AdminId)
	if errAdmin != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errAdmin.Error()
		return
	}
	if adminInfo.Role == "admin" || adminInfo.Role == "researcher" {
		resp.IsCanDownload = true
	}
	memberType := "Admin"
	sqlStr := `  AND s.is_cancel = 0`
	totalStr := sqlStr

	list, err := cygx.GetCygxActivitySpecialTripList(activityId, sqlStr)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	//线上活动，销售查看自己客户，销售组长查看组员
	if resp.IsCanDownload == false && activityInfo.SpecialType == 1 {
		mapMobile, err := cygxService.GetAdminLookUserMobile(adminInfo)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,销售对应权限，Err:" + err.Error()
			return
		}
		for _, v := range list {
			if _, ok := mapMobile[v.Mobile]; ok {
				respList.List = append(respList.List, v)
			}
		}
		if adminInfo.RoleTypeCode == "rai_group" {
			//组长查看本组所有组员
			memberType = "GroupLeader"
		} else {
			//组员查看自己
			memberType = "Sale"
		}
	} else {
		respList.List = list
	}
	if len(respList.List) == 0 {
		respList.List = make([]*cygx.CygxActivitySpecialTripResp, 0)
	}
	//导出excel
	if isExport {
		TripListExport(this, respList.List)
		return
	}
	total, errtotal := cygx.GetActivitySpecialTripTotal(activityId, totalStr)
	if errtotal != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "客户总数获取失败，Err:" + errtotal.Error()
		return
	}
	myTotal := len(respList.List)
	respList.Source = 1
	respList.Total = total
	respList.MyTotal = myTotal
	respList.ActivityId = activityId
	respList.SpecialType = activityInfo.SpecialType
	if activityInfo.LimitPeopleNum > 0 {
		respList.IsLimitPeople = 1
	}
	respList.MemberType = memberType
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = respList
}

// TripListExport 下载报名信息
func TripListExport(this *ActivitySpecialTripCoAntroller, listDate []*cygx.CygxActivitySpecialTripResp) {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	activityId, _ := this.GetInt("ActivityId")
	activityInfo, _ := cygx.GetAddActivityInfoSpecialById(activityId)
	if activityInfo == nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，Err:activityId：" + strconv.Itoa(activityId)
		return
	}
	//超级管理员和权益管理员、权益研究员可以下载所有客户，销售组长能下载本组客户，销售只能下载本人名下客户
	resp := new(cygx.CanDownload)
	adminInfo, errAdmin := system.GetSysUserById(sysUser.AdminId)
	if errAdmin != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + errAdmin.Error()
		return
	}
	if adminInfo.Role == "admin" || adminInfo.Role == "researcher" {
		resp.IsCanDownload = true
	}

	//创建excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}
	style.Alignment = alignment
	style.ApplyAlignment = true

	sheetName := "报名名单"
	sheet, err := xlsxFile.AddSheet(sheetName)
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	//标头
	if activityInfo.SpecialType == 1 || resp.IsCanDownload {
		rowTitle := sheet.AddRow()
		cellA := rowTitle.AddCell()
		cellA.Value = "姓名"
		cellB := rowTitle.AddCell()
		cellB.Value = "手机号"
		cellC := rowTitle.AddCell()
		cellC.Value = "公司名称"
		cellD := rowTitle.AddCell()
		cellD.Value = "所属销售"
		for _, item := range listDate {
			row := sheet.AddRow()
			cellA := row.AddCell()
			cellA.Value = item.RealName
			cellB := row.AddCell()
			cellB.Value = item.Mobile
			cellC := row.AddCell()
			cellC.Value = item.CompanyName
			cellD := row.AddCell()
			cellD.Value = item.SellerName
		}
	} else {
		rowTitle := sheet.AddRow()
		cellA := rowTitle.AddCell()
		cellA.Value = "姓名"
		cellB := rowTitle.AddCell()
		cellB.Value = "公司名称"
		cellC := rowTitle.AddCell()
		cellC.Value = "所属销售"

		for _, item := range listDate {
			row := sheet.AddRow()
			cellA := row.AddCell()
			cellA.Value = item.RealName
			cellB := row.AddCell()
			cellB.Value = item.CompanyName
			cellC := row.AddCell()
			cellC.Value = item.SellerName
		}
	}

	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	downloadFileName := activityInfo.ResearchTheme + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Success = true
	br.Ret = 200
	br.IsAddLog = true
}

// @Title 取消报名
// @Description 取消报名接口
// @Param	request	body cygx.ActivitySpecialTripCancelReq true "type json string"
// @Success 200 操作成功
// @router /special/trip/cancel [post]
func (this *ActivitySpecialTripCoAntroller) TripCancel() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	var req cygx.ActivitySpecialTripCancelReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	userId := req.UserId
	activityId := req.ActivityId
	total, err := cygx.GetActivitySpecialTripCountByThisUser(activityId, strconv.Itoa(userId))
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	if total == 0 {
		br.Msg = "获取报名信息失败"
		br.ErrMsg = "获取失败，activityId:" + strconv.Itoa(activityId)
		return
	}
	activityInfo, errInfo := cygx.GetAddActivityInfoSpecialById(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
	}

	infoUser, err := cygx.GetUserAndCompanyNameList(userId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	//流水记录表
	itemBill := new(cygx.CygxActivitySpecialTripBill)
	itemBill.UserId = infoUser.UserId
	itemBill.ActivityId = activityInfo.ActivityId
	itemBill.CreateTime = time.Now()
	itemBill.Mobile = infoUser.Mobile
	itemBill.Email = infoUser.Email
	itemBill.CompanyId = infoUser.CompanyId
	itemBill.CompanyName = infoUser.CompanyName
	itemBill.RealName = infoUser.RealName
	itemBill.Source = 2
	itemBill.DoType = 2
	itemBill.BillDetailed = 1 // 流水加一
	itemBill.RegisterPlatform = 3
	itemBill.ChartPermissionId = activityInfo.ChartPermissionId
	itemBill.ChartPermissionName = activityInfo.ChartPermissionName
	itemBill.AdminId = sysUser.AdminId

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

	resultTime := utils.StrTimeToTime(activityInfo.ActivityTime)
	//48小时之内的取消也扣除一次参会记录
	var isValid int
	if time.Now().Add(+time.Hour * 48).After(resultTime) {
		isValid = 1
		itemBill.BillDetailed = 0 // 48小时之内取消的，照样扣点，流水不进行加一
	} else {
		err = cygxService.RebateTripRemainingtimesByUser(infoUser, activityInfo) // 返点
		if err != nil {
			br.Msg = "操作失败"
			br.ErrMsg = "操作失败,RebateTripRemainingtimesByUserErr:" + err.Error()
			return
		}
	}
	err = cygx.ActivitySpecialTripCancel(isValid, activityId, userId)
	if err != nil {
		br.Msg = "修改失败"
		br.ErrMsg = "修改失败 Err:" + err.Error()
		return
	}
	//userType, tripRemaining, mapChartName, err := cygxService.GetChartPermissionSpecialSurplusByCompany(infoUser.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 := cygxService.HandleActivitySpecialTripBillTotalText(infoUser.CompanyId)
	if err != nil {
		br.Msg = "报名失败，"
		br.ErrMsg = "二次报名，更改报名是否有效状态失败，Err:" + err.Error()
		return
	}
	itemBill.Total = totalText
	err = cygx.AddCygxActivitySpecialTripBill(itemBill)
	if err != nil {
		br.Msg = "修改失败"
		br.ErrMsg = "修改失败流水记录添加失败 Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}

// @Title 到会详情/提交到会详情
// @Description 报名详情列表接口
// @Param   ActivityId   query   int  true     "活动ID"
// @Success 200 {object} cygx.GetAppointmentSpecialListRsep
// @router /special/trip/meetDetial [get]
func (this *ActivitySpecialTripCoAntroller) MeetDetial() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	activityId, _ := this.GetInt("ActivityId")
	if activityId < 1 {
		br.Msg = "活动不存在"
		return
	}
	activityInfo, err := cygx.GetAddActivityInfoSpecialById(activityId)
	if err != nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，Err:activityId：" + strconv.Itoa(activityId)
		return
	}

	respList := new(cygx.SpecialMeetingDetailRespList)
	if activityInfo.IsSubmitMeeting == 0 {
		sqlStr := `  AND s.is_cancel = 0`
		list, err := cygx.GetCygxActivitySpecialTripList(activityId, sqlStr)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		for _, v := range list {
			item := new(cygx.CygxActivitySpecialMeetingDetailResp)
			item.UserId = v.UserId
			item.RealName = v.RealName
			item.CompanyName = v.CompanyName
			respList.List = append(respList.List, item)
		}
	} else {
		respList.List, err = cygx.GetCygxActivitySpecialMeetingDetailListByActivity(activityId)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		UserMap, err := cygxService.GetSpecialTripUserMap(activityId)
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败，Err:" + err.Error()
			return
		}
		for k, v := range respList.List {
			if v.IsMeeting == 1 {
				if _, ok := UserMap[v.UserId]; !ok {
					respList.List[k].IsMeeting = 2
				}
				respList.List[k].Operation = true
			}
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = respList
}

// @Title 提交线下到会情况
// @Description 提交线下到会情况接口
// @Param	request	body cygx.MeetingDoRep true "type json string"
// @Success 200 操作成功
// @router /special/trip/meetingDo [post]
func (this *ActivitySpecialTripCoAntroller) MeetingDo() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	var req cygx.MeetingSpeciaDoRep
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	var userIdArr []int
	var newMeetingUserid = make(map[int]bool) //新提交的到会的额用户ID
	meetingUids := req.UserIds
	if len(meetingUids) == 0 {
		meetingUids = "0"
	} else {
		//过滤字段
		slice := strings.Split(meetingUids, ",")
		meetingUids = ""
		for _, v := range slice {
			if v != "" {
				meetingUids += v + ","
				userId, _ := strconv.Atoi(v)
				if userId > 0 {
					userIdArr = append(userIdArr, userId)
					newMeetingUserid[userId] = true
				}
			}
		}
		meetingUids = strings.TrimRight(meetingUids, ",")
	}
	activityId := req.ActivityId
	activityInfo, err := cygx.GetAddActivityInfoSpecialById(activityId)
	if err != nil {
		br.Msg = "活动不存在"
		br.ErrMsg = "活动ID错误，Err:activityId：" + strconv.Itoa(activityId)
		return
	}
	//校验活动后台管理员、销售是否有修改权限
	havePower, popupMsg, err := cygxService.CheckActivitySpecialUpdatePower(AdminUser.AdminId, activityInfo)
	if err != nil {
		br.Msg = "获取管理员身份信息失败"
		br.ErrMsg = "获取管理员身份信息失败，Err:" + err.Error()
		return
	}
	if !havePower {
		br.Msg = popupMsg
		return
	}
	noMeetingUids, err := cygx.GetSpecialTripUserIds(activityId, meetingUids) //未到会的用户ID
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取客户信息失败,Err:" + err.Error()
		return
	}
	var allUids string
	if len(noMeetingUids) > 0 {
		allUids = noMeetingUids + "," + meetingUids
	} else {
		allUids = meetingUids
	}
	listUser, err := cygx.GetUserAndCompanyNameListByUids(allUids)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	UserMap, err := cygxService.GetSpecialTripUserMap(activityId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}

	var condition string
	var pars []interface{}
	condition += " AND is_meeting = 1  AND  activity_id = ? "
	pars = append(pars, activityId)
	listOldMeetingDetail, err := cygx.GetCygxActivitySpecialMeetingDetailList(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "GetCygxActivitySpecialMeetingDetailList，Err:" + err.Error()
		return
	}
	//获取之前已经到会的人
	//var oldMeetingUserid = make(map[int]bool)

	pars = make([]interface{}, 0)
	condition = "  AND  activity_id = ? "
	pars = append(pars, activityId)
	listTripBill, err := cygx.GetCygxActivitySpecialTripBill(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "GetCygxActivitySpecialTripBill，Err:" + err.Error()
		return
	}
	//获取用户最后一次的扣点状态
	mapUserLastTripBill := make(map[int]*cygx.CygxActivitySpecialTripBill)
	for _, v := range listTripBill {
		mapUserLastTripBill[v.UserId] = v
	}

	var items []*cygx.CygxActivitySpecialMeetingDetail
	var itemsBill []*cygx.CygxActivitySpecialTripBill
	if len(listOldMeetingDetail) > 0 {
		for _, v := range listOldMeetingDetail {
			if mapUserLastTripBill[v.UserId] == nil {
				continue
			}
			//如果上一次空降的用户，这一次提交的时候没有带入，而且还被扣点了，那么就进行返点处理
			if !newMeetingUserid[v.UserId] && v.IsAirborne == 1 && mapUserLastTripBill[v.UserId].BillDetailed < 0 {
				var itemBill = new(cygx.CygxActivitySpecialTripBill)
				//流水记录表
				itemBill.UserId = v.UserId
				itemBill.ActivityId = activityInfo.ActivityId
				itemBill.CreateTime = time.Now()
				itemBill.Mobile = v.Mobile
				itemBill.Email = v.Email
				itemBill.CompanyId = v.CompanyId
				itemBill.CompanyName = v.CompanyName
				itemBill.RealName = v.RealName
				itemBill.Source = 2
				itemBill.DoType = 2
				itemBill.BillDetailed = 1 // 流水加一
				itemBill.RegisterPlatform = 1
				itemBill.ChartPermissionId = activityInfo.ChartPermissionId
				itemBill.ChartPermissionName = activityInfo.ChartPermissionName
				itemBill.AdminId = AdminUser.AdminId
				itemBill.Way = 2
				userType, tripRemaining, mapChartName, err := cygxService.GetChartPermissionSpecialSurplusByCompany(v.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, "+")
				}
				itemsBill = append(itemsBill, itemBill)
			}
		}
	}

	for _, v := range listUser {
		var item = new(cygx.CygxActivitySpecialMeetingDetail)
		item.UserId = v.UserId
		item.ActivityId = activityId
		item.CreateTime = time.Now()
		item.Mobile = v.Mobile
		item.Email = v.Email
		item.CompanyId = v.CompanyId
		item.CompanyName = v.CompanyName
		item.IsMeeting = 1
		item.RealName = v.RealName
		//添加空降人员字段
		if _, ok := UserMap[v.UserId]; !ok {
			item.IsAirborne = 1
		}
		var itemBill = new(cygx.CygxActivitySpecialTripBill)
		//如果是空降客户,(没有扣点记录，或者上一次的流水不为负) 就进行扣点处理
		if item.IsAirborne == 1 && (mapUserLastTripBill[v.UserId] == nil || mapUserLastTripBill[v.UserId].BillDetailed >= 0) {
			//流水记录表
			itemBill.UserId = v.UserId
			itemBill.ActivityId = activityInfo.ActivityId
			itemBill.CreateTime = time.Now()
			itemBill.Mobile = v.Mobile
			itemBill.Email = v.Email
			itemBill.CompanyId = v.CompanyId
			itemBill.CompanyName = v.CompanyName
			itemBill.RealName = v.RealName
			itemBill.Source = 2
			itemBill.DoType = 1
			itemBill.BillDetailed = -1 // 流水减一
			itemBill.RegisterPlatform = 1
			itemBill.ChartPermissionId = activityInfo.ChartPermissionId
			itemBill.ChartPermissionName = activityInfo.ChartPermissionName
			itemBill.AdminId = AdminUser.AdminId
			itemBill.Way = 2
			userType, tripRemaining, mapChartName, err := cygxService.GetChartPermissionSpecialSurplusByCompany(v.CompanyId)
			if err != nil {
				br.Msg = "获取专项调研剩余次数失败"
				br.ErrMsg = "获取专项调研剩余次数失败,err:" + err.Error()
				return
			}
			if userType == 2 {
				tripRemaining -= 1
				itemBill.Total = strconv.Itoa(tripRemaining) + "次"
			} else {
				for k, num := range mapChartName {
					if activityInfo.ChartPermissionName == k {
						num -= 1
					}
					itemBill.Total += k + strconv.Itoa(num) + "次+"
				}
				itemBill.Total = strings.TrimRight(itemBill.Total, "+")
			}
			itemsBill = append(itemsBill, itemBill)
		}
		items = append(items, item)
	}
	err = cygx.MeetingDopecialMeet(meetingUids, noMeetingUids, activityId, items, itemsBill)
	if err != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "操作失败,Err:" + err.Error()
		return
	}
	go cygxService.ActivitySpecialUserLabelLogAdd(activityId, userIdArr)
	//添加操作日志记录
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}

// @Title 修改外呼号码
// @Description 修改外呼号码接口
// @Param	request	body cygx.OutboundMobileEditResp true "type json string"
// @Success 200 操作成功
// @router /special/trip/outboundMobileEdit [post]
func (this *ActivitySpecialTripCoAntroller) OutboundMobileEdit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	var req cygx.OutboundMobileEditResp
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	id := req.Id
	outboundMobile := req.OutboundMobile
	countryCode := req.CountryCode
	err = cygx.SpecialTripOutboundMobileEdit(id, outboundMobile, countryCode)
	if err != nil {
		br.Msg = "修改失败"
		br.ErrMsg = "修改失败 Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"
	br.IsAddLog = true
}

// @Title 模版消息发送客户类型列表
// @Description 模版消息发送客户类型列表接口
// @Success Ret=200
// @router /special/trip/tempMsg/sendGroupList [get]
func (this *ActivitySpecialTripCoAntroller) SendGroupList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	list := make([]cygx.SendGroup, 0)
	list = append(list, cygx.SendGroup{
		Id:   1,
		Name: "已报名客户",
	})
	br.Ret = 200
	br.Success = true
	br.Data = list
}

// @Title 发送模版消息
// @Description 发送模版消息接口
// @Param	request	body cygx.AddOutboundPersonnelItm true "type json string"
// @Success 200 操作成功
// @router /special/trip/tempMsg [post]
func (this *ActivitySpecialTripCoAntroller) TempMsg() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		return
	}
	var req cygx.ActivitySpecialSignupTempMsgReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	idSlice := strings.Split(req.ActivityIds, ",")
	for _, sId := range idSlice {
		id, e := strconv.Atoi(sId)
		if e != nil {
			br.Msg = "活动Id参数异常"
			br.ErrMsg = "参数解析异常, Err:" + e.Error()
			return
		}
		var openIdList []*cygx.OpenIdList
		idMap := make(map[string]string, 0)
		//1已报名
		if strings.Contains(req.SendGroup, "1") {
			listSignup, err := cygx.GetCygxActivitySpecialTripListByActivityId(id)
			if err != nil {
				br.Msg = "查询报名信息失败失败"
				br.ErrMsg = "GetCygxActivitySpecialTripListByActivityId，Err:" + err.Error()
				return
			}
			if len(listSignup) == 0 {
				continue
			}
			var mobileArr []string
			for _, v := range listSignup {
				if v.Mobile != "" {
					mobileArr = append(mobileArr, v.Mobile)
				}
			}
			mobileLen := len(mobileArr)
			var condition string
			var pars []interface{}
			if mobileLen > 0 {
				condition += ` AND u.mobile IN (` + utils.GetOrmInReplace(mobileLen) + `)`
				pars = append(pars, mobileArr)
			}
			//list, err := models.GetActivitySpecialOpenIdListMobile(condition, pars)
			//if err != nil {
			//	br.Msg = "查询openId失败"
			//	br.ErrMsg = "查询openId失败，Err:" + err.Error()
			//	return
			//}

			if mobileLen == 0 {
				return
			}
			list, err := cygx.GetUserRecordListByMobileArr(mobileArr)
			for _, idList := range list {
				openIdList = append(openIdList, idList)
				idMap[idList.OpenId] = idList.OpenId
			}
		}

		if len(openIdList) > 0 {
			openIdArr := make([]string, len(openIdList))
			for i, v := range openIdList {
				openIdArr[i] = v.OpenId
			}
			sendInfo := new(services.SendWxTemplate)
			sendInfo.Keyword1 = req.ResearchTheme
			sendInfo.Keyword2 = req.Content
			sendInfo.TemplateId = utils.WxMsgTemplateIdActivityChangeApplyXzs
			sendInfo.RedirectUrl = utils.WX_MSG_PATH_ACTIVITY_SPECIAL_DETAIL + strconv.Itoa(id)
			if utils.RunMode == "debug" {
				sendInfo.RedirectUrl = utils.WX_MSG_PATH_ACTIVITY_SPECIAL_DETAIL + strconv.Itoa(110) //测试环境调正式的ID
			}
			sendInfo.RedirectTarget = 3
			sendInfo.Resource = strconv.Itoa(id)
			sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ACTIVITY_CUSTOMIZE
			sendInfo.OpenIdArr = openIdArr
			e = services.SendTemplateMsg(sendInfo)
			if e != nil {
				br.Msg = "推送模板消息失败！"
				br.ErrMsg = "参数解析失败，Err:" + e.Error()
				return
			}
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "发送成功"
}
