package cygx

import (
	"errors"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

//处理OCR识别图片建会的逻辑

//星期日 Sunday=Sun. 读音：英[ˈsʌndeɪ]美[ˈsʌnˌdeɪ]
//
//星期一 Monday=Mon. 读音：英[ˈmʌndeɪ]美[ˈmʌndeɪ]
//
//星期二 Tuesday=Tues. 读音：英[ˈtju:zdeɪ]美[ˈtu:zdeɪ]
//
//星期三 Wednesday=Wed. 读音：英[ˈwenzdeɪ]美[ˈwɛnzdi, -ˌde]
//
//星期四 Thursday=Thur./Thurs. 读音：英[ˈθɜ:zdeɪ]美[ˈθɜ:rzdeɪ]
//
//星期五 Friday=Fri. 读音：英[ˈfraɪdeɪ]美[ˈfraɪˌdeɪ]
//
//星期六 Saturday=Sat. 读音： 英[ˈsætədeɪ]美[ˈsætərdeɪ]

// 处理年月日格式
func ConvertActivityTitmeYMD(TitmeYMD string) (titmeYMDNew string) {
	titmeYMDNew = TitmeYMD
	titmeYMDNew = strings.Replace(titmeYMDNew, "/", "月", -1)
	//titmeYMDNew = strings.Replace(titmeYMDNew, "SUN", "日（周日）", -1)
	//titmeYMDNew = strings.Replace(titmeYMDNew, "MON", "日（周一）", -1)
	//titmeYMDNew = strings.Replace(titmeYMDNew, "TUE", "日（周二）", -1)
	//titmeYMDNew = strings.Replace(titmeYMDNew, "WED", "日（周三）", -1)
	//titmeYMDNew = strings.Replace(titmeYMDNew, "THU", "日（周四）", -1)
	//titmeYMDNew = strings.Replace(titmeYMDNew, "FRI", "日（周五）", -1)
	//titmeYMDNew = strings.Replace(titmeYMDNew, "SAT", "日（周六）", -1)

	titmeYMDNew = strings.Replace(titmeYMDNew, "SUN", "日", -1)
	titmeYMDNew = strings.Replace(titmeYMDNew, "MON", "日", -1)
	titmeYMDNew = strings.Replace(titmeYMDNew, "TUE", "日", -1)
	titmeYMDNew = strings.Replace(titmeYMDNew, "WED", "日", -1)
	titmeYMDNew = strings.Replace(titmeYMDNew, "THU", "日", -1)
	titmeYMDNew = strings.Replace(titmeYMDNew, "FRI", "日", -1)
	titmeYMDNew = strings.Replace(titmeYMDNew, "SAT", "日", -1)
	titmeYMDNew = strconv.Itoa(time.Now().Year()) + "年" + titmeYMDNew
	return
}

// 处理时分PM格式
func ConvertActivityTitmeHM(titmeHM string) (titmeHMNew string) {
	titmeHMNew = titmeHM
	//var hNum int
	var amOrPm string
	if strings.Contains(titmeHM, "PM") {
		//hNum = 12
		amOrPm = "PM"
	} else {
		amOrPm = "AM"
	}
	titmeHM = strings.Replace(titmeHM, "AM", "", -1)
	titmeHM = strings.Replace(titmeHM, "PM", "", -1)
	sliceHm := strings.Split(titmeHM, "：")
	if len(sliceHm) != 2 {
		return
	}
	hourNum, _ := strconv.Atoi(sliceHm[0])
	minute := sliceHm[1]
	titmeHMNew = strconv.Itoa(hourNum) + ":" + minute + " " + amOrPm
	return
}

// 活动内容模版
var ActivityOcrTemplate = "<p>【小范围公司线上交流】{{COMPANY}}</p><p>时间：{{TIME}}</p><p>嘉宾：IR</p><p>主持人：IR</p><p>链接参会：（会前一天下午更新）</p><p>备注：</p><p>1、请先报名，我们将于会议前一天提供【Webex】入会链接（可电话拨入or网络端参会）；</p><p>2、会议语言：{{LANGUAGE}}；</p><p>3、本场会议报名截止时间为会议开始前一天下午3点半；</p><p>4、本次会议扣0.5次研选服务点。</p>"

func MakeActivityReqText(list []*cygx.AliyunOcrTextActivityResp) (req cygx.ActivityRep, err error, errMsg string) {
	for _, v := range list {
		ActivityOcrTmp := ActivityOcrTemplate
		sliceCompany := strings.Split(v.Company, "(")
		company := sliceCompany[0]
		//company := v.Company
		ActivityOcrTmp = strings.Replace(ActivityOcrTmp, "{{COMPANY}}", v.Company, -1)
		v.TitmeYMD = strings.Replace(v.TitmeYMD, "年", "-", -1)
		v.TitmeYMD = strings.Replace(v.TitmeYMD, "月", "-", -1)
		v.TitmeYMD = strings.Replace(v.TitmeYMD, "日", "", -1)
		weeknum := utils.StrDateTimeToWeek(v.TitmeYMD + " 00:00:00")

		havePm := strings.Contains(v.TitmeHM, "PM")
		var activityTime string
		activityTime = strings.Replace(v.TitmeHM, " ", "", -1)
		activityTime = strings.Replace(activityTime, "AM", "", -1)
		activityTime = strings.Replace(activityTime, "PM", "", -1)

		activityTime = v.TitmeYMD + " " + activityTime + ":00"
		resultTime := utils.StrTimeToTime(activityTime)
		var amOrPm string
		if havePm {
			//前端传过来的是 2：00PM 这里转成 14:00 PM
			slicePm := strings.Split(v.TitmeHM, ":")
			for sk, sv := range slicePm {
				// 如果是中午 12:30 PM 就不做任何处理
				if sk == 0 && sv != "12" {
					resultTime = resultTime.Add(12 * time.Hour)
					activityTime = resultTime.Format(utils.FormatDateTime)
				}
			}
			amOrPm = "PM"
		} else {
			amOrPm = "AM"
		}
		var condition string
		var pars []interface{}
		condition = " AND activity_type_id = 3 AND  activity_time = ? AND temporary_label = ? "
		pars = append(pars, activityTime, company)
		total, e := cygx.GetActivityCount(condition, pars)
		if e != nil {
			err = errors.New("GetActivityCount，Err" + e.Error())
			return
		}

		if total > 0 {
			errMsg = "相同时段已存在对应活动"
			return
		}
		ActivityOcrTmp = strings.Replace(ActivityOcrTmp, "{{TIME}}", v.TitmeYMD+"("+weeknum+")"+resultTime.Format(utils.FormatTimeHm)+amOrPm, -1)
		if !utils.CheckStrHaveLetter(company) {
			ActivityOcrTmp = strings.Replace(ActivityOcrTmp, "{{LANGUAGE}}", "中文", -1)
		} else {
			ActivityOcrTmp = strings.Replace(ActivityOcrTmp, "{{LANGUAGE}}", "英文", -1)
		}
		req.Body += ActivityOcrTmp + "<hr>" //分隔符标签
		label := new(cygx.ActivityGroupIndustrialRep)
		label.TemporaryLabel = company
		req.List = append(req.List, label)
	}
	//初始化相关活动参数信息
	req.Body = strings.TrimRight(req.Body, "<hr>")
	req.DoType = 1
	req.ActivityTypeId = 3
	req.PermissionName = utils.CHART_PERMISSION_NAME_MF_YANXUAN
	req.CustomerTypeIds = "1,2,8,10,3,9,5,6,7"
	req.IsAllCustomerType = 1
	req.LimitPeopleNum = 10
	req.LabelType = 1
	req.VisibleRange = 2
	req.IsResearchPoints = 1
	req.IsNeedEmail = 1
	req.IsShowHz = 1 //是否同时在弘则展示  1是，0否
	// 研选点数
	pointsSet := new(cygx.CygxActivityPointsSetRsq)
	pointsSet.PointsObject = "1"
	pointsSet.UserPointsNum = "0.5"
	pointsSet.PointsType = "1"
	pointsSet.CompanyPointsNum = "0"
	pointsSet.CancelDeadlineType = "1"
	req.PointsSet = pointsSet
	return
}

// 代码冲突了先放这里
func UpdateActivityVideoAndVoice(activityInfo *cygx.ActivityDetail, itemVoice *cygx.CygxActivityVoice, itemVideo *cygx.CygxActivityVideo) (err error) {
	if activityInfo.ActiveState != 3 {
		return // 没有结束的活动不会上传音视频
	}
	activityId := activityInfo.ActivityId
	var condition string
	var pars []interface{}
	//处理音频
	if itemVoice.ActivityId > 0 {
		condition = " AND activity_id = ? "
		pars = append(pars, activityId)
		total, e := cygx.GetCygxActivityVoiceCount(condition, pars)
		if e != nil {
			err = errors.New("GetCygxActivityVoiceCount" + e.Error())
			return
		}

		//activityId := itemVoice.ActivityId
		////获取活动详情
		//activityInfo, e := cygx.GetAddActivityInfoById(activityId)
		//if e != nil {
		//	err = errors.New("GetAddActivityInfoById, Err: " + e.Error())
		//	return
		//}

		//易董办会的分析师电话会，为路演回放
		if (activityInfo.ActivityTypeId == 2 || activityInfo.ActivityTypeId == 7) && activityInfo.IsYidongConduct == 1 {
			itemVoice.FileType = 1
		} else {
			itemVoice.FileType = 2
		}

		shareImg, _ := MakeCygxMp3HtmlImg(itemVoice.VoicePlaySeconds, activityInfo.ChartPermissionId) //生成分享图片
		itemVoice.ShareImg = shareImg
		itemVoice.VoiceName = utils.RemoveFileSuffixName(itemVoice.VoiceName) //去掉后缀名称
		//如果等于0就新增，反之就修改
		if total == 0 {
			newId, e := cygx.AddCygxActivityVoice(itemVoice)
			if e != nil {
				err = errors.New("GetCygxActivityVoiceCount" + e.Error())
				return
			}
			go UpdateActivityVoiceResourceData(int(newId)) //写入首页最新  cygx_resource_data 表

			go SendWxMsgWithUpdateActivityVideoAndVoice(activityId, itemVoice.VoiceName) //  已结束的活动上传音频或视频后给已关注这个活动关联的产业的正式、试用 客户发送模板信息
		} else {
			//获取音频详情
			voiceDetail, e := cygx.GetCygxActivityVoiceReqDetailByActivityId(activityId)
			if e != nil {
				err = errors.New("GetCygxActivityVoiceReqDetail" + e.Error())
				return
			}
			//手动修改过的，二次编辑，文件类型不变
			if voiceDetail.IsByHand == 1 {
				itemVoice.FileType = voiceDetail.FileType
			}
			e = cygx.UpdateCygxActivityVoice(itemVoice)
			if e != nil {
				err = errors.New("UpdateCygxActivityVoice" + e.Error())
				return
			}
			go UpdateActivityVoiceResourceData(voiceDetail.ActivityVoiceId) //写入首页最新  cygx_resource_data 表
		}
	} else {
		voiceDetail, e := cygx.GetCygxActivityVoiceReqDetail(activityId)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCygxActivityVoiceReqDetail" + e.Error())
			return
		}
		if voiceDetail != nil {
			e = cygx.DeleteCygxActivityVoice(activityId)
			if e != nil {
				err = errors.New("DeleteCygxActivityVoice" + e.Error())
				return
			}
			go UpdateActivityVoiceResourceData(voiceDetail.ActivityVoiceId) //写入首页最新  cygx_resource_data 表
		}
	}

	//处理视频
	if itemVideo.ActivityId > 0 {
		condition = " AND art.activity_id = ? "
		pars = append(pars, activityId)
		total, e := cygx.GetActivityVideoCount(condition, pars)
		if e != nil {
			err = errors.New("GetActivityVideoCount" + e.Error())
			return
		}
		//activityId := itemVideo.ActivityId
		////获取活动详情
		//activityInfo, e := cygx.GetAddActivityInfoById(activityId)
		//if e != nil {
		//	err = errors.New("GetAddActivityInfoById, Err: " + e.Error())
		//	return
		//}
		//易董办会的分析师电话会，为路演回放
		if (activityInfo.ActivityTypeId == 2 || activityInfo.ActivityTypeId == 7) && activityInfo.IsYidongConduct == 1 {
			itemVideo.FileType = 1
		} else {
			itemVideo.FileType = 2
		}

		shareImg, _ := MakeCygxMp4HtmlImg(itemVideo.VideoDuration, activityInfo.ChartPermissionId) //生成分享图片
		itemVideo.ShareImg = shareImg
		itemVideo.VideoName = utils.RemoveFileSuffixName(itemVideo.VideoName) //去掉后缀名称

		//视频文件更换阿里云oss地址 避免卡顿
		var newOssUrl string
		newOssUrl = strings.Replace(itemVideo.VideoUrl, "https://hzstatic.hzinsights.com", "https://hzchart.oss-accelerate.aliyuncs.com", -1)
		itemVideo.VideoUrl = newOssUrl
		//如果等于0就新增，反之就修改
		if total == 0 {
			newId, e := cygx.AddCygxActivityVideo(itemVideo)
			if e != nil {
				err = errors.New("AddCygxActivityVideo" + e.Error())
				return
			}
			go UpdateActivityVideoResourceData(int(newId))                               //写入首页最新  cygx_resource_data 表
			go SendWxMsgWithUpdateActivityVideoAndVoice(activityId, itemVideo.VideoName) //  已结束的活动上传音频或视频后给已关注这个活动关联的产业的正式、试用 客户发送模板信息
		} else {
			//获取视频详情
			videoDetail, e := cygx.GetCygxActivityVideoReqDetail(activityId)
			if e != nil {
				err = errors.New("GetCygxActivityVideoReqDetail" + e.Error())
				return
			}
			//手动修改过的，二次编辑，文件类型不变
			if videoDetail.IsByHand == 1 {
				itemVideo.FileType = videoDetail.FileType
			}

			e = cygx.UpdateCygxActivityVideo(itemVideo)
			if e != nil {
				err = errors.New("UpdateCygxActivityVideo" + e.Error())
				return
			}
			go UpdateActivityVideoResourceData(videoDetail.VideoId) //写入首页最新  cygx_resource_data 表
		}
	} else {
		//删除原有的视频数据
		videoDetail, e := cygx.GetCygxActivityVideoReqDetail(activityId)
		if e != nil && e.Error() != utils.ErrNoRow() {
			err = errors.New("GetCygxActivityVideoReqDetail" + e.Error())
			return
		}
		if videoDetail != nil {
			e = cygx.DeleteCygxActivityVideo(activityId)
			if e != nil {
				err = errors.New("DeleteCygxActivityVideo" + e.Error())
				return
			}
			go UpdateActivityVideoResourceData(videoDetail.VideoId) //写入首页最新  cygx_resource_data 表
		}
	}
	return
}
