package services

import (
	"errors"
	"fmt"
	"hongze/hongze_cygx/models"
	"hongze/hongze_cygx/utils"
	"regexp"
	"strconv"
	"strings"
	"time"
)

// GetProductInteriorUrl 处理产品内测中的连接并做跳转处理
func GetProductInteriorUrl(url string, urlMap map[string]string) (itemResp *models.ProductInteriorUrlResp) {
	//2：文章详情  https://web.hzinsights.com/material/info/8436
	//3：活动详情  https://web.hzinsights.com/activity/detail/2701
	//4：产业详情  https://web.hzinsights.com/indepth/info/20/79
	item := new(models.ProductInteriorUrlResp)
	item.Body = url
	if urlMap[url] == "" {
		item.Type = 1
	} else {
		urlSlice := strings.Split(url, "/")
		lenurlSlice := len(urlSlice)
		sourceId, _ := strconv.Atoi(urlSlice[lenurlSlice-1])
		item.SourceId = sourceId
		if strings.Contains(url, "material/info") {
			item.Type = 2
		} else if strings.Contains(url, "activity/detail") {
			item.Type = 3
		} else if strings.Contains(url, "indepth/info") {
			if lenurlSlice >= 2 {
				chartPermissionId, _ := strconv.Atoi(urlSlice[lenurlSlice-2])
				item.ChartPermissionId = chartPermissionId
			}
			item.Type = 4
		}
	}
	itemResp = item
	return
}

// GetProductInteriorUrl 处理产品内测中的连接并做跳转处理
func GetProductInteriorUrlBody(body string, user *models.WxUserItem) (itemResp []*models.ProductInteriorUrlResp, err error) {
	//2：文章详情  https://web.hzinsights.com/material/info/8436
	//3：活动详情  https://web.hzinsights.com/activity/detail/2701
	//4：产业详情  https://web.hzinsights.com/indepth/info/20/79

	// 用户权限
	authInfo, permissionArr, e := GetUserRaiPermissionInfo(user.UserId, user.CompanyId)
	if e != nil {
		err = errors.New("GetUserRaiPermissionInfo, Err: " + e.Error())
		return
	}

	material := "material/info"     // 2：文章详情
	activity := "activity/detail"   //3：活动详情
	indepth := "indepth/info"       //4：产业详情
	ctivityvideo := "ctivity/video" //5：活动音频

	var randStrStart = "start_cygx_{|}"
	var randStr = "start_cygx_{|}_end_cygx"
	urlMap := make(map[string]string)
	var hrefRegexp = regexp.MustCompile(utils.RegularUrl)
	match := hrefRegexp.FindAllString(body, -1)
	if match != nil {
		for _, v := range match {
			//过滤不相干的超链接
			if !strings.Contains(v, material) && !strings.Contains(v, activity) && !strings.Contains(v, indepth) && !strings.Contains(v, ctivityvideo) {
				continue
			}
			body = strings.Replace(body, fmt.Sprint("href=\"", v, "\""), "", -1)
			body = strings.Replace(body, fmt.Sprint("<a >"), "", -1)
			body = strings.Replace(body, fmt.Sprint("</a>"), "", -1)
			body = strings.Replace(body, v, randStrStart+v+randStr, -1)
			urlMap[v] = v
		}
	}
	sliceBody := strings.Split(body, randStr)
	var sliceBodyUrl []string
	for _, v := range sliceBody {
		sliceUrl := strings.Split(v, randStrStart)
		for _, url := range sliceUrl {
			if url == "" {
				continue
			}
			sliceBodyUrl = append(sliceBodyUrl, url)
		}
	}

	for _, url := range sliceBodyUrl {
		item := new(models.ProductInteriorUrlResp)
		item.Body = url
		if urlMap[url] == "" {
			item.Type = 1
		} else {
			urlSlice := strings.Split(url, "/")
			lenurlSlice := len(urlSlice)
			sourceId, _ := strconv.Atoi(urlSlice[lenurlSlice-1])
			item.SourceId = sourceId
			if strings.Contains(url, material) {
				item.Type = 2
			} else if strings.Contains(url, activity) {
				item.Type = 3
			} else if strings.Contains(url, indepth) {
				if lenurlSlice >= 2 {
					chartPermissionId, _ := strconv.Atoi(urlSlice[lenurlSlice-2])
					item.ChartPermissionId = chartPermissionId
				}
				item.Type = 4
			} else if strings.Contains(url, ctivityvideo) {
				if lenurlSlice >= 2 {
					chartPermissionId, _ := strconv.Atoi(urlSlice[lenurlSlice-2])
					item.ChartPermissionId = chartPermissionId
				}
				item.Type = 5
				activityVideo, e := models.GetCygxActivityVideoReqByActivityId(sourceId)
				if e != nil {
					err = errors.New("GetCygxActivityVideoReqByActivityId, Err: " + e.Error())
					return
				}
				if activityVideo != nil {
					item.ActivityVideo = activityVideo
				}
				activityInfo, e := models.GetAddActivityInfoById(sourceId)
				if e != nil {
					err = errors.New("GetAddActivityInfoById, Err: " + e.Error())
					return
				}
				// 权限
				au := new(models.UserPermissionAuthInfo)
				au.SellerName = authInfo.SellerName
				au.SellerMobile = authInfo.SellerMobile
				au.HasPermission = authInfo.HasPermission
				au.OperationMode = authInfo.OperationMode
				if au.HasPermission == 1 {
					// 非宏观权限进一步判断是否有权限
					if activityInfo.ChartPermissionId != utils.HONG_GUAN_ID && !utils.InArrayByStr(permissionArr, activityInfo.ChartPermissionName) {
						au.HasPermission = 2
					}
				}
				// 无权限的弹框提示
				if au.HasPermission != 1 {
					if au.OperationMode == UserPermissionOperationModeCall {
						au.PopupMsg = UserPermissionPopupMsgCallMicroVideo
					} else {
						au.PopupMsg = UserPermissionPopupMsgApplyActivity
					}
				}
				item.AuthInfo = au
			}
		}
		itemResp = append(itemResp, item)
	}
	return
}

