package pc

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"hongze/hongze_yb/controller/response"
	userLogic "hongze/hongze_yb/logic/user"
	pcModels "hongze/hongze_yb/models/response/pc"
	"hongze/hongze_yb/models/tables/customer_comment"
	"hongze/hongze_yb/models/tables/rddp/classify"
	"hongze/hongze_yb/models/tables/rddp/msg_code"
	"hongze/hongze_yb/models/tables/rddp/report"
	"hongze/hongze_yb/models/tables/rddp/report_chapter"
	"hongze/hongze_yb/models/tables/rddp/session"
	"hongze/hongze_yb/models/tables/wx_user"
	"hongze/hongze_yb/models/tables/wx_user_log"
	"hongze/hongze_yb/models/tables/yb_activity"
	"hongze/hongze_yb/models/tables/yb_pc_suncode"
	"hongze/hongze_yb/services"
	"hongze/hongze_yb/services/pc"
	report2 "hongze/hongze_yb/services/report"
	userService "hongze/hongze_yb/services/user"
	"hongze/hongze_yb/services/wechat"
	"hongze/hongze_yb/utils"
	"strconv"
	"time"
)

// LatestNews 研报首页最新资讯
func LatestNews(c *gin.Context) {
	reqChartPermissionId := c.DefaultQuery("chart_permission_id", "")
	if reqChartPermissionId == "" {
		response.Fail("请输入权限ID", c)
		return
	}
	chartPermissionId, err := strconv.Atoi(reqChartPermissionId)
	if err != nil {
		response.Fail("权限ID格式错误", c)
		return
	}
	userinfo := userService.GetInfoByClaims(c)

	list, err := pc.GetLatestReportList(userinfo, chartPermissionId)
	if err != nil {
		response.Fail("获取报告失败", c)
		return
	}

	//recommendList, err := pcModels.GetLatestReportList()
	//if err != nil {
	//	response.Fail("获取报告详情失败"+err.Error(), c)
	//	return
	//}

	response.OkData("查询成功", list, c)
	return
}

// Banner 上新公告banner图
func Banner(c *gin.Context) {
	var resp pcModels.LatestReleaseResp
	activityItem, err := yb_activity.GetLatestActivity()
	if err != nil {
		response.Fail(err.Error(), c)
		return
	}
	reportItem, err := report.GetLatestReport()
	if err != nil {
		response.Fail(err.Error(), c)
		return
	}
	imgMap := map[string]string{
		"晨报":      utils.ALIYUN_YBIMG_HOST + "day.png",
		"周报":      utils.ALIYUN_YBIMG_HOST + "week.png",
		"双周报":     utils.ALIYUN_YBIMG_HOST + "two_week.png",
		"月报":      utils.ALIYUN_YBIMG_HOST + "month.png",
		"草根调研":    utils.ALIYUN_YBIMG_HOST + "cgdy.png",
		"需求报告":    utils.ALIYUN_YBIMG_HOST + "xqbg.png",
		"宏观报告":    utils.ALIYUN_YBIMG_HOST + "hgbg.png",
		"日度点评":    utils.ALIYUN_YBIMG_HOST + "rddp.png",
		"数据点评":    utils.ALIYUN_YBIMG_HOST + "sjdp.png",
		"碳市场价格周报": utils.ALIYUN_YBIMG_HOST + "coal.png",
		"行业调研":    utils.ALIYUN_YBIMG_HOST + "hydy.png",
		"百家谈":     utils.ALIYUN_YBIMG_HOST + "bjt.png",
		"会议纪要":    utils.ALIYUN_YBIMG_HOST + "hyjy.png",
		"大事点评":    utils.ALIYUN_YBIMG_HOST + "dsdp.png",
		"年报合集":    utils.ALIYUN_YBIMG_HOST + "nbhj.png",
	}
	if activityItem.CreateTime.Before(reportItem.PublishTime) {
		resp.ActivityOrReport = 1
		resp.ReportId = reportItem.ReportId
		resp.ClassifyIdSecond = reportItem.ClassifyIdSecond
		resp.ImgUrl = imgMap[reportItem.ClassifyNameFirst]
	} else {
		resp.ActivityOrReport = 0
		resp.Activity = activityItem
		resp.ImgUrl = utils.ALIYUN_YBIMG_HOST + "activity.png"
	}

	response.OkData("查询成功", resp, c)
	return
}

// LatestRelease 上新公告
func LatestRelease(c *gin.Context) {
	classifyIdString := c.DefaultQuery("ClassifyId", "")
	if classifyIdString == "" {
		response.Fail("请输入classifyId", c)
		return
	}

	classifyId, err := strconv.Atoi(classifyIdString)
	if err != nil {
		response.Fail("请输入正确classifyId", c)
		return
	}
	classifyInfo, err := classify.GetByClassifyId(classifyId)
	if err != nil {
		response.Fail("分类查询出错", c)
		return
	}

	response.OkData("查询成功", classifyInfo, c)
	return
}

