package services

import (
	"errors"
	"fmt"
	"hongze/hongze_clpt/models"
	"hongze/hongze_clpt/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) (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
	material := "material/info"
	activity := "activity/detail"
	indepth := "indepth/info"

	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) {
				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
			}
		}
		itemResp = append(itemResp, item)
	}
	return
}

func AddCygxProductInteriorHistory(user *models.WxUserItem, articleId int) (err error) {
	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
	historyRecord.RegisterPlatform = utils.REGISTER_PLATFORM
	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)
	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) {
	//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
}