func AddCygxProductInteriorHistory(user *models.WxUserItem, articleId int) (err error) {
	cacheKey := fmt.Sprint("ProductInterior:", user.UserId, "articleId:", articleId)
	isExist := utils.Rc.IsExist(cacheKey)
	if isExist {
		return err
	}
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("产品内测用户浏览信息记录失败"+err.Error(), 2)
		}
	}()
	historyRecord := new(models.CygxProductInteriorHistory)
	historyRecord.UserId = user.UserId
	historyRecord.ProductInteriorId = articleId
	historyRecord.CreateTime = time.Now()
	historyRecord.Mobile = user.Mobile
	historyRecord.Email = user.Email
	historyRecord.CompanyId = user.CompanyId
	historyRecord.CompanyName = user.CompanyName
	sellerItem, err := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return
	}
	historyRecord.RealName = user.RealName
	if sellerItem != nil {
		historyRecord.SellerName = sellerItem.RealName
	}
	_, err = models.AddCygxProductInteriorHistory(historyRecord)
	////10秒之内的阅读不重复记录
	setNX := utils.Rc.SetNX(cacheKey, articleId, time.Second*10)
	if !setNX {
		go utils.SendAlarmMsg("记录用户搜索关键词失败，设置Redis Key 过期时间失败：key"+cacheKey, 3)
	}
	return
}

// 获取产品内测的阅读数据
func GetCygxProductInteriorHistoryListMap(productInteriorIs []int, user *models.WxUserItem) (mapPv map[int]int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("获取产品内测的阅读数据，信息失败，Err："+err.Error(), 3)
		}
	}()
	lenproductInteriorIs := len(productInteriorIs)
	if lenproductInteriorIs == 0 {
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND product_interior_id IN (` + utils.GetOrmInReplace(lenproductInteriorIs) + `) AND  user_id = ?`
	pars = append(pars, productInteriorIs, user.UserId)
	list, err := models.GetCygxProductInteriorHistoryList(condition, pars)
	if err != nil {
		return
	}
	mapPv = make(map[int]int, 0)
	for _, v := range list {
		mapPv[v.ProductInteriorId] = v.Pv
	}
	return
}

// 获取产品内测的阅读数据
func GetCygxProductInteriorHistoryListPvMap(productInteriorIs []int) (mapPv map[int]int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println(err)
			go utils.SendAlarmMsg("获取产品内测的阅读数据，信息失败，Err："+err.Error(), 3)
		}
	}()
	lenproductInteriorIs := len(productInteriorIs)
	if lenproductInteriorIs == 0 {
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND product_interior_id IN (` + utils.GetOrmInReplace(lenproductInteriorIs) + `) `
	pars = append(pars, productInteriorIs)
	list, err := models.GetCygxProductInteriorHistoryList(condition, pars)
	if err != nil {
		return
	}
	mapPv = make(map[int]int, 0)
	for _, v := range list {
		mapPv[v.ProductInteriorId] = v.Pv
	}
	return
}