// ClassifyDetail 专栏详情
func ClassifyDetail(c *gin.Context) {
	reqClassifyIdSecond := c.DefaultQuery("classify_id_second", "")
	if reqClassifyIdSecond == "" {
		response.Fail("请输入二级分类标识", c)
		return
	}

	classifyIdSecond, err := strconv.Atoi(reqClassifyIdSecond)
	if err != nil {
		response.Fail("请输入正确的二级分类标识", c)
		return
	}
	userinfo := userService.GetInfoByClaims(c)

	detail, err := pc.GetClassifyDetail(userinfo, classifyIdSecond)
	if err != nil {
		response.Fail(err.Error(), c)
		return
	}
	response.OkData("查询成功", detail, c)
	return
}

// ClassifyDetailBanner 专栏详情banner图
func ClassifyDetailBanner(c *gin.Context) {
	reqReportId := c.DefaultQuery("reportId", "")
	//classifyName := c.DefaultQuery("classify_name_first", "")
	//if reqReportId == "" {
	//	response.Fail("请输入二级分类标识", c)
	//	return
	//}
	reportId, err := strconv.Atoi(reqReportId)
	if err != nil {
		response.Fail("报告ID格式有误", c)
		return
	}
	reportInfo, err := report.GetByReportId(reportId)
	if err != nil {
		response.Fail("报告查询出错", c)
		return
	}

	//查询分类类别，根据分类配置显示专栏还是报告合集
	parentClassify, err := classify.GetByClassifyIdFirst(reportInfo.ClassifyIdFirst)
	if err != nil {
		response.Fail("获取分类信息失败"+err.Error(), c)
		return
	}
	minClassifyId, _, err := report2.GetMinClassify(reportInfo)
	if err != nil {
		response.FailMsg("查询最新一期报告合集失败", "查询最新一期报告合集失败1:"+err.Error(), c)
		return
	}

	var bannerResp *pcModels.DetailBannerResp
	if reportInfo.HasChapter == 1 {
		chapterItem, err := report_chapter.GetLatestChapterByMinClassifyId(minClassifyId)
		if err != nil {
			response.FailMsg("查询最新一期报告合集失败2", "查询最新一期报告合集失败2:"+err.Error(), c)
			return
		}
		resp := &pcModels.DetailBannerResp{
			ReportId:          chapterItem.ReportId,
			ClassifyNameFirst: chapterItem.ClassifyNameFirst,
			ClassifyIdFirst:   chapterItem.ClassifyIdFirst,
			Stage:             chapterItem.Stage,
			ImgUrl:            "",
			Type:              "报告合集",
			ShowType:          1,
		}
		bannerResp = resp
	} else {
		if reportInfo.Id == 0 {
			response.Fail("报告不存在", c)
			return
		}

		if reportInfo.State != 2 && reportInfo.State != 6 {
			response.Fail("报告未发布", c)
			return
		}

		reportItem, err := report.GetLatestReportByClassifyId(reportInfo.ClassifyIdFirst, reportInfo.ClassifyIdSecond, reportInfo.ClassifyIdThird)
		if err != nil {
			response.Fail("获取报告详情失败"+err.Error(), c)
			return
		}
		//查询分类类别，根据分类配置显示专栏还是报告合集
		minClassify, err := classify.GetByClassifyId(minClassifyId)
		if err != nil {
			response.FailMsg("获取分类信息失败", "获取分类信息失败"+err.Error(), c)
			return
		}

		resp := &pcModels.DetailBannerResp{
			ReportId:           reportItem.ReportId,
			Stage:              reportItem.Stage,
			VipTitle:           minClassify.VipTitle,
			Author:             reportItem.Author,
			ReportAuthor:       minClassify.ReportAuthor,
			ImgUrl:             "",
			ClassifyNameFirst:  reportItem.ClassifyNameFirst,
			ClassifyIdFirst:    reportItem.ClassifyIdFirst,
			ClassifyNameSecond: reportItem.ClassifyNameSecond,
			ClassifyIdSecond:   reportItem.ClassifyIdSecond,
			ShowType:           minClassify.ShowType,
		}

		if parentClassify.ShowType == 1 || parentClassify.ShowType == 3 {
			resp.Type = "报告合集"
		} else {
			resp.Type = "专栏详情"
		}
		bannerResp = resp
	}
	//有人的用人的底图，和上新公告图片不完全一样
	/*firstNameMap := map[string]string{
		"晨报":  utils.ALIYUN_YBIMG_HOST + "day.png",
		"周报":  utils.ALIYUN_YBIMG_HOST + "week.png",
		"双周报": utils.ALIYUN_YBIMG_HOST + "two_week.png",
		"月报":  utils.ALIYUN_YBIMG_HOST + "month.png",

		"会议纪要": utils.ALIYUN_YBIMG_HOST + "hyjy.png",
		"大事点评": utils.ALIYUN_YBIMG_HOST + "dsdp.png",
		"年报合集": utils.ALIYUN_YBIMG_HOST + "nbhj.png",

		//"草根调研":    utils.ALIYUN_YBIMG_HOST + "hy.png",
		//"需求报告":    utils.ALIYUN_YBIMG_HOST + "lxt.png",
		//"碳市场价格周报": utils.ALIYUN_YBIMG_HOST + "sjx.png",
		//"行业调研":    utils.ALIYUN_YBIMG_HOST + "qp.png",
	}*/
	//secondNameMap := map[string]string{
	//	//宏观报告
	//	"宏观周期观察":     utils.ALIYUN_YBIMG_HOST + "gx.png",
	//	"房地产市场跟踪":    utils.ALIYUN_YBIMG_HOST + "gx.png",
	//	"货币政策跟踪":     utils.ALIYUN_YBIMG_HOST + "gx.png",
	//	"全球宏观经济周度回顾": utils.ALIYUN_YBIMG_HOST + "ldb.png",
	//	"宏观点评":       utils.ALIYUN_YBIMG_HOST + "zzh.png",
	//	//日度点评
	//	"知白守黑日评":    utils.ALIYUN_YBIMG_HOST + "wxy.png",
	//	"有声有色日度闲":   utils.ALIYUN_YBIMG_HOST + "qp.png",
	//	"化里化外日评":    utils.ALIYUN_YBIMG_HOST + "qmz.png",
	//	"每日经济数据备忘录": utils.ALIYUN_YBIMG_HOST + "ldb.png",
	//	"股债日评":      utils.ALIYUN_YBIMG_HOST + "zzh.png",
	//	"贵金属复盘":     utils.ALIYUN_YBIMG_HOST + "hx.png",
	//	//数据点评
	//	"钢材周度数据点评":   utils.ALIYUN_YBIMG_HOST + "wxy.png",
	//	"甲醇开工数据点评":   utils.ALIYUN_YBIMG_HOST + "lqx.png",
	//	"短纤数据点评":     utils.ALIYUN_YBIMG_HOST + "zyy.png",
	//	"玻璃数据点评":     utils.ALIYUN_YBIMG_HOST + "gwy.png",
	//	"聚烯烃数据点评":    utils.ALIYUN_YBIMG_HOST + "lqx.png",
	//	"铜行业数据点评":    utils.ALIYUN_YBIMG_HOST + "yf.png",
	//	"国际钢材市场数据点评": utils.ALIYUN_YBIMG_HOST + "bx.png",
	//	"废钢周度数据点评":   utils.ALIYUN_YBIMG_HOST + "bx.png",
	//	"PP数据点评":     utils.ALIYUN_YBIMG_HOST + "lqx.png",
	//	"PVC数据点评":    utils.ALIYUN_YBIMG_HOST + "lyx.png",
	//	"BOPP数据点评":   utils.ALIYUN_YBIMG_HOST + "lqx.png",
	//	"塑编数据点评":     utils.ALIYUN_YBIMG_HOST + "lqx.png",
	//	"铁矿库存数据点评":   utils.ALIYUN_YBIMG_HOST + "hk.png",
	//	"宏观数据点评":     utils.ALIYUN_YBIMG_HOST + "zzh.png",
	//	"铝数据点评":      utils.ALIYUN_YBIMG_HOST + "yf.png",
	//	"甲醇库存数据点评":   utils.ALIYUN_YBIMG_HOST + "lqx.png",
	//	"玻璃纯碱数据点评":   utils.ALIYUN_YBIMG_HOST + "gwy.png",
	//	"乙二醇数据点评":    utils.ALIYUN_YBIMG_HOST + "zyy.png",
	//	"纯碱数据点评":     utils.ALIYUN_YBIMG_HOST + "gwy.png",
	//	"COVID-19跟踪": utils.ALIYUN_YBIMG_HOST + "lxt.png",
	//	"双焦数据点评":     utils.ALIYUN_YBIMG_HOST + "zs.png",
	//	"苯乙烯库存数据点评":  utils.ALIYUN_YBIMG_HOST + "cy.png",
	//	"苯乙烯数据点评":    utils.ALIYUN_YBIMG_HOST + "cy.png",
	//	"苯乙烯简评":      utils.ALIYUN_YBIMG_HOST + "cy.png",
	//	"EIA天然气库存点评": utils.ALIYUN_YBIMG_HOST + "wyy.png",
	//	"美国油气钻机数据点评": utils.ALIYUN_YBIMG_HOST + "wyy.png",
	//	"OPEC+产量点评":  utils.ALIYUN_YBIMG_HOST + "hyy.png",
	//	"原油船期数数据跟踪":  utils.ALIYUN_YBIMG_HOST + "wyy.png",
	//	"EIA原油库存点评":  utils.ALIYUN_YBIMG_HOST + "hyy.png",
	//	"苯乙烯开工数据点评":  utils.ALIYUN_YBIMG_HOST + "cy.png",
	//	"聚酯数据点评":     utils.ALIYUN_YBIMG_HOST + "qc.png",
	//	"铁矿航运数据点评":   utils.ALIYUN_YBIMG_HOST + "hk.png",
	//	//百家谈
	//	"能化百家谈": utils.ALIYUN_YBIMG_HOST + "qmz.png",
	//	"有色百家谈": utils.ALIYUN_YBIMG_HOST + "qp.png",
	//	"黑色百家谈": utils.ALIYUN_YBIMG_HOST + "wxy.png",
	//}
	authorMap := map[string]string{
		"白昕":           utils.ALIYUN_YBIMG_HOST + "bx.png",
		"曹阳":           utils.ALIYUN_YBIMG_HOST + "cy.png",
		"曾硕":           utils.ALIYUN_YBIMG_HOST + "zs.png",
		"曾滢月":          utils.ALIYUN_YBIMG_HOST + "zyy.png",
		"程品":           utils.ALIYUN_YBIMG_HOST + "cp.png",
		"高雯宇":          utils.ALIYUN_YBIMG_HOST + "gwy.png",
		"高昕":           utils.ALIYUN_YBIMG_HOST + "gx.png",
		"高吟":           utils.ALIYUN_YBIMG_HOST + "gy.png",
		"陈聪聪":          utils.ALIYUN_YBIMG_HOST + "ccc.png",
		"何凯":           utils.ALIYUN_YBIMG_HOST + "hk.png",
		"黄鑫":           utils.ALIYUN_YBIMG_HOST + "hx.png",
		"黄逸赟":          utils.ALIYUN_YBIMG_HOST + "hyy.png",
		"黄溢":           utils.ALIYUN_YBIMG_HOST + "hy.png",
		"李灵":           utils.ALIYUN_YBIMG_HOST + "ll.png",
		"林秋馨":          utils.ALIYUN_YBIMG_HOST + "lqx.png",
		"刘鼎邦":          utils.ALIYUN_YBIMG_HOST + "ldb.png",
		"钱鹏":           utils.ALIYUN_YBIMG_HOST + "qp.png",
		"刘艺羡":          utils.ALIYUN_YBIMG_HOST + "lyx.png",
		"戚明之":          utils.ALIYUN_YBIMG_HOST + "qmz.png",
		"秦钏":           utils.ALIYUN_YBIMG_HOST + "qc.png",
		"施琪":           utils.ALIYUN_YBIMG_HOST + "sq.png",
		"王存响":          utils.ALIYUN_YBIMG_HOST + "wcx.png",
		"王沛":           utils.ALIYUN_YBIMG_HOST + "wp.png",
		"苏畅":           utils.ALIYUN_YBIMG_HOST + "sc.png",
		"史瑾璇":          utils.ALIYUN_YBIMG_HOST + "sjx.png",
		"王亚丹":          utils.ALIYUN_YBIMG_HOST + "wyd.png",
		"虞风":           utils.ALIYUN_YBIMG_HOST + "yf.png",
		"魏忻悦":          utils.ALIYUN_YBIMG_HOST + "wxy.png",
		"王艺滢":          utils.ALIYUN_YBIMG_HOST + "wyy.png",
		"姚昕泽":          utils.ALIYUN_YBIMG_HOST + "yxz.png",
		"章左昊":          utils.ALIYUN_YBIMG_HOST + "zzh.png",
		"李晓瞳":          utils.ALIYUN_YBIMG_HOST + "lxt.png",
		"弘则FICC无锡调研团队": utils.ALIYUN_YBIMG_HOST + "qp.png",
		"弘则能化组":        utils.ALIYUN_YBIMG_HOST + "qmz.png",
		"弘则有色团队":       utils.ALIYUN_YBIMG_HOST + "qp.png",
		"弘则黑色团队":       utils.ALIYUN_YBIMG_HOST + "wp.png",
		"弘则宏观团队":       utils.ALIYUN_YBIMG_HOST + "zzh.png",
		"张立舟":          utils.ALIYUN_YBIMG_HOST + "zlz.png",
		"郑露":           utils.ALIYUN_YBIMG_HOST + "zl.png",
		"酒子怡":          utils.ALIYUN_YBIMG_HOST + "jzy.png",
	}

	if parentClassify.ShowType == 1 || parentClassify.ShowType == 3 {
		bannerResp.ImgUrl = parentClassify.YbRightBanner
	} else if url, ok := authorMap[bannerResp.ReportAuthor]; ok {
		bannerResp.ImgUrl = url
	}
	response.OkData("查询成功", bannerResp, c)
	return
}

