package controllers

import (
	"encoding/json"
	"fmt"
	"hongze/hongze_open_api/models/request/yidong"
	cygxActivity "hongze/hongze_open_api/models/tables/cygx_activity"
	"hongze/hongze_open_api/services/alarm_msg"
	servicesYidong "hongze/hongze_open_api/services/yidong"
	"hongze/hongze_open_api/utils"
	"math"
	"strconv"
	"strings"
	"time"
)

// 易董
type YiDongController struct {
	BaseCommon
}

// YiDongController
// @Title 易董提交报名用户审核接口
// @Description 易董提交报名用户审核接口
// @Param	request	body yidong.ActivityExamineReq true "type json string"
// @Success 200 创建成功
// @router /activity/examine/signup [post]
func (c *YiDongController) ActivityExamine() {
	var req yidong.ActivityExamineReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.FailWithMessage("参数解析异常")
		return
	}
	activityIdYiDong := req.ActivityId
	timeInt := req.Time
	list := req.List
	appid := req.Appid
	timeUnix := time.Now().Unix() //当前格林威治时间，int64类型
	timestamp := int64(timeInt)
	if math.Abs(float64(timeUnix-timestamp)) > 600 {
		c.FailWithMessage("当前时间异常，请调整设备时间与北京时间一致：" + strconv.Itoa(timeInt))
		return
	}
	//校验 APPID 与ip白名单
	ip := c.Ctx.Input.IP()
	err = servicesYidong.CheckAppidAndIp(appid, ip)
	if err != nil {
		c.FailWithMessage(err.Error())
		return
	}
	//校验 签名

	signStr := servicesYidong.GetSign(activityIdYiDong, timeInt)
	fmt.Println("____")
	fmt.Println(signStr)
	ownSign := req.Sign
	if ownSign != signStr {
		c.FailWithMessage("签名错误！")
		return
	}
	activityInfo, err := cygxActivity.GetAddActivityInfoById(activityIdYiDong)
	if err != nil {
		c.FailWithMessage("会议id异常：" + activityIdYiDong)
		return
	}
	activityId := activityInfo.ActivityId

	var examineMobile string
	var delMyMobile string     //审核不通过需要删除日程的手机号
	var delSignupMobile string //取消活动需要删除报名信息的手机号
	var itemsLog []*cygxActivity.CygxYidongActivityExamineStatus
	for _, v := range list {
		var dateTxt = []byte(v.Mobile)
		resultDe := utils.DesBase64Decrypt(dateTxt)
		deMobile := string(resultDe)
		if deMobile == "" {
			go alarm_msg.SendAlarmMsg("加密手机号解密失败："+v.Mobile, 3)
			c.FailWithMessage("加密手机号解密失败：" + v.Mobile)
			return
		}

		examineMobile += "'" + deMobile + "'" + ","
		itemlog := new(cygxActivity.CygxYidongActivityExamineStatus)
		//记录日志
		itemlog.ActivityId = activityId
		itemlog.YidongActivityId = activityIdYiDong
		itemlog.CreateTime = time.Now()
		itemlog.ExamineTime = v.CreateTime
		itemlog.Mobile = deMobile
		itemlog.YidongExamineStatus = v.ExamineStatus
		itemsLog = append(itemsLog, itemlog)
	}

	//记录日志
	err = cygxActivity.AddActivityItemsLogNumMulti(itemsLog)
	if err != nil {
		c.FailWithMessage("修改活动审核状态失败：" + activityIdYiDong)
		go alarm_msg.SendAlarmMsg("修改活动审核状态失败AddActivityItemsLogNumMulti："+err.Error()+"活动ID"+activityIdYiDong, 3)
		return
	}

	//以下处理传过来的逻辑
	// 获取已经报名了的用户列表
	signupList, err := cygxActivity.GetActivitySignupListByActivity(activityId)
	if err != nil {
		c.FailWithMessage("会议id异常：" + activityIdYiDong)
		return
	}

	mapSignUp := make(map[string]string)
	for _, v := range signupList {
		mapSignUp[v.Mobile] = v.Mobile
	}

	// 获取我的日程列表
	myScheduleList, err := cygxActivity.GetCygxMyScheduleList(activityId)
	if err != nil {
		c.FailWithMessage("会议id异常：" + activityIdYiDong)
		return
	}

	mapMyScheduleList := make(map[string]string)
	for _, v := range myScheduleList {
		mapMyScheduleList[v.Mobile] = v.Mobile
	}

	examineMobile = strings.TrimRight(examineMobile, ",")
	userList, err := cygxActivity.GetUserListByMobile(examineMobile)
	if err != nil {
		c.FailWithMessage("操作失败，用户信息不存在")
		return
	}
	mapUserinfo := make(map[string]*cygxActivity.CygxActivitySignup)
	mapMySchedule := make(map[string]*cygxActivity.CygxMySchedule)
	for _, v := range userList {
		item := new(cygxActivity.CygxActivitySignup)
		item.UserId = v.UserId
		item.RealName = v.RealName
		item.SellerName = v.SellerName
		item.ActivityId = activityId
		item.CreateTime = time.Now()
		item.Mobile = v.Mobile
		item.Email = v.Email
		item.CompanyId = v.CompanyId
		item.CompanyName = v.CompanyName
		item.Source = 3
		//优先绑定用户修改过的外呼手机号
		if v.OutboundMobile != "" {
			item.OutboundMobile = v.OutboundMobile
			if v.OutboundCountryCode == "" {
				item.CountryCode = "86"
			} else {
				item.CountryCode = v.OutboundCountryCode
			}
		} else {
			item.OutboundMobile = v.Mobile
			if v.CountryCode == "" {
				item.CountryCode = "86"
			} else {
				item.CountryCode = v.CountryCode
			}
		}
		item.SignupType = 1
		mapUserinfo[v.Mobile] = item

		//添加我的日程
		itemMySchedule := new(cygxActivity.CygxMySchedule)
		itemMySchedule.UserId = v.UserId
		itemMySchedule.ActivityId = activityId
		itemMySchedule.CreateTime = time.Now()
		itemMySchedule.Mobile = v.Mobile
		itemMySchedule.Email = v.Email
		itemMySchedule.CompanyId = v.CompanyId
		itemMySchedule.CompanyName = v.CompanyName
		mapMySchedule[v.Mobile] = itemMySchedule

	}
	var items []*cygxActivity.ExamineStatusReq
	var itemsAdd []*cygxActivity.CygxActivitySignup

	var itemsMyAdd []*cygxActivity.CygxMySchedule
	for _, v := range list {
		item := new(cygxActivity.ExamineStatusReq)
		var dateTxt = []byte(v.Mobile)
		resultDe := utils.DesBase64Decrypt(dateTxt)
		deMobile := string(resultDe)
		if mapSignUp[deMobile] != "" {
			item.ActivityId = activityId
			item.Mobile = deMobile
			item.ExamineStatus = v.ExamineStatus
			items = append(items, item)
		} else {
			if mapUserinfo[deMobile] != nil {
				mapUserinfo[deMobile].YidongExamineStatus = v.ExamineStatus
				if v.ExamineStatus != 3 {
					itemsAdd = append(itemsAdd, mapUserinfo[deMobile])
				}
			}
		}

		//处理我的日程
		if mapMyScheduleList[deMobile] != "" {
			if v.ExamineStatus != 1 {
				delMyMobile += "'" + deMobile + "'" + ","
			}
			if v.ExamineStatus == 3 {
				delSignupMobile += "'" + deMobile + "'" + ","
			}
		} else {
			if mapMySchedule[deMobile] != nil {
				if v.ExamineStatus == 1 {
					itemsMyAdd = append(itemsMyAdd, mapMySchedule[deMobile])
				}
			}
		}
	}

	//fmt.Println(delSignupMobile)

	//return

	//处理要删除的日程
	delMyMobile = strings.TrimRight(delMyMobile, ",")
	if delMyMobile != "" {
		fmt.Println("删除日程")
		err = cygxActivity.DelCygxMyScheduleList(delMyMobile, activityId)
		if err != nil {
			go alarm_msg.SendAlarmMsg("处理要删除的日程失败 DelCygxMyScheduleList："+err.Error()+"活动ID"+activityIdYiDong, 3)
		}
	}

	//处理要删除的报名信息
	delSignupMobile = strings.TrimRight(delSignupMobile, ",")
	if delSignupMobile != "" {
		fmt.Println("处理要删除的报名信息")
		err = cygxActivity.DelCygxcActivitySignup(delSignupMobile, activityId)
		if err != nil {
			go alarm_msg.SendAlarmMsg("处理要删除的报名信息失败 DelCygxMyScheduleList："+err.Error()+"活动ID"+activityIdYiDong, 3)
		}
	}

	//修改审核状态
	err = cygxActivity.UpdateActivitySignupNumMulti(items)
	if err != nil {
		fmt.Println(err, "UpdateActivitySignupNumMulti")
		go alarm_msg.SendAlarmMsg("修改活动审核状态失败："+err.Error()+"活动ID"+activityIdYiDong, 3)

	}

	// 批量添加报名信息
	err = cygxActivity.AddActivitySignupNumMulti(itemsAdd)
	if err != nil {
		fmt.Println(err, "AddActivitySignupNumMulti")
		go alarm_msg.SendAlarmMsg("修改活动审核状态失败："+err.Error()+"活动ID"+activityIdYiDong, 3)
	}

	// 批量添加我的日程
	err = cygxActivity.AddCygxMyScheduleLNumMulti(itemsMyAdd)
	if err != nil {
		fmt.Println(err, "AddCygxMyScheduleLNumMulti")
		go alarm_msg.SendAlarmMsg("修改活动审核状态失败："+err.Error()+"活动ID"+activityIdYiDong, 3)
	}
	c.OkWithMessage("操作成功")
}

