Browse Source

新增pc端接口

rdluck 4 years ago
parent
commit
30f1b28fc7

+ 7 - 2
controllers/base_common.go

@@ -5,6 +5,7 @@ import (
 	"net/http"
 	"net/url"
 	"strconv"
+	"strings"
 
 	"github.com/astaxie/beego"
 
@@ -35,7 +36,11 @@ func (this *BaseCommonController) Prepare() {
 		utils.FileLog.Info("authorization:%s,cookie:%s", authorization, cookie)
 		authorization = cookie
 	}
-
+	uri := this.Ctx.Input.URI()
+	utils.FileLog.Info("URI:%s", uri)
+	if strings.Contains(uri, "/api/wechat/login") {
+		authorization = ""
+	}
 	if authorization != "" {
 		session, err := models.GetSessionByToken(authorization)
 		if err != nil {
@@ -71,7 +76,7 @@ func (this *BaseCommonController) Prepare() {
 		}
 		this.User = wxUser
 	}
-	this.Token=authorization
+	this.Token = authorization
 }
 
 func (c *BaseCommonController) ServeJSON(encoding ...bool) {

+ 43 - 12
controllers/home_pc.go

@@ -2,8 +2,10 @@ package controllers
 
 import (
 	"hongze/hongze_api/models"
+	"hongze/hongze_api/services"
 	"hongze/hongze_api/utils"
 	"rdluck_tools/paging"
+	"time"
 )
 
 // @Title 首页专栏接口
@@ -41,6 +43,12 @@ func (this *HomeCommonController) ListHome() {
 		this.Data["json"] = br
 		this.ServeJSON()
 	}()
+	var uid int
+
+	if this.Token != "" && this.User != nil {
+		uid = this.User.UserId
+	}
+
 	pageSize, _ := this.GetInt("PageSize")
 	currentIndex, _ := this.GetInt("CurrentIndex")
 
@@ -59,33 +67,56 @@ func (this *HomeCommonController) ListHome() {
 		br.ErrMsg = "参数错误"
 		return
 	}
-	total, err := models.PcListHomeCount(classifyId)
+
+	endDate:=time.Now().AddDate(0,-1,0).Format(utils.FormatDate)
+
+	total, err := models.PcListHomeCount(classifyId,endDate)
 	if err != nil {
 		br.Msg = "获取数据失败"
-		br.ErrMsg = "获取数据失败,Err:" + err.Error()
+		br.ErrMsg = "获取数据条数失败,Err:" + err.Error()
 		return
 	}
-	list, err := models.PcListHome(classifyId, startSize, pageSize)
+
+	list, err := models.PcListHome(classifyId, uid, startSize, pageSize,endDate)
 	if err != nil {
 		br.Msg = "获取数据失败"
 		br.ErrMsg = "获取数据失败,Err:" + err.Error()
 		return
 	}
+	var hasPermission bool
+	if this.Token != "" && this.User != nil {
+		userPermission, err := services.CheckUserPermission(this.User.UserId)
+		if err != nil {
+			br.Msg = "获取失败"
+			br.ErrMsg = "判断权限失败,判断权限失败:" + err.Error()
+			return
+		}
+
+		if userPermission == 0 {
+			hasPermission = true
+		}
+	}
+
 	for i := 0; i < len(list); i++ {
 		item := list[i]
 		if item.ClassifyName == "权益研报" {
-			list[i].ReportInfo.TitleType = "权益"
+			list[i].TitleType = "权益"
 		} else {
-			list[i].ReportInfo.TitleType = "FICC"
+			list[i].TitleType = "FICC"
 		}
 
-		if this.Token == "" {
-			list[i].ReportInfo.VideoUrl = ""
-			list[i].ReportInfo.VideoName = ""
-			list[i].ReportInfo.VideoPlaySeconds = ""
-			list[i].ReportInfo.VideoSize = ""
+		if !hasPermission {
+			list[i].VideoUrl = ""
+			list[i].VideoName = ""
+			list[i].VideoPlaySeconds = ""
+			list[i].VideoSize = ""
 		}
 	}
+
+	if len(list) == 0 {
+		list = make([]*models.PcHomeClassifyItem, 0)
+	}
+
 	page := paging.GetPaging(currentIndex, pageSize, total)
 	resp := new(models.PcListHomeResp)
 	resp.Paging = page
@@ -96,8 +127,8 @@ func (this *HomeCommonController) ListHome() {
 	br.Data = resp
 }
 
-// @Title 首页列表接口
-// @Description 首页列表接口
+// @Title 首页banner接口
+// @Description 首页banner接口
 // @Success 200 {object} models.Banner
 // @router /pc/banner [get]
 func (this *HomeCommonController) PcListBanner() {

+ 46 - 6
controllers/report.go

@@ -3,6 +3,7 @@ package controllers
 import (
 	"encoding/json"
 	"hongze/hongze_api/models"
+	"hongze/hongze_api/services"
 	"hongze/hongze_api/utils"
 	"html"
 	"strings"
@@ -66,10 +67,13 @@ func (this *ReportController) Detail() {
 	report.Content = html.UnescapeString(report.Content)
 
 	productId := 0
+	maxPermissionCount := 0
 	if report.ClassifyName == "权益研报" {
 		productId = 2
+		maxPermissionCount = 5
 	} else {
 		productId = 1
+		maxPermissionCount = 15
 	}
 	company, err := models.GetCompanyProductById(user.CompanyId, productId)
 	if err != nil {
@@ -80,19 +84,16 @@ func (this *ReportController) Detail() {
 		} else {
 			status = 2
 			msg = "您还未开通权限,如有需要请联系对口销售"
-			report.Content = report.ContentSub
 		}
 	}
 	if company == nil {
 		status = 2
 		msg = "您还未开通权限,如有需要请联系对口销售"
-		report.Content = report.ContentSub
 	} else {
 		if company.Status == utils.COMPANY_STATUS_LOSE ||
 			company.Status == utils.COMPANY_STATUS_FREEZE {
 			status = 2
 			msg = "您还未开通权限,如有需要请联系对口销售"
-			report.Content = report.ContentSub
 		}
 	}
 
@@ -107,13 +108,11 @@ func (this *ReportController) Detail() {
 			} else {
 				status = 2
 				msg = "您还未开通权限,如有需要请联系对口销售"
-				report.Content = report.ContentSub
 			}
 		}
 		if len(reportPermissionList) == 0 {
 			status = 2
 			msg = "您还未开通权限,如有需要请联系对口销售"
-			report.Content = report.ContentSub
 		}
 		permissionMap := make(map[int]int)
 		for _, v := range reportPermissionList {
@@ -125,7 +124,6 @@ func (this *ReportController) Detail() {
 		if _, ok := permissionMap[reportId]; !ok {
 			tips := ""
 			status = 2
-			report.Content = report.ContentSub
 			classifyNameSecond := report.ClassifyNameSecond
 			if strings.Contains(classifyNameSecond, "宏观商品复盘") ||
 				strings.Contains(classifyNameSecond, "股债日评") ||
@@ -151,7 +149,29 @@ func (this *ReportController) Detail() {
 	} else {
 		report.TitleType = "FICC"
 	}
+	//判断大小权限
+	{
+		if status == 2 {
+			permissionCount, err := models.GetCompanyProductPermissionCount(company.CompanyId, productId)
+			if err != nil {
+				br.Msg = "获取信息失败"
+				br.ErrMsg = "获取权限信息失败,Err:" + err.Error()
+				return
+			}
+			if permissionCount >= maxPermissionCount {
+				status = 0
+				msg = ""
+			}
+		}
+	}
 
+	if status == 2 {
+		report.Content = report.ContentSub
+		report.VideoUrl = ""
+		report.VideoSize = ""
+		report.VideoPlaySeconds = ""
+		report.VideoName = ""
+	}
 	resp := new(models.ReportDetailResp)
 	resp.Status = status
 	resp.Msg = msg
@@ -268,6 +288,19 @@ func (this *ReportController) ListReport() {
 		br.ErrMsg = "获取失败,Err:" + err.Error()
 		return
 	}
+
+	var hasPermission bool
+	userPermission, err := services.CheckUserPermission(this.User.UserId)
+	if err != nil {
+		br.Msg = "绑定失败"
+		br.ErrMsg = "绑定失败,判断权限失败:" + err.Error()
+		return
+	}
+
+	if userPermission == 0 {
+		hasPermission = true
+	}
+
 	listLen := len(list)
 	for i := 0; i < listLen; i++ {
 		item := list[i]
@@ -288,6 +321,13 @@ func (this *ReportController) ListReport() {
 		} else {
 			list[i].TitleType = "FICC"
 		}
+
+		if hasPermission == false {
+			list[i].VideoUrl = ""
+			list[i].VideoName = ""
+			list[i].VideoName = ""
+			list[i].VideoPlaySeconds = ""
+		}
 	}
 
 	page := models.GetPaging(currentIndex, pageSize, total)

+ 30 - 18
controllers/user.go

@@ -307,26 +307,38 @@ func (this *UserController) Login() {
 		br.ErrMsg = "无效的登录方式,Err:" + err.Error()
 		return
 	}
-	timeUnix := time.Now().Unix()
-	timeUnixStr := strconv.FormatInt(timeUnix, 10)
-	token := utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
-	//新增session
-	{
-		session := new(models.Session)
-		session.OpenId = openId
-		session.UserId = userId
-		session.CreatedTime = time.Now()
-		session.LastUpdatedTime = time.Now()
-		session.ExpireTime = time.Now().AddDate(1, 0, 0)
-		session.AccessToken = token
-		err = models.AddSession(session)
-		if err != nil {
-			br.Msg = "登录失败"
-			br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
-			return
-		}
+	var token string
+	tokenItem, err := models.GetTokenByUid(userId)
+	if err != nil && err.Error() != utils.ErrNoRow() {
+		br.Msg = "登录失败"
+		br.ErrMsg = "登录失败,获取token失败:" + err.Error()
+		return
 	}
 
+	if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
+		token = tokenItem.AccessToken
+		timeUnix := time.Now().Unix()
+		timeUnixStr := strconv.FormatInt(timeUnix, 10)
+		token := utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
+		//新增session
+		{
+			session := new(models.Session)
+			session.OpenId = openId
+			session.UserId = userId
+			session.CreatedTime = time.Now()
+			session.LastUpdatedTime = time.Now()
+			session.ExpireTime = time.Now().AddDate(0, 1, 0)
+			session.AccessToken = token
+			err = models.AddSession(session)
+			if err != nil {
+				br.Msg = "登录失败"
+				br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
+				return
+			}
+		}
+	} else {
+		token = tokenItem.AccessToken
+	}
 	userPermission, err := services.CheckUserPermission(newUserId)
 	if err != nil {
 		br.Msg = "登录失败"

+ 231 - 77
controllers/user_pc.go

@@ -187,7 +187,7 @@ func (this *UserCommonController) PcLogin() {
 				isAdd = true
 			} else {
 				br.Msg = "登陆失败"
-				br.ErrMsg = "根据邮箱获取用户信息失败,Err:" + err.Error()
+				br.ErrMsg = "根据手机号获取用户信息失败,Err:" + err.Error()
 				return
 			}
 		}
@@ -255,16 +255,43 @@ func (this *UserCommonController) PcLogin() {
 		user.CreatedTime = time.Now()
 		user.FirstLogin = 1
 		user.Enabled = 1
+		user.Email = req.Email
+		user.Mobile = req.Mobile
+		if req.LoginType == 1 {
+			user.BindAccount = user.Mobile
+		} else {
+			user.BindAccount = user.Email
+		}
 		user.RegisterTime = time.Now()
 		user.LoginTime = time.Now()
 		user.IsFreeLogin = req.IsFreeLogin
+		user.RegisterPlatform=2
 		lastId, err := models.AddWxUser(user)
 		if err != nil {
 			br.Msg = "登录失败"
-			br.ErrMsg = "登录失败,Err:" + err.Error()
+			br.ErrMsg = "登录失败,新增客户信息失败,Err:" + err.Error()
 			return
 		}
 		userId = int(lastId)
+
+		timeUnix := time.Now().Unix()
+		timeUnixStr := strconv.FormatInt(timeUnix, 10)
+		token := utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
+		//新增session
+		{
+			session := new(models.Session)
+			session.UserId = userId
+			session.CreatedTime = time.Now()
+			session.LastUpdatedTime = time.Now()
+			session.ExpireTime = time.Now().AddDate(0, 1, 0)
+			session.AccessToken = token
+			err = models.AddSession(session)
+			if err != nil {
+				br.Msg = "登录失败"
+				br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
+				return
+			}
+		}
 	} else {
 		err = models.ModifyLoginTime(userId, req.IsFreeLogin)
 		if err != nil {
@@ -278,24 +305,6 @@ func (this *UserCommonController) PcLogin() {
 		br.ErrMsg = "登录失败,id为 0"
 		return
 	}
-	timeUnix := time.Now().Unix()
-	timeUnixStr := strconv.FormatInt(timeUnix, 10)
-	token := utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
-	//新增session
-	{
-		session := new(models.Session)
-		session.UserId = userId
-		session.CreatedTime = time.Now()
-		session.LastUpdatedTime = time.Now()
-		session.ExpireTime = time.Now().AddDate(1, 0, 0)
-		session.AccessToken = token
-		err = models.AddSession(session)
-		if err != nil {
-			br.Msg = "登录失败"
-			br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
-			return
-		}
-	}
 
 	userPermission, err := services.CheckUserPermission(userId)
 	if err != nil {
@@ -309,14 +318,57 @@ func (this *UserCommonController) PcLogin() {
 		br.ErrMsg = "登录失败,判断权限失败:" + err.Error()
 		return
 	}
-	newUser, _ := models.GetWxUserItemByUserId(userId)
-	checkPermissionCount, err := models.GetCustomPermission(newUser.CompanyId)
-	if err != nil {
+	var token string
+	tokenItem, err := models.GetTokenByUid(userId)
+	if err != nil && err.Error() != utils.ErrNoRow() {
 		br.Msg = "登录失败"
-		br.ErrMsg = "校验提示权限信息失败 Err:" + err.Error()
+		br.ErrMsg = "登录失败,获取token失败:" + err.Error()
 		return
 	}
 
+	if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
+		timeUnix := time.Now().Unix()
+		timeUnixStr := strconv.FormatInt(timeUnix, 10)
+		token = utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
+		//新增session
+		{
+			session := new(models.Session)
+			session.UserId = userId
+			session.CreatedTime = time.Now()
+			session.LastUpdatedTime = time.Now()
+			session.ExpireTime = time.Now().AddDate(0, 1, 0)
+			session.AccessToken = token
+			err = models.AddSession(session)
+			if err != nil {
+				br.Msg = "登录失败"
+				br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
+				return
+			}
+		}
+	} else {
+		token = tokenItem.AccessToken
+	}
+
+	cp, err := models.GetCompanyProductsByUserId(userId)
+	if err != nil {
+		br.Msg = "登录失败"
+		br.ErrMsg = "登录失败,获取客户信息失败:" + err.Error()
+		return
+	}
+	var companyName, status, endDate, productName string
+	for _, v := range cp {
+		companyName = v.CompanyName
+		if status != "" {
+			status = status + "/" + v.Status
+			endDate = endDate + "/" + v.EndDate
+			productName = productName + "/" + v.ProductName
+		} else {
+			status = v.Status
+			endDate = v.EndDate
+			productName = v.ProductName
+		}
+	}
+	newUser, _ := models.GetWxUserItemByUserId(userId)
 	resp := new(models.LoginResp)
 	resp.UserId = newUser.UserId
 	resp.UserPermission = userPermission
@@ -324,10 +376,10 @@ func (this *UserCommonController) PcLogin() {
 	resp.Headimgurl = newUser.Headimgurl
 	resp.Mobile = newUser.Mobile
 	resp.Email = newUser.Email
-
-	if checkPermissionCount <= 0 {
-		resp.IsTips = true
-	}
+	resp.CompanyName = companyName
+	resp.EndDate = endDate
+	resp.Status = status
+	resp.ProductName = productName
 
 	br.Ret = 200
 	br.Success = true
@@ -353,8 +405,12 @@ func (this *UserController) PcBind() {
 		br.ErrMsg = "参数解析失败,Err:" + err.Error()
 		return
 	}
-	openId := this.User.OpenId
+	unionId := this.User.UnionId
 	userId := this.User.UserId
+
+	utils.FileLog.Info("绑定unionId:%s", unionId)
+	utils.FileLog.Info("userId:%d", userId)
+
 	var newUserId int
 	if req.BindType == 1 { //手机号
 		if req.Mobile == "" {
@@ -383,7 +439,10 @@ func (this *UserController) PcBind() {
 			br.Msg = "手机验证码错误,请重新输入"
 			return
 		}
-		newUserId, err = models.BindMobile(openId, req.Mobile, userId, req.BindType)
+		fmt.Println("bind")
+		fmt.Println(unionId, req.Mobile, userId, req.BindType)
+
+		newUserId, err = models.PcBindMobile(unionId, req.Mobile, userId, req.BindType)
 		if err != nil {
 			br.ErrMsg = "绑定失败"
 			br.Msg = "绑定失败,Err:" + err.Error()
@@ -421,7 +480,7 @@ func (this *UserController) PcBind() {
 			br.Msg = "邮箱证码错误,请重新输入"
 			return
 		}
-		newUserId, err = models.BindMobile(openId, req.Mobile, userId, req.BindType)
+		newUserId, err = models.PcBindMobile(unionId, req.Email, userId, req.BindType)
 		if err != nil {
 			br.ErrMsg = "绑定失败"
 			br.Msg = "绑定失败,Err:" + err.Error()
@@ -432,24 +491,37 @@ func (this *UserController) PcBind() {
 		br.ErrMsg = "无效的绑定方式,bindType:" + strconv.Itoa(req.BindType)
 		return
 	}
-	timeUnix := time.Now().Unix()
-	timeUnixStr := strconv.FormatInt(timeUnix, 10)
-	token := utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
-	//新增session
-	{
-		session := new(models.Session)
-		session.UserId = userId
-		session.CreatedTime = time.Now()
-		session.LastUpdatedTime = time.Now()
-		session.ExpireTime = time.Now().AddDate(1, 0, 0)
-		session.AccessToken = token
-		err = models.AddSession(session)
-		if err != nil {
-			br.Msg = "绑定失败"
-			br.ErrMsg = "绑定失败,新增用户session信息失败:" + err.Error()
-			return
+
+	var token string
+	tokenItem, err := models.GetTokenByUid(newUserId)
+	if err != nil && err.Error() != utils.ErrNoRow() {
+		br.Msg = "登录失败"
+		br.ErrMsg = "登录失败,获取token失败:" + err.Error()
+		return
+	}
+	if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
+		timeUnix := time.Now().Unix()
+		timeUnixStr := strconv.FormatInt(timeUnix, 10)
+		token = utils.MD5(strconv.Itoa(newUserId)) + utils.MD5(timeUnixStr)
+		//新增session
+		{
+			session := new(models.Session)
+			session.UserId = newUserId
+			session.CreatedTime = time.Now()
+			session.LastUpdatedTime = time.Now()
+			session.ExpireTime = time.Now().AddDate(0, 1, 0)
+			session.AccessToken = token
+			err = models.AddSession(session)
+			if err != nil {
+				br.Msg = "登录失败"
+				br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
+				return
+			}
 		}
+	} else {
+		token = tokenItem.AccessToken
 	}
+
 	userPermission, err := services.CheckUserPermission(newUserId)
 	if err != nil {
 		br.Msg = "绑定失败"
@@ -462,10 +534,46 @@ func (this *UserController) PcBind() {
 		br.ErrMsg = "绑定失败,判断权限失败:" + err.Error()
 		return
 	}
+
+	cp, err := models.GetCompanyProductsByUserId(newUserId)
+	if err != nil {
+		br.Msg = "登录失败"
+		br.ErrMsg = "登录失败,获取客户信息失败:" + err.Error()
+		return
+	}
+	var companyName, status, endDate, productName string
+	for _, v := range cp {
+		companyName = v.CompanyName
+		if status != "" {
+			status = status + "/" + v.Status
+			endDate = endDate + "/" + v.EndDate
+			productName = productName + "/" + v.ProductName
+		} else {
+			status = v.Status
+			endDate = v.EndDate
+			productName = v.ProductName
+		}
+	}
+
+	newUser, err := models.GetWxUserItemByUserId(newUserId)
+	if err != nil {
+		br.Msg = "登录失败"
+		br.ErrMsg = "获取客户信息失败 GetWxUserItemByUserId:" + err.Error()
+		return
+	}
+
 	resp := new(models.LoginResp)
 	resp.UserId = newUserId
 	resp.UserPermission = userPermission
 	resp.Authorization = token
+	resp.Email = newUser.Email
+	resp.Headimgurl = newUser.Headimgurl
+	resp.Mobile = newUser.Mobile
+	resp.CompanyName = companyName
+	resp.EndDate = endDate
+	resp.Status = status
+	resp.ProductName = productName
+
 	br.Ret = 200
 	br.Success = true
 	br.Data = resp
@@ -474,7 +582,7 @@ func (this *UserController) PcBind() {
 
 // @Title 校验免登陆
 // @Description 校验免登陆
-// @Success Ret=200 绑定成功
+// @Success 200 {object} models.CheckLoginResp
 // @router /pc/check/login [get]
 func (this *UserController) CheckLogin() {
 	br := new(models.BaseResponse).Init()
@@ -495,37 +603,83 @@ func (this *UserController) CheckLogin() {
 			br.Ret = 408
 		}
 	}
+	authorization := this.Ctx.Input.Header("Authorization")
+	if authorization == "" {
+		cookie := this.Ctx.GetCookie("rddp_access_token")
+		utils.FileLog.Info("authorization:%s,cookie:%s", authorization, cookie)
+		authorization = cookie
+	}
 	br.IsSendEmail = false
+	//判断token是否过期
+	if br.Ret == 408 {
+		tokenCount, err := models.GetSessionCountByToken(authorization)
+		if err != nil {
+			if err.Error() == utils.ErrNoRow() {
+				br.Ret = 408
+			} else {
+				br.ErrMsg = "登录失败,Err:" + err.Error()
+				br.ErrMsg = "登录失败"
+				br.IsSendEmail = true
+				return
+			}
+		}
+		if tokenCount > 0 {
+			br.Ret = 600
+		}
+	}
+	resp := new(models.CheckLoginResp)
+	if br.Ret == 600 {
+		checkPermissionCount, err := models.GetCustomPermission(this.User.CompanyId)
+		if err != nil && err.Error() != utils.ErrNoRow() {
+			br.Msg = "登录失败"
+			br.ErrMsg = "校验提示权限信息失败 Err:" + err.Error()
+			return
+		}
+		if checkPermissionCount <= 0 && this.User.CompanyId > 1 {
+			resp.IsTips = true
+		}
+
+		if this.User.Mobile == "" && this.User.Email == "" {
+			resp.IsBind = true
+		}
+	}
 	br.Success = true
 	br.Msg = "获取成功"
+	br.Data = resp
 }
 
-/*
-var (
-	searcher = riot.New("zh")
-)
-
-func init() {
-	fmt.Sprintf("start")
-	data := types.DocData{Content: `I wonder how, I wonder why
-		, I wonder where they are`}
-	data1 := types.DocData{Content: "所以, 你好, 再见"}
-	data2 := types.DocData{Content: "没有理由"}
-	data3 := types.DocData{Content: "你好,中国"}
-	data4 := types.DocData{Content: "晚上好"}
-
-	searcher.Index("1", data)
-	searcher.Index("2", data1)
-	searcher.IndexDoc("3", data2)
-	searcher.IndexDoc("4", data3)
-	searcher.IndexDoc("5", data4)
-	searcher.Flush()
-
-	req := types.SearchReq{Text: "你好"}
-	search := searcher.Search(req)
-	jsonStr,_:=json.Marshal(search)
-	fmt.Println(string(jsonStr))
-	utils.FileLog.Info("%s",string(jsonStr))
-	fmt.Sprintf("end")
-}
-*/
+//
+//var (
+//	searcher = riot.New("zh")
+//)
+//
+//func init() {
+//	fmt.Sprintf("start")
+//	data := types.DocData{Content: `I wonder how, I wonder why
+//		, I wonder where they are`}
+//	data1 := types.DocData{Content: "所以, 你好, 再见"}
+//	data2 := types.DocData{Content: "没有理由"}
+//	data3 := types.DocData{Content: "你好,中国"}
+//	data4 := types.DocData{Content: "晚上好"}
+//	data5 := types.DocData{Content: "中国人民,你好啊,2020年"}
+//	data6 := types.DocData{Content: "中国的新冠疫情算基本得到了有效的控制,随着各地的纷纷复工,甚至有些省市已经开始了复学,大量的外籍华人、旅居的、留学的平时召唤都召唤不来的那些人纷纷回国,这都说明了我们伟大的中国,伟大的中国人民战胜了这次肆虐全球的瘟疫。\n\n  在这这次的抗击新冠疫情中,我们的白衣天使们,我们的专家、学者、科学家们,纷纷的冲在了抗疫第一线。看着84岁高龄的钟南山院士坐在高铁座位上睡着的照片,看着73岁的第一个提出武汉封城的李兰娟院士数次往返于武汉,脸上那一道道的长时间佩戴口罩和护目镜留下的压痕,看着一个个的花季少女剪掉秀发只是为了更好的穿戴防护装备,看着一车车的物资涌向武汉,看着一张张按着手印的奔赴疫区申请书,听着一句句熟悉而又温暖的入党誓词,感动无不充盈心腔,眼泪也从未吝啬。对最美逆行者的赞美是多么的诚挚!"}
+//	data7 := types.DocData{Content: "在此,我除了表达对他们由衷的感动,还想说:我们中国千万万的普普通通的老百姓也是最伟大、最可爱的人。从来没有一个朝代,从来没有一个国家,像我们中国的老百姓这样如此的对待疫情。平凡的老百姓节衣缩食,也要将物资援助最需要的地方,宁愿几个月不出门,也不给国家增加一分的负担。试问世界上有哪个国家的人民有我们中国的人民对国家如母亲般的感情呢?\n\n  近期看到的最多的新闻就是国外疫情的泛滥,不说在抗疫中每个国家的责任和力量,就说普通的百姓不戴口罩到处跑的,一只狗被遛了三十二次的,最硬核的就是用棍棒打腿的,这些都说明了他们的意识,他们面对疫情的态度和我们的同胞不是一个层次,他们对待国家的情感是不能和我们比拟的!当然,我们国家也不排除有个别的另类出现,但一定会收到最严厉的惩戒。\n\n  中国人民在这次的抗击新冠疫情的战役中表现出来的智慧、勇气、精神,都使我感到作为一个中国人是多么幸运。"}
+//
+//	searcher.Index("1", data)
+//	searcher.Index("2", data1)
+//	searcher.IndexDoc("3", data2)
+//	searcher.IndexDoc("4", data3)
+//	searcher.IndexDoc("5", data4)
+//	searcher.IndexDoc("6", data5)
+//	searcher.IndexDoc("7", data6)
+//	searcher.IndexDoc("8", data7)
+//	searcher.Flush()
+//
+//	req := types.SearchReq{Text: "中国人民",Orderless: false,CountDocsOnly: false}
+//	search := searcher.Search(req)
+//	jsonStr,_:=json.Marshal(search)
+//	fmt.Println(string(jsonStr))
+//	utils.FileLog.Info("%s",string(jsonStr))
+//	fmt.Sprintf("end")
+//}
+//

+ 42 - 24
controllers/wechat.go

@@ -42,6 +42,7 @@ func (this *WechatCommonController) WechatLogin() {
 		return
 	}
 	openId := item.Openid
+	unionid := item.Unionid
 	firstLogin := 1
 	userId := 0
 	//获取成功
@@ -71,12 +72,15 @@ func (this *WechatCommonController) WechatLogin() {
 				br.ErrMsg = "获取用户信息失败 errcode:" + item.Errcode + " ;errmsg:" + item.Errmsg
 				return
 			}*/
+			if unionid == "" {
+				unionid = wxUserInfo.Unionid
+			}
 			user := new(models.WxUser)
 			user.OpenId = openId
 			user.CompanyId = 1
 			user.CreatedTime = time.Now()
-			user.UnionId = wxUserInfo.Unionid
-			user.Unionid = wxUserInfo.Unionid
+			user.UnionId = unionid
+			user.Unionid = unionid
 			user.Subscribe = wxUserInfo.SubscribeScene
 			user.SubscribeTime = wxUserInfo.SubscribeTime
 			user.NickName = wxUserInfo.Nickname
@@ -88,8 +92,9 @@ func (this *WechatCommonController) WechatLogin() {
 			user.Remark = wxUserInfo.Remark
 			user.FirstLogin = 1
 			user.Enabled = 1
-			user.RegisterTime=time.Now()
-			_,err = models.AddWxUser(user)
+			user.RegisterPlatform=1
+			user.RegisterTime = time.Now()
+			_, err = models.AddWxUser(user)
 			if wxUserInfo.Unionid != "" {
 				wxUser, err = models.GetWxUserItemByUnionid(wxUserInfo.Unionid)
 				if err != nil {
@@ -115,31 +120,44 @@ func (this *WechatCommonController) WechatLogin() {
 		br.ErrMsg = "获取openid失败,openid:" + item.Openid
 		return
 	}
-	timeUnix := time.Now().Unix()
-	timeUnixStr := strconv.FormatInt(timeUnix, 10)
-	token := utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
-	//新增session
-	{
-		session := new(models.Session)
-		session.OpenId = openId
-		session.UserId = userId
-		session.CreatedTime = time.Now()
-		session.LastUpdatedTime = time.Now()
-		session.ExpireTime = time.Now().AddDate(1, 0, 0)
-		session.AccessToken = token
-		err = models.AddSession(session)
-		if err != nil {
-			br.Msg = "登录失败"
-			br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
-			return
-		}
-	}
+
 	permission, err := services.CheckUserPermission(userId)
 	if err != nil {
 		br.Msg = "登录失败"
 		br.ErrMsg = "登录失败,判断权限失败:" + err.Error()
 		return
 	}
+	var token string
+	tokenItem, err := models.GetTokenByUid(userId)
+	if err != nil && err.Error() != utils.ErrNoRow() {
+		br.Msg = "登录失败"
+		br.ErrMsg = "登录失败,获取token失败:" + err.Error()
+		return
+	}
+
+	if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
+		timeUnix := time.Now().Unix()
+		timeUnixStr := strconv.FormatInt(timeUnix, 10)
+		token = utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
+		//新增session
+		{
+			session := new(models.Session)
+			session.OpenId = openId
+			session.UserId = userId
+			session.CreatedTime = time.Now()
+			session.LastUpdatedTime = time.Now()
+			session.ExpireTime = time.Now().AddDate(0, 1, 0)
+			session.AccessToken = token
+			err = models.AddSession(session)
+			if err != nil {
+				br.Msg = "登录失败"
+				br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
+				return
+			}
+		}
+	} else {
+		token = tokenItem.AccessToken
+	}
 	resp := new(models.WxLoginResp)
 	resp.UserId = userId
 	resp.Code = 0
@@ -200,4 +218,4 @@ func (this *WechatController) GetWxSign() {
 
 /*
 $app->bag('api/wechat/check', "WechatController@check");
-*/
+*/

+ 132 - 48
controllers/wechat_pc.go

@@ -1,6 +1,7 @@
 package controllers
 
 import (
+	"encoding/json"
 	"fmt"
 	"hongze/hongze_api/models"
 	"hongze/hongze_api/services"
@@ -33,51 +34,70 @@ func (this *WechatCommonController) PcWechatLogin() {
 		br.ErrMsg = "获取access_token 失败 errcode:" + strconv.Itoa(item.Errcode) + " ;errmsg:" + item.Errmsg
 		return
 	}
+
 	openId := item.Openid
+
+	//accessToken, err := services.PcWxGetAccessToken()
+	//utils.FileLog.Info("accessToken:%s", accessToken)
+	//if err != nil {
+	//	br.Msg = "获取用户信息失败"
+	//	br.ErrMsg = "获取access_token失败,err:" + err.Error()
+	//	return
+	//}
+	utils.FileLog.Info("item.AccessToken):%s", item.AccessToken)
+
+	//获取用户信息
+	wxUserInfo, err := services.PcWxGetUserInfo(openId, item.AccessToken)
+	if err != nil {
+		br.Msg = "获取用户信息失败"
+		br.ErrMsg = "获取微信用户信息失败,Err:" + err.Error()
+		return
+	}
+	if wxUserInfo.Errcode != 0 {
+		userInfoJson, _ := json.Marshal(wxUserInfo)
+		br.Msg = "登录失败"
+		br.ErrMsg = "获取用户信息失败,err:" + string(userInfoJson)
+		return
+	}
+	var unionid string
+	unionid = item.Unionid
+	utils.FileLog.Info("item unionid:%s", unionid)
+	if unionid == "" {
+		unionid = wxUserInfo.Unionid
+	}
+	utils.FileLog.Info("openId:%s", openId)
+	utils.FileLog.Info("unionid:%s", unionid)
+
 	firstLogin := 1
 	userId := 0
 	//获取成功
-	if openId != "" {
-		wxUser, err := models.GetWxUserItemByOpenId(openId)
+	if unionid != "" {
+		wxUser, err := models.GetWxUserItemByUnionid(unionid)
 		if err != nil && err.Error() != utils.ErrNoRow() {
 			br.Msg = "获取用户信息失败"
 			br.ErrMsg = "根据openid获取用户信息失败,Eerr:" + err.Error()
 			return
 		}
 		if wxUser == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
-			accessToken, err := services.PcWxGetAccessToken()
-			if err != nil {
-				br.Msg = "获取用户信息失败"
-				br.ErrMsg = "获取access_token失败,err:" + err.Error()
-				return
-			}
-			//获取用户信息
-			wxUserInfo, err := services.WxGetUserInfo(openId, accessToken)
-			if err != nil {
-				br.Msg = "获取用户信息失败"
-				br.ErrMsg = "获取微信用户信息失败,Err:" + err.Error()
-				return
-			}
+			utils.FileLog.Info("用户不存在,注册")
 			user := new(models.WxUser)
 			user.OpenId = openId
 			user.CompanyId = 1
 			user.CreatedTime = time.Now()
-			user.UnionId = wxUserInfo.Unionid
-			user.Unionid = wxUserInfo.Unionid
-			user.Subscribe = wxUserInfo.SubscribeScene
-			user.SubscribeTime = wxUserInfo.SubscribeTime
+			user.UnionId = unionid
+			user.Unionid = unionid
 			user.NickName = wxUserInfo.Nickname
 			user.Sex = wxUserInfo.Sex
 			user.City = wxUserInfo.City
 			user.Province = wxUserInfo.Province
 			user.Country = wxUserInfo.Country
 			user.Headimgurl = wxUserInfo.Headimgurl
-			user.Remark = wxUserInfo.Remark
 			user.FirstLogin = 1
 			user.Enabled = 1
 			user.RegisterTime = time.Now()
+			user.RegisterPlatform = 2
 			_, err = models.AddWxUser(user)
-			if wxUserInfo.Unionid != "" {
+			if unionid != "" {
 				wxUser, err = models.GetWxUserItemByUnionid(wxUserInfo.Unionid)
 				if err != nil {
 					br.Msg = "获取用户信息失败"
@@ -93,34 +113,38 @@ func (this *WechatCommonController) PcWechatLogin() {
 				}
 			}
 			userId = wxUser.UserId
+			utils.FileLog.Info("注册后获取的用户id:%d", userId)
+			timeUnix := time.Now().Unix()
+			timeUnixStr := strconv.FormatInt(timeUnix, 10)
+			token := utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
+			//新增session
+			{
+				session := new(models.Session)
+				session.OpenId = openId
+				session.UserId = userId
+				session.CreatedTime = time.Now()
+				session.LastUpdatedTime = time.Now()
+				session.ExpireTime = time.Now().AddDate(0, 1, 0)
+				session.AccessToken = token
+				err = models.AddSession(session)
+				if err != nil {
+					br.Msg = "登录失败"
+					br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
+					return
+				}
+			}
 		} else {
+			utils.FileLog.Info("用户已经存在")
 			firstLogin = wxUser.FirstLogin
 			userId = wxUser.UserId
+			utils.FileLog.Info("用户已经存在,用户id:%d", userId)
 		}
 	} else {
 		br.Msg = "获取用户信息失败"
 		br.ErrMsg = "获取openid失败,openid:" + item.Openid
 		return
 	}
-	timeUnix := time.Now().Unix()
-	timeUnixStr := strconv.FormatInt(timeUnix, 10)
-	token := utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
-	//新增session
-	{
-		session := new(models.Session)
-		session.OpenId = openId
-		session.UserId = userId
-		session.CreatedTime = time.Now()
-		session.LastUpdatedTime = time.Now()
-		session.ExpireTime = time.Now().AddDate(1, 0, 0)
-		session.AccessToken = token
-		err = models.AddSession(session)
-		if err != nil {
-			br.Msg = "登录失败"
-			br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
-			return
-		}
-	}
+
 	permission, err := services.CheckUserPermission(userId)
 	if err != nil {
 		br.Msg = "登录失败"
@@ -128,12 +152,57 @@ func (this *WechatCommonController) PcWechatLogin() {
 		return
 	}
 	newUser, _ := models.GetWxUserItemByUserId(userId)
-	checkPermissionCount, err := models.GetCustomPermission(newUser.CompanyId)
+	utils.FileLog.Info("获取用户信息:%d", userId)
+
+	var token string
+	tokenItem, err := models.GetTokenByUid(userId)
+	if err != nil && err.Error() != utils.ErrNoRow() {
+		br.Msg = "登录失败"
+		br.ErrMsg = "登录失败,获取token失败:" + err.Error()
+		return
+	}
+	if tokenItem == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
+		timeUnix := time.Now().Unix()
+		timeUnixStr := strconv.FormatInt(timeUnix, 10)
+		token = utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
+		//新增session
+		{
+			session := new(models.Session)
+			session.UserId = userId
+			session.CreatedTime = time.Now()
+			session.LastUpdatedTime = time.Now()
+			session.ExpireTime = time.Now().AddDate(0, 1, 0)
+			session.AccessToken = token
+			err = models.AddSession(session)
+			if err != nil {
+				br.Msg = "登录失败"
+				br.ErrMsg = "登录失败,新增用户session信息失败:" + err.Error()
+				return
+			}
+		}
+	} else {
+		token = tokenItem.AccessToken
+	}
+
+	cp, err := models.GetCompanyProductsByUserId(userId)
 	if err != nil {
 		br.Msg = "登录失败"
-		br.ErrMsg = "校验提示权限信息失败 Err:" + err.Error()
+		br.ErrMsg = "登录失败,获取客户信息失败:" + err.Error()
 		return
 	}
+	var companyName, status, endDate, productName string
+	for _, v := range cp {
+		companyName = v.CompanyName
+		if status != "" {
+			status = status + "/" + v.Status
+			endDate = endDate + "/" + v.EndDate
+			productName = productName + "/" + v.ProductName
+		} else {
+			status = v.Status
+			endDate = v.EndDate
+			productName = v.ProductName
+		}
+	}
 
 	resp := new(models.WxLoginResp)
 	resp.UserId = userId
@@ -144,14 +213,29 @@ func (this *WechatCommonController) PcWechatLogin() {
 	resp.Email = newUser.Email
 	resp.Headimgurl = newUser.Headimgurl
 	resp.Mobile = newUser.Mobile
-	if newUser.Mobile == "" && newUser.Email == "" {
-		resp.IsBind = true
-	}
-	if checkPermissionCount <= 0 {
-		resp.IsTips = true
-	}
+	resp.CompanyName = companyName
+	resp.EndDate = endDate
+	resp.Status = status
+	resp.ProductName = productName
+
 	br.Ret = 200
 	br.Success = true
 	br.Msg = "登录成功"
 	br.Data = resp
 }
+
+//func init() {
+//	accessToken:=`40_6_YtSyR4Kg9MYbODrNVc1mpztpbZDPWb8aiNzgq96vfvSLGb59dTZk6dprQuhCdsPrqYRKFvaAAij0_NzR-rnMCb0Bxsngov9eLBuk4WQoI`
+//	openId:=`oNUl652NjgjPz_C4M1ezCIro_s98`
+//	item,err:=services.WxGetUserInfo(openId, accessToken)
+//	fmt.Println(err)
+//	fmt.Println(item)
+//}
+
+//func init() {
+//	fmt.Println("start accessToken")
+//	accessToken, err := services.PcWxGetAccessToken()
+//	fmt.Println(err)
+//	utils.FileLog.Info("accessToken:%s",accessToken)
+//	fmt.Println("end accessToken")
+//}

+ 2 - 1
main.go

@@ -2,6 +2,7 @@ package main
 
 import (
 	"fmt"
+	"hongze/hongze_api/services"
 	"runtime"
 	"time"
 
@@ -18,7 +19,7 @@ func main() {
 		beego.BConfig.WebConfig.DirectoryIndex = true
 		beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
 	}
-
+	go services.Task()
 	beego.BConfig.RecoverFunc = Recover
 	beego.Run()
 }

+ 2 - 1
models/classify.go

@@ -39,7 +39,8 @@ func GetClassifyList() (item []*Classify, err error) {
 }
 
 func GetClassifySecondList(classifyId int) (item []*ClassifyDetail, err error) {
-	sql := ` SELECT a.id AS classify_id,a.classify_name,a.sort,a.parent_id,a.create_time,a.modify_time,a.abstract,a.descript,a.report_author,a.author_descript,a.report_img_url,a.head_img_url,a.avatar_img_url,a.column_img_url,a.is_home_column,MAX(b.stage) AS stage FROM classify AS a 
+	sql := ` SELECT a.id AS classify_id,a.classify_name,a.sort,a.parent_id,a.create_time,a.modify_time,a.abstract,a.descript,a.report_author,a.author_descript,a.report_img_url,a.head_img_url,a.avatar_img_url,a.column_img_url,a.is_home_column,MAX(b.stage) AS stage 
+            FROM classify AS a 
 			LEFT JOIN report AS b ON a.id=b.classify_id_second 
 			WHERE a.parent_id = ?
 			GROUP BY a.id  `

+ 55 - 1
models/company_product.go

@@ -1,6 +1,9 @@
 package models
 
-import "time"
+import (
+	"rdluck_tools/orm"
+	"time"
+)
 
 type CompanyProduct struct {
 	CompanyProductId int       `orm:"column(company_product_id);pk" description:"客户产品id"`
@@ -30,3 +33,54 @@ type CompanyProduct struct {
 	LossTime         time.Time `description:"流失时间"`
 	CompanyType      string    `description:"客户类型"`
 }
+
+//判断客户权限总数
+func GetCompanyProductPermissionCount(companyId, productId int) (count int, err error) {
+	sql := ` SELECT COUNT(DISTINCT c.chart_permission_id) AS COUNT FROM company AS a
+				INNER JOIN company_product AS b ON a.company_id=b.company_id 
+				INNER JOIN company_report_permission AS c ON a.company_id=c.company_id
+				WHERE  b.company_id=? AND b.product_id=?
+				AND b.status IN('正式','试用')
+				AND c.product_id=? `
+	o := orm.NewOrm()
+	err = o.Raw(sql, companyId, productId, productId).QueryRow(&count)
+	return
+}
+
+
+type CompanyProductDetail struct {
+	CompanyProductId int       `orm:"column(company_product_id);pk" description:"客户产品id"`
+	CompanyId        int       `description:"客户id"`
+	ProductId        int       `description:"产品id"`
+	ProductName      string    `description:"产品名称"`
+	CompanyName      string    `description:"客户名称"`
+	Source           string    `description:"来源"`
+	Reasons          string    `description:"新增理由"`
+	Status           string    `description:"客户状态"`
+	IndustryId       int       `description:"行业id"`
+	IndustryName     string    `description:"行业名称"`
+	SellerId         int       `description:"销售id"`
+	SellerName       string    `description:"销售名称"`
+	GroupId          int       `description:"销售分组id"`
+	DepartmentId     int       `description:"销售部门id"`
+	IsSuspend        int       `description:"1:暂停,0:启用"`
+	SuspendTime      time.Time `description:"暂停启用时间"`
+	ApproveStatus    string    `description:"审批状态:'审批中','通过','驳回'"`
+	FreezeTime       time.Time `description:"冻结时间"`
+	Remark           string    `description:"备注信息"`
+	CreateTime       time.Time `description:"创建时间"`
+	ModifyTime       time.Time `description:"修改时间"`
+	StartDate        string    `description:"开始日期"`
+	EndDate          string    `description:"结束日期"`
+	LoseReason       string    `description:"流失原因"`
+	LossTime         time.Time `description:"流失时间"`
+}
+
+func GetCompanyProductsByUserId(userId int) (items []*CompanyProductDetail, err error) {
+	sql := ` SELECT a.* FROM company_product AS a
+			INNER JOIN wx_user AS b ON a.company_id=b.company_id
+			WHERE b.user_id=? `
+	o := orm.NewOrm()
+	_, err = o.Raw(sql, userId).QueryRows(&items)
+	return
+}

+ 34 - 39
models/home.go

@@ -79,56 +79,51 @@ func ListHome(userId, maxPermission, userPermission int, permissionStr string) (
 }
 
 type PcHomeClassifyItem struct {
-	ClassifyId   int    `orm:"column(id)"`
-	ClassifyName string `description:"分类名称"`
-	Abstract       string    `description:"栏目简介"`
-	Descript       string    `description:"分享描述"`
-	ReportAuthor   string    `description:"栏目作者"`
-	AuthorDescript string    `description:"作者简介"`
-	ColumnImgUrl   string    `description:"栏目配图"`
-	HeadImgUrl     string    `description:"头部banner"`
-	AvatarImgUrl   string    `description:"头像"`
-	ReportImgUrl   string    `description:"报告配图"`
-	ReportInfo   *PcReport
+	ClassifyId     int
+	ClassifyName   string `description:"分类名称"`
+	Abstract       string `description:"栏目简介"`
+	Descript       string `description:"分享描述"`
+	ReportAuthor   string `description:"栏目作者"`
+	AuthorDescript string `description:"作者简介"`
+	ColumnImgUrl   string `description:"栏目配图"`
+	HeadImgUrl     string `description:"头部banner"`
+	AvatarImgUrl   string `description:"头像"`
+	ReportImgUrl   string `description:"报告配图"`
+	PcReport
 }
 
-func PcListHomeCount(classifyId int) (count int, err error) {
+func PcListHomeCount(classifyId int, endDate string) (count int, err error) {
 	o := orm.NewOrm()
 	o.Using("rddp")
-	sql := `SELECT COUNT(1) AS count FROM classify WHERE parent_id=? `
-	err = o.Raw(sql, classifyId).QueryRow(&count)
+
+	sql := `SELECT COUNT(1) AS count
+                FROM classify AS a
+                INNER JOIN report AS b ON a.id=b.classify_id_second
+                WHERE b.state=2 AND b.classify_id_first=? AND b.publish_time>=?`
+	err = o.Raw(sql, classifyId, endDate).QueryRow(&count)
 	return
 }
 
-func PcListHome(classifyId, startSize, pageSize int) (items []*PcHomeClassifyItem, err error) {
+func PcListHome(classifyId, uid, startSize, pageSize int, endDate string) (items []*PcHomeClassifyItem, err error) {
 	o := orm.NewOrm()
 	o.Using("rddp")
-	subSql := ` SELECT * FROM classify WHERE parent_id=?  `
-	subSql += ` ORDER BY create_time ASC LIMIT ?,? `
-	_, err = o.Raw(subSql, classifyId, startSize, pageSize).QueryRows(&items)
-	if err != nil {
-		fmt.Println("Sub Err:" + err.Error())
-		return
-	}
-	lenSub := len(items)
-	for k := 0; k < lenSub; k++ {
-		subItem := items[k]
-		reportSql := ` SELECT a.*,b.*,
+	if uid > 0 {
+		reportSql := ` SELECT a.id AS classify_id,a.head_img_url,a.avatar_img_url,a.column_img_url,a.report_img_url,b.*,
+                (SELECT COUNT(1) FROM report_view_log AS c WHERE c.user_id=? AND c.report_id=b.id ) AS is_show_new_label,
                 CASE WHEN DATE(b.modify_time)=DATE(NOW()) THEN 1 ELSE 0 END AS is_current_date
                 FROM classify AS a
                 INNER JOIN report AS b ON a.id=b.classify_id_second
-                WHERE b.state=2 AND a.id=?
-                ORDER BY b.publish_time DESC LIMIT 1  `
-		report := new(PcReport)
-		err = o.Raw(reportSql, subItem.ClassifyId).QueryRow(&report)
-		if err != nil {
-			if err.Error() != utils.ErrNoRow() {
-				return
-			} else {
-				err = nil
-			}
-		}
-		items[k].ReportInfo = report
+                WHERE b.state=2 AND b.classify_id_first=? AND b.publish_time>=?
+                ORDER BY b.publish_time DESC LIMIT ?,? `
+		_, err = o.Raw(reportSql, uid, classifyId, endDate, startSize, pageSize).QueryRows(&items)
+	} else {
+		reportSql := ` SELECT a.id AS classify_id,a.head_img_url,a.avatar_img_url,a.column_img_url,a.report_img_url,b.*,
+                CASE WHEN DATE(b.modify_time)=DATE(NOW()) THEN 1 ELSE 0 END AS is_current_date
+                 FROM classify AS a
+                INNER JOIN report AS b ON a.id=b.classify_id_second
+                WHERE b.state=2 AND b.classify_id_first=? AND b.publish_time>=?
+                ORDER BY b.publish_time DESC LIMIT ?,? `
+		_, err = o.Raw(reportSql, classifyId, endDate, startSize, pageSize).QueryRows(&items)
 	}
 	return
 }
@@ -136,4 +131,4 @@ func PcListHome(classifyId, startSize, pageSize int) (items []*PcHomeClassifyIte
 type PcListHomeResp struct {
 	Paging *paging.PagingItem
 	List   []*PcHomeClassifyItem
-}
+}

+ 6 - 4
models/report.go

@@ -57,6 +57,7 @@ type ReportList struct {
 	VideoSize          string    `description:"音频文件大小,单位M"`
 	HasPermission      int       `description:"是否拥有报告权限,1:拥有,0:没有"`
 	TitleType          string    `description:"标题类型,FICC或者权益"`
+	IsCurrentDate      int       `description:"是否当前日期:1是,0不是"`
 	ClassifyDetail
 }
 
@@ -77,8 +78,9 @@ func GetReportList(classifyId, startSize, pageSize int) (items []*ReportList, er
 	o := orm.NewOrm()
 	o.Using("rddp")
 	sql := ` SELECT a.id,a.add_type,a.classify_id_first,a.classify_name_first,a.classify_id_second,a.classify_name_second,a.title,a.abstract,a.author,a.frequency,
-			a.create_time,a.modify_time,a.state,a.publish_time,a.stage,a.msg_is_send,b.id AS classify_id,b.classify_name,b.abstract,b.descript,b.report_author,b.author_descript,
-            b.report_img_url,b.head_img_url,b.avatar_img_url,b.column_img_url,a.video_url,a.video_name,a.video_play_seconds,a.video_size
+			a.create_time,a.modify_time,a.state,a.publish_time,a.stage,a.msg_is_send,b.id AS classify_id,b.classify_name,b.descript,b.report_author,b.author_descript,
+            b.report_img_url,b.head_img_url,b.avatar_img_url,b.column_img_url,a.video_url,a.video_name,a.video_play_seconds,a.video_size,
+            CASE WHEN DATE(a.modify_time)=DATE(NOW()) THEN 1 ELSE 0 END AS is_current_date
             FROM report AS a
 			INNER JOIN  classify AS b ON a.classify_id_second=b.id
 			WHERE a.state=2 AND a.classify_id_second=? ORDER BY  a.publish_time DESC LIMIT ?,? `
@@ -244,8 +246,8 @@ type PcReport struct {
 	VideoPlaySeconds   string    `description:"音频播放时长"`
 	VideoSize          string    `description:"音频文件大小,单位M"`
 	ContentSub         string    `json:"-" description:"内容前两个章节"`
-	IsShowNewLabel     int       `description:"是否显示新标签"`
-	IsCurrentDate      int       `description:"是否当前日期"`
+	IsShowNewLabel     int       `description:"是否显示新标签,等于0不显示,大于0显示"`
+	IsCurrentDate      int       `description:"是否当前日期:1是,0不是"`
 	ClassifyName       string    `description:"分类名称"`
 	TitleType          string    `description:"标题类型,FICC或者权益"`
 }

+ 1 - 1
models/report_pc.go

@@ -49,7 +49,7 @@ func GetSearchReportList(condition string) (items []*ReportList, err error) {
 	o := orm.NewOrm()
 	o.Using("rddp")
 	sql := ` SELECT a.id,a.add_type,a.classify_id_first,a.classify_name_first,a.classify_id_second,a.classify_name_second,a.title,a.abstract,a.author,a.frequency,
-			a.create_time,a.modify_time,a.state,a.publish_time,a.stage,a.msg_is_send,b.id AS classify_id,b.classify_name,b.abstract,b.descript,b.report_author,b.author_descript,
+			a.create_time,a.modify_time,a.state,a.publish_time,a.stage,a.msg_is_send,b.id AS classify_id,b.classify_name,b.descript,b.report_author,b.author_descript,
             b.report_img_url,b.head_img_url,b.avatar_img_url,b.column_img_url,a.video_url,a.video_name,a.video_play_seconds,a.video_size
             FROM report AS a
 			INNER JOIN  classify AS b ON a.classify_id_second=b.id

+ 17 - 1
models/session.go

@@ -23,10 +23,26 @@ func GetSessionByToken(token string) (item *Session, err error) {
 	return
 }
 
+func GetSessionCountByToken(token string) (count int, err error) {
+	sql := `SELECT COUNT(1) AS count FROM session WHERE access_token=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
+	o := orm.NewOrm()
+	o.Using("rddp")
+	err = o.Raw(sql, token).QueryRow(&count)
+	return
+}
+
 //添加用户session信息
 func AddSession(item *Session) (err error) {
 	o := orm.NewOrm()
 	o.Using("rddp")
 	_, err = o.Insert(item)
 	return
-}
+}
+
+func GetTokenByUid(uid int) (item *Session, err error) {
+	sql := `SELECT * FROM session WHERE user_id=? AND expire_time> NOW() ORDER BY session_id DESC LIMIT 1 `
+	o := orm.NewOrm()
+	o.Using("rddp")
+	err = o.Raw(sql, uid).QueryRow(&item)
+	return
+}

+ 4 - 4
models/wx_token_pc.go

@@ -3,22 +3,22 @@ package models
 import "rdluck_tools/orm"
 
 func PcGetWxToken() (item *WxToken, err error) {
-	sql := `SELECT *  FROM pc_wx_token `
+	sql := `SELECT *  FROM wx_pc_token `
 	o := orm.NewOrm()
 	err = o.Raw(sql).QueryRow(&item)
 	return
 }
 
 func PcAddWxToken(token string, expiresIn int64) (err error) {
-	sql := `INSERT INTO pc_wx_token(access_token, expires_in)VALUES(?,?) `
+	sql := `INSERT INTO wx_pc_token(access_token, expires_in)VALUES(?,?) `
 	o := orm.NewOrm()
 	_, err = o.Raw(sql, token, expiresIn).Exec()
 	return
 }
 
 func PcUpdateWxToken(token string, expiresIn int64,id int) (err error) {
-	sql := `UPDATE pc_wx_token SET access_token=?, expires_in=? WHERE id=? `
+	sql := `UPDATE wx_pc_token SET access_token=?, expires_in=? WHERE id=? `
 	o := orm.NewOrm()
 	_, err = o.Raw(sql, token, expiresIn,id).Exec()
 	return
-}
+}

+ 214 - 38
models/wx_user.go

@@ -1,47 +1,49 @@
 package models
 
 import (
+	"fmt"
 	"hongze/hongze_api/utils"
 	"rdluck_tools/orm"
 	"time"
 )
 
 type WxUser struct {
-	UserId          int       `orm:"column(user_id);pk"`
-	OpenId          string    `description:"open_id"`
-	UnionId         string    `description:"union_id"`
-	Subscribe       string    `description:"是否关注"`
-	CompanyId       int       `description:"客户id"`
-	NickName        string    `description:"用户昵称"`
-	RealName        string    `description:"用户实际名称"`
-	UserCode        string    `description:"用户编码"`
-	Mobile          string    `description:"手机号码"`
-	BindAccount     string    `description:"绑定时的账号"`
-	WxCode          string    `description:"微信号"`
-	Profession      string    `description:"职业"`
-	Email           string    `description:"邮箱"`
-	Telephone       string    `description:"座机"`
-	Sex             int       `description:"普通用户性别,1为男性,2为女性"`
-	Province        string    `description:"普通用户个人资料填写的省份"`
-	City            string    `description:"普通用户个人资料填写的城市"`
-	Country         string    `description:"国家,如中国为CN"`
-	SubscribeTime   int       `description:"关注时间"`
-	Remark          string    `description:"备注"`
-	Headimgurl      string    `description:"用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空"`
-	Privilege       string    `description:"用户特权信息,json数组,如微信沃卡用户为(chinaunicom)"`
-	Unionid         string    `description:"用户统一标识。针对一个微信开放平台帐号下的应用,同一用户的unionid是唯一的。"`
-	FirstLogin      int       `description:"是否第一次登陆"`
-	Enabled         int       `description:"是否可用"`
-	CreatedTime     time.Time `description:"创建时间"`
-	LastUpdatedTime time.Time `description:"最新一次修改时间"`
-	Seller          string    `description:"销售员"`
-	Note            string    `description:"客户备份信息"`
-	IsNote          int       `description:"是否备注过信息"`
-	FromType        string    `description:"report' COMMENT 'report:研报,teleconference:电话会"`
-	ApplyMethod     int       `description:"0:未申请,1:已付费客户申请试用,2:非客户申请试用"`
-	RegisterTime    time.Time `description:"注册时间"`
-	IsFreeLogin     bool      `description:"是否免登陆,true:免登陆,false:非免登陆"`
-	LoginTime       time.Time `description:"最近一次登录时间"`
+	UserId           int       `orm:"column(user_id);pk"`
+	OpenId           string    `description:"open_id"`
+	UnionId          string    `description:"union_id"`
+	Subscribe        string    `description:"是否关注"`
+	CompanyId        int       `description:"客户id"`
+	NickName         string    `description:"用户昵称"`
+	RealName         string    `description:"用户实际名称"`
+	UserCode         string    `description:"用户编码"`
+	Mobile           string    `description:"手机号码"`
+	BindAccount      string    `description:"绑定时的账号"`
+	WxCode           string    `description:"微信号"`
+	Profession       string    `description:"职业"`
+	Email            string    `description:"邮箱"`
+	Telephone        string    `description:"座机"`
+	Sex              int       `description:"普通用户性别,1为男性,2为女性"`
+	Province         string    `description:"普通用户个人资料填写的省份"`
+	City             string    `description:"普通用户个人资料填写的城市"`
+	Country          string    `description:"国家,如中国为CN"`
+	SubscribeTime    int       `description:"关注时间"`
+	Remark           string    `description:"备注"`
+	Headimgurl       string    `description:"用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空"`
+	Privilege        string    `description:"用户特权信息,json数组,如微信沃卡用户为(chinaunicom)"`
+	Unionid          string    `description:"用户统一标识。针对一个微信开放平台帐号下的应用,同一用户的unionid是唯一的。"`
+	FirstLogin       int       `description:"是否第一次登陆"`
+	Enabled          int       `description:"是否可用"`
+	CreatedTime      time.Time `description:"创建时间"`
+	LastUpdatedTime  time.Time `description:"最新一次修改时间"`
+	Seller           string    `description:"销售员"`
+	Note             string    `description:"客户备份信息"`
+	IsNote           int       `description:"是否备注过信息"`
+	FromType         string    `description:"report' COMMENT 'report:研报,teleconference:电话会"`
+	ApplyMethod      int       `description:"0:未申请,1:已付费客户申请试用,2:非客户申请试用"`
+	RegisterTime     time.Time `description:"注册时间"`
+	RegisterPlatform int       `description:"注册平台,1:微信端,2:PC网页端"`
+	IsFreeLogin      bool      `description:"是否免登陆,true:免登陆,false:非免登陆"`
+	LoginTime        time.Time `description:"最近一次登录时间"`
 }
 
 type WxUserItem struct {
@@ -118,8 +120,10 @@ type WxLoginResp struct {
 	Headimgurl     string `description:"用户头像"`
 	Mobile         string `description:"手机号"`
 	Email          string `description:"邮箱"`
-	IsBind         bool   `description:"true:需要绑定邮箱或验证码,false:不需要绑定邮箱或验证码"`
-	IsTips         bool   `description:"true:需要提示,false:不需要提示"`
+	CompanyName    string `description:"客户名称"`
+	Status         string `description:"状态"`
+	EndDate        string `description:"到期日期"`
+	ProductName    string `description:"客户类型名称"`
 }
 
 type UserDetail struct {
@@ -189,7 +193,10 @@ type LoginResp struct {
 	Headimgurl     string `description:"用户头像"`
 	Mobile         string `description:"手机号"`
 	Email          string `description:"邮箱"`
-	IsTips         bool   `description:"true:需要提示,false:不需要提示"`
+	CompanyName    string `description:"客户名称"`
+	Status         string `description:"状态"`
+	EndDate        string `description:"到期日期"`
+	ProductName    string `description:"客户类型名称"`
 }
 
 func BindMobile(openId, mobile string, userId, loginType int) (wxUserId int, err error) {
@@ -203,19 +210,25 @@ func BindMobile(openId, mobile string, userId, loginType int) (wxUserId int, err
 	user := new(WxUser)
 	o := orm.NewOrm()
 	err = o.Raw(sql, mobile).QueryRow(&user)
+	fmt.Println("err:", err)
 	if err != nil && err.Error() != utils.ErrNoRow() {
 		return
 	}
+	fmt.Println(user)
 	if user == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
+		fmt.Println("line  210")
 		msql := ``
 		if loginType == 1 {
 			msql = "UPDATE wx_user SET mobile = ?,bind_account = ? where open_id = ? "
 		} else {
 			msql = "UPDATE wx_user SET email = ?,bind_account = ? where open_id = ?  "
 		}
+		fmt.Println("bind")
+		fmt.Println(msql, mobile, mobile, openId)
 		_, err = o.Raw(msql, mobile, mobile, openId).Exec()
 		wxUserId = userId
 	} else {
+		fmt.Println("line  223")
 		if user.OpenId == "" {
 			wxUserId = user.UserId
 			dsql := ` DELETE FROM wx_user WHERE open_id = ? `
@@ -231,6 +244,150 @@ func BindMobile(openId, mobile string, userId, loginType int) (wxUserId int, err
 			}
 			_, err = o.Raw(msql, openId, mobile, mobile).Exec()
 		} else {
+			fmt.Println("line  239")
+			wxUserId = userId
+		}
+	}
+	return
+}
+
+func PcBindMobile(unionId, mobile string, userId, loginType int) (wxUserId int, err error) {
+	//loginType  登录方式:1:手机,2:邮箱
+
+	utils.FileLog.Info("绑定参数:%s %s %d %d", unionId, mobile, userId, loginType)
+
+	sql := ``
+	if loginType == 1 {
+		sql = `SELECT * FROM wx_user WHERE mobile = ? `
+	} else {
+		sql = "SELECT * FROM wx_user WHERE email = ? "
+	}
+	user := new(WxUser)
+	o := orm.NewOrm()
+	err = o.Raw(sql, mobile).QueryRow(&user)
+
+	if err != nil && err.Error() != utils.ErrNoRow() {
+		return
+	}
+
+	if user == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
+		utils.FileLog.Info("用户不存在,根据union_id绑定")
+		msql := ``
+		if loginType == 1 {
+			msql = "UPDATE wx_user SET mobile = ?,bind_account = ? WHERE union_id = ? "
+		} else {
+			msql = "UPDATE wx_user SET email = ?,bind_account = ? WHERE union_id = ?  "
+		}
+		_, err = o.Raw(msql, mobile, mobile, unionId).Exec()
+		wxUserId = userId
+	} else {
+		utils.FileLog.Info("用户存在,user.UnionId:%s", user.UnionId)
+		if user.UnionId == "" {
+			sql = `SELECT * FROM wx_user WHERE union_id = ? `
+			userInfo := new(WxUser)
+			o := orm.NewOrm()
+			err = o.Raw(sql, unionId).QueryRow(&userInfo)
+			if err != nil {
+				return
+			}
+
+			utils.FileLog.Info("user.RegisterTime %s",user.RegisterTime.Format(utils.FormatDateTime))
+			utils.FileLog.Info("userInfo.RegisterTime %s",userInfo.RegisterTime.Format(utils.FormatDateTime))
+
+			var maxRegisterTime time.Time
+			if user.RegisterTime.Before(userInfo.RegisterTime) {
+				maxRegisterTime = user.RegisterTime
+				utils.FileLog.Info("after")
+			} else {
+				maxRegisterTime = userInfo.RegisterTime
+				utils.FileLog.Info("not after")
+			}
+			utils.FileLog.Info("maxRegisterTime %s",maxRegisterTime.Format(utils.FormatDateTime))
+			wxUserId = user.UserId
+			dsql := ` DELETE FROM wx_user WHERE user_id = ? `
+			_, err = o.Raw(dsql, wxUserId).Exec()
+			if err != nil {
+				return wxUserId, err
+			}
+			msql := ``
+			if loginType == 1 {
+				msql = ` UPDATE wx_user SET mobile=?,bind_account = ?,created_time=NOW(),register_time=?`
+				if user.CompanyId > 0 {
+					msql += ` ,company_id = ? `
+				}
+				msql += ` WHERE union_id = ? `
+			} else {
+				msql = ` UPDATE wx_user SET email=?,bind_account = ?,created_time=NOW(),register_time=? `
+				if user.CompanyId > 0 {
+					msql += ` ,company_id = ? `
+				}
+				msql += `  WHERE union_id = ? `
+			}
+			if user.CompanyId > 0 {
+				_, err = o.Raw(msql, mobile, mobile, maxRegisterTime, user.CompanyId, unionId).Exec()
+			} else {
+				_, err = o.Raw(msql, mobile, mobile, maxRegisterTime, unionId).Exec()
+			}
+			wxUserId = userInfo.UserId
+		} else {
+			sql = `SELECT * FROM wx_user WHERE union_id = ? `
+			userInfo := new(WxUser)
+			o := orm.NewOrm()
+			err = o.Raw(sql, unionId).QueryRow(&userInfo)
+			if err != nil && err.Error() != utils.ErrNoRow() {
+				return
+			}
+			if userInfo.UserId != user.UserId {
+				isDelete := 0
+				if userInfo.CompanyId <= 1 {
+					dsql := ` DELETE FROM wx_user WHERE user_id = ? `
+					_, err = o.Raw(dsql, userInfo.UserId).Exec()
+					if err != nil {
+						return userInfo.UserId, err
+					}
+					isDelete = 1
+				}
+
+				if user.CompanyId <= 1 {
+					dsql := ` DELETE FROM wx_user WHERE user_id = ? `
+					_, err = o.Raw(dsql, user.UserId).Exec()
+					if err != nil {
+						return userInfo.UserId, err
+					}
+					isDelete = 2
+				}
+
+				if userInfo.CompanyId > 1 && user.CompanyId > 1 {
+					dsql := ` DELETE FROM wx_user WHERE user_id = ? `
+					_, err = o.Raw(dsql, user.UserId).Exec()
+					if err != nil {
+						return userInfo.UserId, err
+					}
+					isDelete = 2
+				}
+				if isDelete == 1 {
+					msql := ` UPDATE wx_user SET union_id = ?,unionid=?,bind_account = ?,created_time=NOW(),register_time=NOW()  `
+					if loginType == 1 {
+						msql += ` ,mobile = ? `
+					} else {
+						msql += ` ,email = ? `
+					}
+					msql += ` WHERE user_id = ? `
+					_, err = o.Raw(msql, user.Unionid, user.Unionid, mobile, mobile, user.UserId).Exec()
+					wxUserId = user.UserId
+				} else {
+					msql := ` UPDATE wx_user SET union_id = ?,unionid=?,bind_account = ?,created_time=NOW(),register_time=NOW()  `
+					if loginType == 1 {
+						msql += ` ,mobile = ? `
+					} else {
+						msql += ` ,email = ? `
+					}
+					msql += ` WHERE user_id = ? `
+					_, err = o.Raw(msql, unionId, unionId, mobile, mobile, userInfo.UserId).Exec()
+					wxUserId = userInfo.UserId
+				}
+			}
+			utils.FileLog.Info("用户存在,bind:%s,%d", unionId, wxUserId)
 			wxUserId = userId
 		}
 	}
@@ -287,3 +444,22 @@ func GetCustomPermission(companyId int) (count int, err error) {
 	err = o.Raw(sql, companyId).QueryRow(&count)
 	return
 }
+
+type CheckLoginResp struct {
+	IsTips bool `description:"true:需要提示,false:不需要提示"`
+	IsBind bool `description:"true:需要绑定邮箱或验证码,false:不需要绑定邮箱或验证码"`
+}
+
+func GetOpenIdAll() (items []*WxUserItem, err error) {
+	sql := ` SELECT * FROM wx_user WHERE open_id='oNUl651tL_VgkyUu71crPkjOMzyM' `
+	o := orm.NewOrm()
+	_, err = o.Raw(sql).QueryRows(&items)
+	return
+}
+
+func ModifyWxUserUnionId(unionId string, userId int) (err error) {
+	o := orm.NewOrm()
+	sql := `UPDATE wx_user SET union_id=?,unionid=? WHERE user_id = ? `
+	_, err = o.Raw(sql, unionId, unionId, userId).Exec()
+	return
+}

+ 9 - 0
services/task.go

@@ -0,0 +1,9 @@
+package services
+
+import "fmt"
+
+func Task() {
+	fmt.Println("start")
+	//InitSetUnionId()
+	fmt.Println("end")
+}

+ 9 - 6
services/wechat.go

@@ -17,8 +17,9 @@ type WxAccessToken struct {
 	ExpiresIn    int    `json:"expires_in"`
 	RefreshToken string `json:"refresh_token"`
 	Openid       string `json:"openid"`
+	Unionid      string `json:"unionid"`
 	Scope        string `json:"scope"`
-	Errcode      int `json:"errcode"`
+	Errcode      int    `json:"errcode"`
 	Errmsg       string `json:"errmsg"`
 }
 
@@ -33,7 +34,7 @@ func WxGetUserOpenIdByCode(code string) (item *WxAccessToken, err error) {
 	if err != nil {
 		return nil, err
 	}
-	utils.FileLog.Info("WxGetUserOpenIdByCode:%s",string(result))
+	utils.FileLog.Info("WxGetUserOpenIdByCode:%s", string(result))
 	err = json.Unmarshal(result, &item)
 	return
 }
@@ -62,7 +63,7 @@ func WxGetToken() (item *WxToken, err error) {
 
 func WxGetAccessToken() (accessToken string, err error) {
 	wxToken, err := models.GetWxToken()
-	fmt.Println(err,wxToken)
+	fmt.Println(err, wxToken)
 	if err != nil && err.Error() != utils.ErrNoRow() {
 		return
 	}
@@ -121,18 +122,20 @@ type WxUserInfo struct {
 	Remark         string `json:"remark"`
 	Groupid        int    `json:"groupid"`
 	SubscribeScene string `json:"subscribe_scene"`
-	Errcode        int `json:"errcode"`
+	Errcode        int    `json:"errcode"`
 	Errmsg         string `json:"errmsg"`
 }
 
-func WxGetUserInfo(openId,accessToken string) (item *WxUserInfo, err error) {
+func WxGetUserInfo(openId, accessToken string) (item *WxUserInfo, err error) {
 	requestUrl := `https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s`
 	requestUrl = fmt.Sprintf(requestUrl, accessToken, openId)
 	result, err := http.Get(requestUrl)
 	if err != nil {
 		return
 	}
-	utils.FileLog.Info("WxGetUserInfo:%s openId:%s,accessToken:%s ",string(result),openId,accessToken)
+	fmt.Println("result:",string(result))
+	utils.FileLog.Info("WxGetUserInfo:%s openId:%s,accessToken:%s ", string(result), openId, accessToken)
+	utils.FileLog.Info("WxGetUserInfo Result:%s ", string(result))
 	err = json.Unmarshal(result, &item)
 	return
 }

+ 61 - 5
services/wechat_pc.go

@@ -10,7 +10,6 @@ import (
 	"time"
 )
 
-
 func PcWxGetUserOpenIdByCode(code string) (item *WxAccessToken, err error) {
 	if code == "" {
 		err = errors.New("code is empty")
@@ -22,20 +21,22 @@ func PcWxGetUserOpenIdByCode(code string) (item *WxAccessToken, err error) {
 	if err != nil {
 		return nil, err
 	}
-	utils.FileLog.Info("WxGetUserOpenIdByCode:%s",string(result))
+	utils.FileLog.Info("WxGetUserOpenIdByCode:%s", string(result))
 	err = json.Unmarshal(result, &item)
 	return
 }
 
-
 func PcWxGetAccessToken() (accessToken string, err error) {
-	wxToken, err := models.GetWxToken()
-	fmt.Println(err,wxToken)
+	wxToken, err := models.PcGetWxToken()
+	fmt.Println(err, wxToken)
 	if err != nil && err.Error() != utils.ErrNoRow() {
 		return
 	}
+
+	fmt.Println(wxToken, err)
 	//wx_token 不存在
 	if wxToken == nil || (err != nil && err.Error() == utils.ErrNoRow()) {
+		fmt.Println("token is nil")
 		token, err := PcWxGetToken()
 		if err != nil {
 			return accessToken, err
@@ -52,6 +53,7 @@ func PcWxGetAccessToken() (accessToken string, err error) {
 		}
 		accessToken = token.AccessToken
 	} else {
+		fmt.Println("token is not nil")
 		if wxToken.ExpiresIn <= time.Now().Unix() {
 			token, err := PcWxGetToken()
 			if err != nil {
@@ -79,9 +81,63 @@ func PcWxGetToken() (item *WxToken, err error) {
 	requestUrl := `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s`
 	requestUrl = fmt.Sprintf(requestUrl, utils.PcWxAppId, utils.PcWxAppSecret)
 	result, err := http.Get(requestUrl)
+	utils.FileLog.Info("result:%s", string(result))
 	if err != nil {
 		return nil, err
 	}
 	err = json.Unmarshal(result, &item)
 	return
 }
+
+func InitSetUnionId() {
+	list, err := models.GetOpenIdAll()
+	if err != nil {
+		fmt.Println("err:" + err.Error())
+		return
+	}
+	accessToken := "40_2L4GKbzCZ7qLtlATugEBKBIO6NZJBf4_0O6bHcelPSSSHbgeZhLFyU2jLdLeAP5d_DAinICR2ifS5M_TK-cmGwSKnVz4oa2nnR2UyhD3WbIbvMv3lRbXo06Ujtmwht_gilx_dU26kTHxOKpYDTEjAAAVLW"
+	for k, v := range list {
+		fmt.Println(k, v.OpenId)
+		wxUserInfo, err := WxGetUserInfo(v.OpenId, accessToken)
+		if err != nil {
+			fmt.Println("Err:" + err.Error())
+			return
+		}
+		unionId := wxUserInfo.Unionid
+		if unionId != "" {
+			err = models.ModifyWxUserUnionId(unionId, v.UserId)
+			if err != nil {
+				fmt.Println("ModifyWxUserUnionId Err:" + err.Error())
+				return
+			}
+		}
+	}
+}
+
+type PcWxUserInfo struct {
+	Openid         string `json:"openid"`
+	Nickname       string `json:"nickname"`
+	Sex            int    `json:"sex"`
+	Language       string `json:"language"`
+	City           string `json:"city"`
+	Province       string `json:"province"`
+	Country        string `json:"country"`
+	Headimgurl     string `json:"headimgurl"`
+	Unionid        string `json:"unionid"`
+	Errcode        int    `json:"errcode"`
+	Errmsg         string `json:"errmsg"`
+}
+
+func PcWxGetUserInfo(openId, accessToken string) (item *PcWxUserInfo, err error) {
+	requestUrl := `https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s`
+	requestUrl = fmt.Sprintf(requestUrl, accessToken, openId)
+	result, err := http.Get(requestUrl)
+	if err != nil {
+		return
+	}
+	fmt.Println("result:",string(result))
+	utils.FileLog.Info("WxGetUserInfo:%s openId:%s,accessToken:%s ", string(result), openId, accessToken)
+	utils.FileLog.Info("WxGetUserInfo Result:%s ", string(result))
+	err = json.Unmarshal(result, &item)
+	return
+}

+ 4 - 5
utils/config.go

@@ -51,9 +51,8 @@ func init() {
 		TemplateIdByProduct = "Cp2wF8gvBtxyWV4DeYuI172oqwyYXVRSm3AyJO42d84"
 		TemplateRedirectUrl = "https://ficc.hzinsights.com/reportdtl?id="
 
-		PcWxId = "wx615472d6874eeb7f"
-		PcWxAppId = "97fe374fb0cc90ef58c4b49d431366f1"
-
+		PcWxAppId = "wx615472d6874eeb7f"
+		PcWxAppSecret="97fe374fb0cc90ef58c4b49d431366f1"
 		STATIC_DIR = "/home/static/imgs/"
 	} else {
 		WxAppId = "wx9b5d7291e581233a"
@@ -62,8 +61,8 @@ func init() {
 		TemplateIdByProduct = "-YjuPOB7Fqd-S3ilabYa6wvjDY9aXmeEfPN6DCiy-EY"
 		TemplateRedirectUrl = "http://rddpweb.brilliantstart.cn/reportdtl?id="
 
-		PcWxId = "wx615472d6874eeb7f"
-		PcWxAppId = "26c586e7ccb3c575433f0f37797b3eeb"
+		PcWxAppId = "wx7c8084f6e5b1d85a"
+		PcWxAppSecret="9e4210cd5a363aa1f316b7c4b8898418"
 
 		STATIC_DIR = "/home/static/imgs/"
 	}