// Recommend 报告详情页更多推荐
func Recommend(c *gin.Context) {
	reqReportId := c.DefaultQuery("reportId", "")
	if reqReportId == "" {
		response.Fail("请输入二级分类标识", c)
		return
	}
	reportId, err := strconv.Atoi(reqReportId)
	if err != nil {
		response.Fail("报告ID格式有误", c)
		return
	}
	reportInfo, err := report.GetByReportId(reportId)
	if err != nil {
		response.Fail("报告查询出错", c)
		return
	}
	if reportInfo.Id == 0 {
		response.Fail("报告不存在", c)
		return
	}
	minClassifyId, _, err := report2.GetMinClassify(reportInfo)
	if err != nil {
		response.FailMsg("查询最新一期报告合集失败", "查询最新一期报告合集失败1:"+err.Error(), c)
		return
	}

	var recommendResp []*pcModels.RecommendResp
	if reportInfo.HasChapter == 1 {
		recommendList, err := report_chapter.GetWeekRecommendListV2(reportId, minClassifyId)
		if err != nil {
			response.FailMsg("获取推荐报告列表失败", "获取推荐报告列表失败："+err.Error(), c)
			return
		}
		for _, chapter := range recommendList {
			resp := &pcModels.RecommendResp{
				ReportId:            chapter.ReportId,
				ReportChapterID:     chapter.ReportChapterId,
				Title:               chapter.Title,
				Stage:               chapter.Stage,
				ClassifyNameFirst:   chapter.ClassifyNameFirst,
				ClassifySecondFirst: "",
			}
			recommendResp = append(recommendResp, resp)
		}
	} else {

		if reportInfo.State != 2 && reportInfo.State != 6 {
			response.Fail("报告未发布", c)
			return
		}

		reportType := 0
		if reportInfo.ClassifyNameFirst == "权益研报" {
			reportType = 1
		} else {
			reportType = 2
		}

		recommendList := make([]*pcModels.Report, 0)
		if reportInfo.RaiReportId > 0 {
			recommendList, err = pcModels.GetRaiRecommendList(reportId, reportInfo.ClassifyIdFirst, reportInfo.ClassifyIdSecond, reportInfo.ClassifyIdThird, reportInfo.PublishTime)
			if err != nil {
				response.Fail("获取报告详情失败"+err.Error(), c)
				return
			}
		} else {
			recommendList, err = pcModels.GetRecommendListV2(reportId, reportType, reportInfo.ClassifyIdFirst, reportInfo.ClassifyIdSecond, reportInfo.ClassifyIdThird)
			if err != nil {
				response.Fail("获取报告详情失败"+err.Error(), c)
				return
			}
		}
		for _, chapter := range recommendList {
			resp := &pcModels.RecommendResp{
				ReportId:            chapter.Id,
				ReportChapterID:     0,
				Title:               chapter.Title,
				Stage:               chapter.Stage,
				ClassifyNameFirst:   chapter.ClassifyNameFirst,
				ClassifySecondFirst: chapter.ClassifyNameSecond,
				RaiReportId:         chapter.RaiReportId,
			}
			recommendResp = append(recommendResp, resp)
		}
	}
	response.OkData("查询成功", recommendResp, c)
	return
}

