package cygx

import (
	"errors"
	"fmt"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/services/alarm_msg"
	"hongze/hz_crm_api/utils"
	"strconv"
)

// 获取线上活动到会更新时间
func GetActivityMeetUpdateTime(activityIdS []int) (mapResp map[int]string, err error) {
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("获取线上活动到会更新时间失败，Err："+err.Error()+fmt.Sprint(activityIdS), 3)
		}
	}()
	lenNum := len(activityIdS)
	if lenNum == 0 {
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND a.activity_id IN (` + utils.GetOrmInReplace(lenNum) + `)`
	pars = append(pars, activityIdS)
	condition += ` GROUP BY a.activity_id  `
	list, e := cygx.GetCygxActivityAttendanceDetailList(condition, pars, 0, lenNum)
	if e != nil {
		err = errors.New("GetCygxActivityAttendanceDetailList，Err" + e.Error())
		return
	}
	mapResp = make(map[int]string, 0)
	for _, v := range list {
		mapResp[v.ActivityId] = v.CreateTime.Format(utils.FormatDateTime)
	}
	return
}

func AddCygxActivityMeetDetailLogOffline(meetingUids string, activityId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println("err：", err)
			go alarm_msg.SendAlarmMsg("添加线下到会记录失败，Err："+err.Error()+fmt.Sprint(activityId), 3)
		}
	}()
	if meetingUids == "" {
		return
	}

	list, e := cygx.GetOfflineMeetingListByUser(meetingUids, activityId)
	if e != nil {
		err = errors.New("GetOfflineMeetingListByUser" + e.Error())
		return
	}
	var companyIdArr []int
	var mobileArr []string
	var items []*cygx.CygxActivityMeetDetailLog

	if err != nil {
		return
	}
	//插入新的数据
	for _, v := range list {
		item := new(cygx.CygxActivityMeetDetailLog)
		item.ActivityId = v.ActivityId
		item.Mobile = v.Mobile
		item.CompanyName = v.CompanyName
		item.CompanyId = v.CompanyId
		item.CreateTime = v.CreateTime
		if v.Mobile != "" {
			mobileArr = append(mobileArr, v.Mobile)
		}
		if v.CompanyId > 0 {
			companyIdArr = append(companyIdArr, v.CompanyId)
		}
		items = append(items, item)
	}

	var condition string
	var pars []interface{}
	var itemsUpdateCompany []*cygx.MeetDetailLoggGroupCount
	lencompanyIdArr := len(companyIdArr)

	if lencompanyIdArr > 0 {
		condition = ` AND company_id IN (` + utils.GetOrmInReplace(lencompanyIdArr) + `)  GROUP BY company_id  `
		pars = append(pars, companyIdArr)
		listCompanyIdCount, e := cygx.GetMeetDetailLogGroupCount(condition, pars)
		if e != nil {
			err = errors.New("GetMeetDetailLogGroupCount" + e.Error())
			return
		}

		for _, v := range listCompanyIdCount {
			item := new(cygx.MeetDetailLoggGroupCount)
			item.CompanyId = v.CompanyId
			item.Count = v.Count
			itemsUpdateCompany = append(itemsUpdateCompany, item)
		}
	}
	fmt.Println(111)
	var itemsUpdateMobile []*cygx.MeetDetailLoggGroupCount
	lenmobileArr := len(mobileArr)
	if lenmobileArr > 0 {
		pars = make([]interface{}, 0)
		condition = ` AND mobile IN (` + utils.GetOrmInReplace(lenmobileArr) + `)  GROUP BY mobile  `
		pars = append(pars, mobileArr)
		listMobileCount, e := cygx.GetMeetDetailLogGroupCount(condition, pars)
		if e != nil {
			err = errors.New("GetMeetDetailLogGroupCount" + e.Error())
			return
		}
		for _, v := range listMobileCount {
			item := new(cygx.MeetDetailLoggGroupCount)
			item.Mobile = v.Mobile
			item.Count = v.Count
			itemsUpdateMobile = append(itemsUpdateMobile, item)
		}
	}

	e = cygx.UpdatecygxActivityMeetDetailLogOffline(items, itemsUpdateCompany, itemsUpdateMobile, activityId)
	if e != nil {
		err = errors.New("UpdatecygxActivityMeetDetailLogOffline" + e.Error())
		return
	}
	return
}

// AddctivitySignupDetailList
func AddctivitySignupDetailList(itemsDetail []*cygx.CygxActivitySignupDetail, activityId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("通过进门财经添加用户参数信息失败 ErrMsg:"+err.Error(), 2)
		}
	}()

	activityIds := make([]int, 0)
	activityIds = append(activityIds, activityId)
	actLen := len(activityIds)
	var condition string
	var pars []interface{}
	if actLen > 0 {
		condition += ` AND activity_id IN (` + utils.GetOrmInReplace(actLen) + `)`
		pars = append(pars, activityIds)
	}

	signUpDetailList, err := cygx.GetSignupDetailList(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}

	mapsignUpDetai := make(map[string]string)
	if len(signUpDetailList) > 0 {
		for _, v := range signUpDetailList {
			mapsignUpDetai[fmt.Sprint("ActivityId", v.ActivityId, "Mobile", v.Mobile)] = v.Mobile
		}
	}

	//获取当天已经结束了 活动的报名人数
	signUpList, err := cygx.GetSignupDetailBySignup(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	//建立外呼号与手机号的绑定
	mapsignUp := make(map[string]string)
	if len(signUpList) > 0 {
		for _, v := range signUpList {
			mapsignUp[fmt.Sprint(v.OutboundMobile)] = v.Mobile
		}
	}

	var itemsAdd []*cygx.CygxActivitySignupDetail
	var itemsUpdate []*cygx.CygxActivitySignupDetail

	for _, v := range itemsDetail {
		var item = new(cygx.CygxActivitySignupDetail)
		item.ActivityId = v.ActivityId
		//item.RealName = v.RealName
		//如果手机号存在那么就是报名的，不存在就是直接参与的
		if _, ok := mapsignUp[v.Mobile]; ok {
			item.Mobile = mapsignUp[v.Mobile]
		} else {
			item.Mobile = v.Mobile
		}
		item.UserId = v.UserId
		item.RealName = v.RealName
		item.OutboundMobile = v.Mobile
		item.CompanyName = v.CompanyName
		item.CompanyId = v.CompanyId
		item.SellerName = v.SellerName
		item.FirstMeetingTime = v.FirstMeetingTime
		item.LastMeetingTime = v.LastMeetingTime
		item.Duration = v.Duration
		item.MeetingTypeStr = v.MeetingTypeStr
		item.MeetingAuthentication = v.MeetingAuthentication
		item.MeetingStatusStr = v.MeetingStatusStr
		item.CreateTime = v.CreateTime
		item.Position = v.Position
		item.IsMeeting = v.IsMeeting
		item.UseridEntity = v.UseridEntity
		item.ActivityTime = v.ActivityTime
		item.CrmCompanyMapStatusId = v.CrmCompanyMapStatusId

		if _, ok := mapsignUpDetai[fmt.Sprint("ActivityId", v.ActivityId, "Mobile", item.Mobile)]; !ok {
			itemsAdd = append(itemsAdd, item)
		} else {
			itemsUpdate = append(itemsUpdate, item)
		}
	}
	//return err
	if len(itemsAdd) > 0 {
		err = cygx.AddCygxActivitySignupDetail(itemsAdd)
		if err != nil {
			return
		}
	}

	if len(itemsUpdate) > 0 {
		err = cygx.UpdateActivitySignupDetailMulti(itemsUpdate)
		if err != nil {
			return
		}
	}

	return err
}

// AddctivitySignupDetailListByHand 手动匹配进门财经信息
func AddctivitySignupDetailListByHand(itemsDetail []*cygx.CygxActivityAttendanceDetail, activityId int) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg("通过进门财经添加用户参数信息失败 ErrMsg:"+err.Error(), 2)
		}
	}()

	activityIds := make([]int, 0)
	activityIds = append(activityIds, activityId)
	actLen := len(activityIds)
	var condition string
	var pars []interface{}
	if actLen > 0 {
		condition += ` AND activity_id IN (` + utils.GetOrmInReplace(actLen) + `)`
		pars = append(pars, activityIds)
	}

	signUpDetailList, err := cygx.GetSignupDetailList(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}

	mapsignUpDetai := make(map[string]string)
	if len(signUpDetailList) > 0 {
		for _, v := range signUpDetailList {
			mapsignUpDetai[fmt.Sprint("ActivityId", v.ActivityId, "Mobile", v.Mobile)] = v.Mobile
		}
	}

	//获取当天已经结束了 活动的报名人数
	signUpList, err := cygx.GetSignupDetailBySignup(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	//建立外呼号与手机号的绑定
	mapsignUp := make(map[string]string)
	if len(signUpList) > 0 {
		for _, v := range signUpList {
			mapsignUp[fmt.Sprint(v.OutboundMobile)] = v.Mobile
		}
	}

	var itemsAdd []*cygx.CygxActivitySignupDetail
	var itemsUpdate []*cygx.CygxActivitySignupDetail

	var mobiles []string
	mobileMap := make(map[string]bool)
	mobileUserMap := make(map[string]int)
	for _, v := range itemsDetail {
		if !mobileMap[v.Mobile] {
			mobiles = append(mobiles, v.Mobile)
		}
		mobileMap[v.Mobile] = true
	}

	//根据手机号获取这些用户的信息
	listUser, e := models.GetWxUserByOutboundMobiles(mobiles)
	if e != nil {
		err = errors.New("GetWxUserOutboundMobiles, Err: " + e.Error())
		return
	}

	for _, v := range listUser {
		mobileUserMap[v.Mobile] = int(v.UserId)
	}

	for _, v := range itemsDetail {
		var item = new(cygx.CygxActivitySignupDetail)
		item.ActivityId = v.ActivityId
		//item.RealName = v.RealName
		//如果手机号存在那么就是报名的，不存在就是直接参与的
		if _, ok := mapsignUp[v.Mobile]; ok {
			item.Mobile = mapsignUp[v.Mobile]
		} else {
			item.Mobile = v.Mobile
		}
		item.UserId = mobileUserMap[v.Mobile]
		item.RealName = v.RealName
		item.OutboundMobile = v.Mobile
		item.CompanyName = v.CompanyName
		item.CompanyId = v.CompanyId
		item.SellerName = v.SellerName
		item.FirstMeetingTime = v.FirstMeetingTime
		item.LastMeetingTime = v.LastMeetingTime
		item.Duration = v.Duration
		item.MeetingTypeStr = v.MeetingTypeStr
		item.MeetingAuthentication = v.MeetingAuthentication
		item.MeetingStatusStr = v.MeetingStatusStr
		item.CreateTime = v.CreateTime
		item.Position = v.Position
		item.IsMeeting = 1
		item.UseridEntity = v.UseridEntity
		item.ActivityTime = v.ActivityTime
		item.CrmCompanyMapStatusId = v.CrmCompanyMapStatusId

		if _, ok := mapsignUpDetai[fmt.Sprint("ActivityId", v.ActivityId, "Mobile", item.Mobile)]; !ok {
			itemsAdd = append(itemsAdd, item)
		} else {
			itemsUpdate = append(itemsUpdate, item)
		}
	}
	//return err
	if len(itemsAdd) > 0 {
		err = cygx.AddCygxActivitySignupDetail(itemsAdd)
		if err != nil {
			return
		}
	}

	if len(itemsUpdate) > 0 {
		err = cygx.UpdateActivitySignupDetailMulti(itemsUpdate)
		if err != nil {
			return
		}
	}

	return err
}

// AddctivitySignupDetailListByAdminSignup 已结束的活动，管理员手动添加报名，把信息写入到联系人列表参会信息中
func AddctivitySignupDetailListByAdminSignup(activityIdsStr string) (err error) {
	defer func() {
		if err != nil {
			fmt.Println(err)
			go alarm_msg.SendAlarmMsg(fmt.Sprint("已结束的活动，管理员手动添加报名，把信息写入到联系人列表参会信息中 ErrMsg:"+err.Error(), "activityIds:", activityIdsStr), 2)
		}
	}()

	var condition string
	var pars []interface{}
	condition = ` AND active_state = 3 AND  activity_id IN (` + activityIdsStr + `)  `
	list, e := cygx.GetActivityListAll(condition, pars, 0, 9999)
	if e != nil && e.Error() != utils.ErrNoRow() {
		err = errors.New("GetWxUserOutboundMobiles, Err: " + e.Error())
		return
	}
	if len(list) == 0 {
		return
	}

	var activityIds []int

	for _, v := range list {
		activityIds = append(activityIds, v.ActivityId)
	}

	actLen := len(activityIds)
	condition = ` AND activity_id IN (` + utils.GetOrmInReplace(actLen) + `)`
	pars = append(pars, activityIds)

	//获取已经写入的信息，并建立map
	signUpDetailList, err := cygx.GetSignupDetailList(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	mapsignUpDetai := make(map[string]string)
	if len(signUpDetailList) > 0 {
		for _, v := range signUpDetailList {
			mapsignUpDetai[fmt.Sprint("ActivityId", v.ActivityId, "Mobile", v.Mobile)] = v.Mobile
		}
	}

	pars = make([]interface{}, 0)
	condition = ` AND activity_id IN (` + utils.GetOrmInReplace(actLen) + `) AND do_fail_type = 0`
	pars = append(pars, activityIds)
	//获取成功报名的人员信息
	signUpList, err := cygx.GetSignupDetailBySignup(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	//建立外呼号与手机号的绑定
	mapsignUp := make(map[string]string)
	if len(signUpList) > 0 {
		for _, v := range signUpList {
			mapsignUp[fmt.Sprint(v.OutboundMobile)] = v.Mobile
		}
	}
	var items []*cygx.CygxActivitySignupDetail
	if len(signUpList) > 0 {
		for _, v := range signUpList {
			if _, ok := mapsignUpDetai[fmt.Sprint("ActivityId", v.ActivityId, "Mobile", v.Mobile)]; !ok {
				item := new(cygx.CygxActivitySignupDetail)
				item.UserId = v.UserId
				item.RealName = v.RealName
				item.SellerName = v.SellerName
				item.ActivityId = v.ActivityId
				item.CreateTime = v.CreateTime
				item.Mobile = v.Mobile
				item.OutboundMobile = v.OutboundMobile
				item.Email = v.Email
				item.CompanyId = v.CompanyId
				item.CompanyName = v.CompanyName
				item.SignupType = v.SignupType
				item.FailType = v.FailType
				item.DoFailType = v.DoFailType
				items = append(items, item)
			}
		}
	}
	if len(items) > 0 {
		e = cygx.AddCygxActivitySignupDetail(items)
		if e != nil {
			err = errors.New("AddCygxActivitySignupDetail, Err: " + e.Error())
			return
		}
	}

	return err
}

func init77777() {
	var condition string
	var pars []interface{}

	listAct, errList := cygx.GetActivityListAll(condition+"AND active_state = 3 AND activity_id > 3000  AND publish_status = 1 ", pars, 0, 9999)
	if errList != nil {
		fmt.Println(errList)
		return
	}

	fmt.Println(len(listAct))

	for _, v := range listAct {
		condition = ` AND a.activity_id  = ` + strconv.Itoa(v.ActivityId)
		//pars = append(pars)
		list, e := cygx.GetCygxActivityAttendanceDetailList(condition, pars, 0, 999)
		if e != nil {
			fmt.Println(e)
			return
		}

		fmt.Println("ActivityId", v.ActivityId, "list", len(list))

		AddctivitySignupDetailListByHand(list, v.ActivityId)
	}

}