func init2342() {
	//allow 59.46.229.165;
	//allow 123.185.222.0/24;
	//allow 123.185.223.0/24;
	//allow 59.36.22.17;
	//allow 120.86.187.82;
	//202.105.122.162

	//	@张怀民 您好，不好意思，刚才发错了，我们这边生产IP是个地址池，
	//生产:
	//	49.4.0.0/16
	//	119.3.0.0/16
	//	117.78.0.0/16
	//	43.254.0.0/16
	//allow 59.36.22.17;
	//allow 120.86.187.82;
	//测试:
	//	121.36.45.174
	//	麻烦帮忙配置一下白名单

	var ipstr string
	var ipstrs string
	ipstr = "43.254.0.0."

	for i := 0; i <= 16; i++ {
		fmt.Println(i)
		ipstrs += ipstr + strconv.Itoa(i) + ","
		//ipstr += ipstr + strconv.Itoa(i)
	}
	fmt.Println(ipstrs)
}

// YiDongController
// @Title 易董提交报名时，获取用户信息接口
// @Description 易董提交报名时，获取用户信息接口
// @Param	request	body yidong.ActivityExamineReq true "type json string"
// @Success 200 创建成功
// @router /activity/user/signup [post]
func (c *YiDongController) UserSignup() {
	var req yidong.ActivitySignUpReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.FailWithMessage("参数解析异常")
		return
	}
	activityIdYiDong := req.ActivityId
	timeInt := req.Time
	appid := req.Appid
	mobile := req.Mobile
	timeUnix := time.Now().Unix() //当前格林威治时间，int64类型
	timestamp := int64(timeInt)
	if math.Abs(float64(timeUnix-timestamp)) > 600 {
		c.FailWithMessage("当前时间异常，请调整设备时间与北京时间一致：" + strconv.Itoa(timeInt))
		return
	}
	//校验 APPID 与ip白名单
	ip := c.Ctx.Input.IP()
	err = servicesYidong.CheckAppidAndIp(appid, ip)
	if err != nil {
		c.FailWithMessage(err.Error())
		return
	}
	//校验 签名

	signStr := servicesYidong.GetSign(activityIdYiDong, timeInt)
	fmt.Println("____")
	fmt.Println(signStr)
	ownSign := req.Sign
	if ownSign != signStr {
		c.FailWithMessage("签名错误！")
		return
	}
	activityInfo, err := cygxActivity.GetAddActivityInfoById(activityIdYiDong)
	if err != nil {
		c.FailWithMessage("会议id异常：" + activityIdYiDong)
		return
	}
	activityId := activityInfo.ActivityId

	var dateTxt = []byte(mobile)
	resultDe := utils.DesBase64Decrypt(dateTxt)
	deMobile := string(resultDe)
	if deMobile == "" {
		go alarm_msg.SendAlarmMsg("加密手机号解密失败："+mobile, 3)
		c.FailWithMessage("加密手机号解密失败：" + mobile)
		return
	}

	item := new(cygxActivity.CygxYidongActivitySignupLog)
	item.ActivityId = activityId
	item.YidongActivityId = activityIdYiDong
	item.CreateTime = time.Now()
	item.Mobile = deMobile

	err = cygxActivity.AddCygxYidongActivitySignupLog(item)
	if err != nil {
		fmt.Println(err)
		c.FailWithMessage("获取用户信息失败：" + activityIdYiDong)
		go alarm_msg.SendAlarmMsg("修改活动审核状态失败："+err.Error()+"活动ID"+activityIdYiDong, 3)
		return
	}
	userInfo, err := cygxActivity.GetAddActivityInfoByMobile(deMobile)
	if err != nil {
		fmt.Println(err)
		c.FailWithMessage("获取用户信息失败：" + activityIdYiDong)
		go alarm_msg.SendAlarmMsg("修改活动审核状态失败："+err.Error()+"活动ID"+activityIdYiDong, 3)
		return
	}
	c.OkDetailed(userInfo, "获取成功")
}