// ClassifyFirstList Ficc 菜单
func ClassifyFirstList(c *gin.Context) {
	userinfo := userService.GetInfoByClaims(c)

	classList, err := pc.GetClassifyFirstList(userinfo)
	if err != nil {
		response.Fail(err.Error(), c)
		return
	}
	response.OkData("查询成功", classList, c)
	return
}

// CustomerComment 客户评价
func CustomerComment(c *gin.Context) {
	lists, err := customer_comment.GetCustomerComment()
	if err != nil {
		response.Fail(err.Error(), c)
		return
	}
	response.OkData("查询成功", lists, c)
	return
}

// GetSunCode 获取太阳码
// @Tags 公共模块
// @Summary  获取分享海报
// @Description 获取分享海报
// @Param	request	body services.SunCodeReq true "type json string"
// @Success 200 {object} string "获取成功"
// @failure 400 {string} string "获取失败"
// @Router /pc/getSunCode [post]
func GetSunCode(c *gin.Context) {
	var req services.SunCodeReq
	if c.ShouldBind(&req) != nil {
		response.Fail("参数异常", c)
		return
	}

	var sunCodeUrl string
	//先查，查不到再去生成上传
	item, err := yb_pc_suncode.GetYbPcSunCode(req.CodeScene, req.CodePage)
	if err != nil && err != utils.ErrNoRow {
		response.FailMsg("获取太阳码失败", err.Error(), c)
		return
	}
	if item != nil && item.SuncodeURL != "" {
		sunCodeUrl = item.SuncodeURL
	}
	if sunCodeUrl == "" {
		sunCodeUrl, err = services.PcCreateAndUploadSunCode(req.CodeScene, req.CodePage)
		if err != nil {
			response.FailMsg("生成太阳码失败:err:"+err.Error(), err.Error(), c)
			return
		}
	}

	response.OkData("查询成功", sunCodeUrl, c)
	return
}