// 用户产品内测阅读，模板消息推送
func ProductInteriorHistoryUserRmind(user *models.WxUserItem, productInteriorId int) (err error) {
	if user.UserId == 0 {
		return
	}
	//30秒内阅读同一篇报告不做重复推送
	key := "CYGX_" + utils.CYGX_OBJ_PRODUCTINTERIOR + "_READ" + strconv.Itoa(productInteriorId) + "_" + strconv.Itoa(user.UserId)
	if utils.Rc.IsExist(key) {
		return
	}
	utils.Rc.Put(key, 1, 30*time.Second)
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg(fmt.Sprint("用户产品内测阅读，模板消息推送，模板消息推送失败 ,ProductInteriorHistoryUserRmind"+err.Error(), "userId：", user.UserId, "productInteriorId:", productInteriorId), 2)
		}
	}()
	countUser, err := models.GetUserRemind(user.UserId)
	if err != nil {
		return err
	}
	if countUser == 0 {
		return err
	}
	var first string
	var keyword1 string
	var keyword2 string
	var keyword3 string
	var keyword4 string
	var remark string
	//获取销售手机号
	sellerItemQy, err := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return err
	}
	if sellerItemQy != nil {

		sllerAndShareMobileArr, e := GetCompanySellerAndShareMobileByRai(user.CompanyId) //获取所属销售以及对应销售的手机号
		if e != nil {
			err = errors.New("GetCompanySellerAndShareMobileByRai, Err: " + e.Error())
			return
		}
		sllerAndShareMobiles := strings.Join(sllerAndShareMobileArr, ",")
		openIdList, e := models.GetWxOpenIdByMobileList(sllerAndShareMobiles)
		if e != nil {
			err = errors.New("GetSellerByAdminId, Err: " + e.Error())
			return
		}
		if len(openIdList) == 0 {
			return
		}
		detail, e := models.GetCygxProductInteriorDetail(productInteriorId)
		if e != nil {
			err = errors.New("GetCygxProductInteriorDetail, Err: " + e.Error())
			return
		}
		if detail == nil {
			return
		}
		keyword1 = detail.Title
		keyword2 = fmt.Sprint("互动：阅读报告,", user.RealName, "--", user.CompanyName)
		openIdArr := make([]string, 0)
		for _, v := range openIdList {
			openIdArr = append(openIdArr, v.OpenId)
		}
		redirectUrl := utils.WX_MSG_PATH_PRODUCTINTERIOR_DETAIL + strconv.Itoa(productInteriorId)
		sendInfo := new(SendWxTemplate)
		sendInfo.First = first
		sendInfo.Keyword1 = keyword1
		sendInfo.Keyword2 = keyword2
		sendInfo.Keyword3 = keyword3
		sendInfo.Keyword4 = keyword4
		sendInfo.Remark = remark
		sendInfo.TemplateId = utils.WxMsgTemplateIdArticleUserRemind
		sendInfo.RedirectUrl = redirectUrl
		sendInfo.RedirectTarget = 3
		sendInfo.Resource = strconv.Itoa(productInteriorId)
		sendInfo.SendType = utils.TEMPLATE_MSG_CYGX_ARTICLE_ADD
		sendInfo.OpenIdArr = openIdArr
		e = PublicSendTemplateMsg(sendInfo)
		if e != nil {
			err = errors.New("PublicSendTemplateMsg, Err: " + e.Error())
			return
		}
	}
	return
}