// @Title pc端微信登录接口
// @Description pc端微信登录接口
// @Param   Code   query   string  true       "微信唯一编码code"
// @Success 200 {object} models.WxLoginResp
// @router /pc/login [get]
func WechatLogin(c *gin.Context) {
	var resp pcModels.LoginResp
	var token string
	var userId int
	var isBind bool
	code := c.DefaultQuery("Code", "")
	if code == "" {
		response.Fail("code参数错误", c)
		return
	}
	item, err := wechat.PcWxGetUserOpenIdByCode(code)
	if err != nil {
		response.Fail(err.Error(), c)
		return
	}
	fmt.Println("token:", item.AccessToken)
	fmt.Println("token:", item.Errmsg)
	fmt.Println("token:", item.Errcode)
	if item.Errcode != 0 {
		response.Fail(item.Errmsg, c)
		return
	}

	openId := item.Openid
	//wxUserInfo, err := wx_app.GetSession(code)
	//if err != nil {
	//	response.Fail("获取失败，Err:"+err.Error(), c)
	//	return
	//}

	//获取用户信息
	wxPcUserInfo, err := wechat.PcWxGetUserInfo(openId, item.AccessToken)
	if err != nil {
		response.Fail(err.Error(), c)
		return
	}
	if wxPcUserInfo.Errcode != 0 {
		response.Fail(err.Error(), c)
		return
	}

	unionId := item.Unionid
	//sessionKey := wxUserInfo.SessionKey
	//needUpdateSessionKey := true //是否更新sessionKey

QUERY_WX_USER:
	wxUser, wxUserErr := userService.GetWxUserItemByOpenId(openId)
	if wxUserErr == userService.ERR_NO_USER_RECORD { //没有用户openid记录
		_, recordErr := userService.AddUserRecord(openId, unionId, "", "", "", "", "", "", "", 3, 0, 0)
		//如果插入失败，那么直接将错误信息返回
		if recordErr != nil {
			err = recordErr
			return
		}
		//needUpdateSessionKey = false //因为是新增用户微信信息，所以不需要更新sessionKey的数据了

		//插入成功后，需要重新查询该用户，并进入下面的逻辑
		goto QUERY_WX_USER
	} else if wxUserErr == userService.ERR_USER_NOT_BIND {
		// 未绑定则去查询unionId是否已经绑定了用户（其他平台，不区分平台），有相应的手机号邮箱信息则自动绑定
		//platformUser, platformErr := userService.GetFirstWxUserItemByUnionId(unionId)
		//if platformErr == nil {
		//	// 当公众号用户存在时
		//	if platformUser.Mobile != "" || platformUser.Email != "" {
		//		// 有手机号或邮箱则绑定信息则自动绑定并新增wx_user
		//		countryCode := 0
		//		if platformUser.CountryCode != "" {
		//			countryCode, _ = strconv.Atoi(platformUser.CountryCode)
		//		}
		//		tempToken, tempUser, tempErr, errMsg := userService.BindWxUser(openId, platformUser.Mobile, platformUser.Email, "", 3, countryCode, 1)
		//		if tempErr != nil {
		//			err = errors.New("自动绑定公众号用户失败，Err：" + tempErr.Error() + ", errMsg：" + errMsg)
		//			return
		//		}
		//		token = tempToken
		//		userId = int(tempUser.UserID)
		//		isBind = true
		//	}
		//}
	} else if wxUserErr != nil {
		err = wxUserErr
		return
	}

	//更新微信用户的sessionKey
	//if needUpdateSessionKey {
	//	_ = user_record.ModifySessionKeyByOpenid(openId, sessionKey)
	//}

	// 如果已经登录注册绑定的情况下/或者首次登录且为弘则研究公众号用户
	if wxUserErr == nil {
		userId = int(wxUser.UserID)

		// 如果账户有绑定了手机号或者邮箱，那么标记为已绑定
		if wxUser.Mobile != "" || wxUser.Email != "" {
			isBind = true
		}
	}

	//获取登录token
	tokenItem, tokenErr := session.GetTokenByOpenId(openId)
	if tokenErr != nil && tokenErr != utils.ErrNoRow {
		err = errors.New("登录失败，获取token失败:" + tokenErr.Error())
		return
	}
	fmt.Println("AccessToken:", item.AccessToken)
	fmt.Println("tokenItem:", tokenItem.AccessToken)
	if tokenErr != nil && tokenErr == utils.ErrNoRow {
		timeUnix := time.Now().Unix()
		timeUnixStr := strconv.FormatInt(timeUnix, 10)
		token = utils.MD5(openId) + utils.MD5(timeUnixStr)
		fmt.Println("token:", tokenItem.AccessToken)
		//新增session
		{
			sessionItem := &session.Session{
				OpenID:          openId,
				UserID:          int64(userId),
				CreatedTime:     time.Now(),
				LastUpdatedTime: time.Now(),
				ExpireTime:      time.Now().AddDate(0, 3, 0),
				AccessToken:     token,
			}
			sessionErr := sessionItem.Create()
			if err != nil {
				err = errors.New("登录失败，新增用户session信息失败:" + sessionErr.Error())
				return
			}
		}
	} else {
		token = tokenItem.AccessToken
		//如果联系人编号不为空，且联系人编号与session里面的联系人编号不一致的时候，需要做session变更
		//if userId > 0 && tokenItem.UserID != int64(userId) {
		//	_ = tokenItem.UpdateSession(int64(userId), time.Now().AddDate(0, 1, 0))
		//}

		//if userId > 0 {
		//}
		_ = tokenItem.UpdateSession(int64(userId), time.Now().AddDate(0, 1, 0))
	}

	//新增登录日志
	{
		loginLog := &wx_user_log.WxUserLog{
			UserID:     userId,
			OpenID:     openId,
			UnionID:    unionId,
			CreateTime: time.Now(),
			Handle:     "yb_login",
			Remark:     token,
		}
		go loginLog.Create()
	}
	resp.IsBind = isBind
	resp.Token = token
	response.OkData("查询成功", resp, c)
	return
}

// @Title 登录
// @Description 登录接口
// @Param	request	body models.LoginReq true "type json string"
// @Success 200 {object} models.LoginResp
// @router /pc/pcLogin [post]
func PcLogin(c *gin.Context) {
	var req pcModels.PcLoginReq
	if c.ShouldBind(&req) != nil {
		response.Fail("参数异常", c)
		return
	}

	userId := 0
	var isAdd bool
	if req.LoginType == 1 {
		if req.Mobile == "" {
			response.Fail("请输入手机号", c)
			return
		}
		if req.SmsCode == "" {
			response.Fail("请输入有效手机验证码", c)
			return
		}
		item, err := msg_code.GetMsgCode(req.Mobile, req.SmsCode)
		if err != nil {
			if err == utils.ErrNoRow {
				response.Fail("校验验证码失败，Err:"+err.Error(), c)
				return
			} else {
				response.Fail("校验验证码失败，Err:"+err.Error(), c)
				return
			}
		}
		if item == nil {
			response.Fail("手机验证码错误,请重新输入", c)
			return
		}
		if item.Code != req.SmsCode {
			response.Fail("验证码失效,请重新最新验证码", c)
			return
		}

		wxUser, err := wx_user.GetByMobile(req.Mobile)
		if err != nil {
			if err == utils.ErrNoRow {
				isAdd = true
			} else {
				response.Fail("根据手机号获取用户信息失败，Err:"+err.Error(), c)
				return
			}
		}
		if wxUser == nil {
			isAdd = true
		} else {
			userId = int(wxUser.UserID)
		}
		//BindMobile(openId, mobile string, userId, loginType int) (err error) {
		//newUserId, err = models.BindMobile(openId, req.Mobile, userId, req.LoginType)
	} else if req.LoginType == 2 {
		if req.Email == "" {
			response.Fail("邮箱不能为空,请输入邮箱", c)
			return
		}
		if !utils.ValidateEmailFormatat(req.Email) {
			response.Fail("邮箱格式错误，请重新输入", c)
			return
		}
		if req.SmsCode == "" {
			response.Fail("请输入有效验证码", c)
			return
		}
		item, err := msg_code.GetMsgCode(req.Email, req.SmsCode)
		if err != nil {
			if err == utils.ErrNoRow {
				response.Fail("校验验证码失败，Err:"+err.Error(), c)
				return
			} else {
				response.Fail("校验验证码失败，Err:"+err.Error(), c)
				return
			}
		}
		if item == nil {
			response.Fail("邮箱证码错误,请重新输入:", c)
			return
		}
		wxUser, err := wx_user.GetByEmail(req.Email)
		if err != nil {
			if err == utils.ErrNoRow {
				isAdd = true
			} else {
				response.Fail("根据邮箱获取用户信息失败,Err:"+err.Error(), c)
				return
			}
		}
		if wxUser == nil {
			isAdd = true
		} else {
			userId = int(wxUser.UserID)
		}
	} else {
		response.Fail("无效的登录方式,loginType:"+strconv.Itoa(req.LoginType), c)
	}
	if isAdd {
		user := new(wx_user.WxUser)
		user.CompanyID = 1
		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.RegisterPlatform = 2
		if req.IsFreeLogin {
			user.IsFreeLogin = 1
		} else {
			user.IsFreeLogin = 0
		}

		lastId, err := user.Add()
		if err != nil {
			response.Fail("登录失败,新增客户信息失败,Err:"+err.Error(), c)
			return
		}
		fmt.Println("lastId：", lastId)
		userId = int(lastId)

		timeUnix := time.Now().Unix()
		timeUnixStr := strconv.FormatInt(timeUnix, 10)
		token := utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
		//新增session
		{
			session := new(session.Session)
			session.UserID = int64(userId)
			session.CreatedTime = time.Now()
			session.LastUpdatedTime = time.Now()
			session.ExpireTime = time.Now().AddDate(0, 3, 0)
			session.AccessToken = token
			err = session.Create()
			if err != nil {
				response.Fail("登录失败，新增用户session信息失败:"+err.Error(), c)
				return
			}
		}
	} else {
		user := new(wx_user.WxUser)
		user.UserID = uint64(userId)
		if req.IsFreeLogin {
			user.IsFreeLogin = 1
		} else {
			user.IsFreeLogin = 0
		}

		err := user.Update([]string{"is_free_login"})
		if err != nil {
			response.Fail("登录失败,修改登录信息失败,Err:"+err.Error(), c)
			return
		}
	}
	if userId == 0 {
		response.Fail("登录失败,id为 0", c)
		return
	}

	err := wx_user.ModifyFirstLogin(uint64(userId))
	if err != nil {
		response.Fail("登录失败，判断权限失败:"+err.Error(), c)
		return
	}
	var token string
	tokenItem, err := session.GetTokenByUid(userId)
	if err != nil && err != utils.ErrNoRow {
		response.Fail("登录失败，获取token失败:"+err.Error(), c)
		return
	}

	if tokenItem == nil || (err != nil && err == utils.ErrNoRow) {
		timeUnix := time.Now().Unix()
		timeUnixStr := strconv.FormatInt(timeUnix, 10)
		token = utils.MD5(strconv.Itoa(userId)) + utils.MD5(timeUnixStr)
		//新增session
		{
			session := new(session.Session)
			session.UserID = int64(userId)
			session.CreatedTime = time.Now()
			session.LastUpdatedTime = time.Now()
			session.ExpireTime = time.Now().AddDate(0, 3, 0)
			session.AccessToken = token
			err = session.Create()
			if err != nil {
				response.Fail("登录失败，新增用户session信息失败:"+err.Error(), c)
				return
			}
		}
	} else {
		token = tokenItem.AccessToken
	}

	//新增登录日志
	{
		loginLog := new(wx_user_log.WxUserLog)
		loginLog.UserID = userId
		loginLog.Mobile = req.Mobile
		loginLog.Email = req.Email
		loginLog.Handle = "pc_login"
		loginLog.CreateTime = time.Now()
		go loginLog.Create()
	}

	response.OkData("登录成功", token, c)
}

// GetSmsCode 获取短信验证码接口
// @Tags 用户模块
// @Summary  获取短信验证码
// @Description 获取短信验证码接口
// @Security ApiKeyAuth
// @securityDefinitions.basic BasicAuth
// @Param mobile	query string true "手机号"
// @Param area_num	query string true "手机国际区号（中国大陆：86）"
// @Accept  json
// @Product json
// @Success 200 {string} string 获取验证码成功
// @Failure 400 {string} string 手机号不能为空,请输入手机号
// @Router /pc_code/get_sms_code [get]
func GetSmsCode(c *gin.Context) {
	mobile := c.DefaultQuery("mobile", "")
	areaNum := c.DefaultQuery("area_num", "")
	err, errMsg := userLogic.PcSendSmsCode(mobile, areaNum)
	if err != nil {
		if errMsg != "" {
			errMsg = "获取验证码失败"
		} else {
			errMsg = err.Error()
		}
		response.Fail(errMsg, c)
		return
	}

	response.Ok("获取验证码成功", c)
}

// GetEmailCode 获取邮箱验证码接口
// @Tags 用户模块
// @Summary  获取邮箱验证码
// @Description 获取邮箱验证码
// @Security ApiKeyAuth
// @securityDefinitions.basic BasicAuth
// @Param email	query string true "电子邮箱账号"
// @Accept  json
// @Product json
// @Success 200 {string} string 获取验证码成功
// @Failure 400 {string} string 请输入邮箱地址
// @Router /pc_code/get_email_code [get]
func GetEmailCode(c *gin.Context) {
	email := c.DefaultQuery("email", "")
	if email == "" {
		response.Fail("请输入邮箱地址", c)
		return
	}
	if !utils.ValidateEmailFormatat(email) {
		response.Fail("邮箱格式错误，请重新输入", c)
		return
	}

	err, errMsg := userLogic.PcSendEmailCode(email)
	if err != nil {
		if errMsg != "" {
			errMsg = "获取验证码失败"
		} else {
			errMsg = err.Error()
		}
		response.Fail(errMsg, c)
		return
	}

	response.Ok("获取验证码成功", c)
}
