package controllers

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/common"
	"hongze/hongze_open_api/logic"
	"hongze/hongze_open_api/models/request/article"
	"hongze/hongze_open_api/models/response/report"
	celuePushTable "hongze/hongze_open_api/models/tables/article"
	"hongze/hongze_open_api/models/tables/rddp/classify"
	tables "hongze/hongze_open_api/models/tables/report"
	"hongze/hongze_open_api/models/tables/wx_user"
	"hongze/hongze_open_api/utils"
	"net/url"
	"strconv"
	"strings"
	"time"
)

// 报告模块
type ReportController struct {
	BaseAuth
}

// 报告模块
type ReportControllerCommon struct {
	BaseCommon
}

// ListReport
// @Title 获取报告列表接口
// @Description 获取报告列表
// @Param   _page_size   query   int  true       "每页数据条数"
// @Param   _page   query   int  true       "当前页页码，从1开始"
// @Param   report_type   query   string  true       "类型 day：晨报 、week ：周报、two_week：双周报 、month：月报、other ：点评 (默认为day:晨报) "
// @Param   keyword   query   string  true       "搜索关键词"
// @Param   mobile   query   string  true       "用户手机号(加密后的)"
// @Success 200 {object} report.ReportListResp
// @router /list [get]
func (c *ReportController) ListReport() {
	pageSize, _ := c.GetInt("_page_size")
	currentIndex, _ := c.GetInt("_page")
	keyWord := c.GetString("keyword")
	reportType := c.GetString("report_type")
	//mobile := c.GetString("mobile")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	//通过url获取mobile中的参数
	var mobile string
	URL, err := url.Parse(c.Ctx.Input.URI())
	if err != nil {
		c.FailWithMessage("获取报告失败")
		return
	}
	urlParameter := URL.RawQuery
	sliceUrl := strings.Split(urlParameter, "&")
	if len(sliceUrl) > 0 {
		for _, v := range sliceUrl {
			if strings.Contains(v, "mobile=") {
				mobile = strings.Replace(v, "mobile=", "", -1)
			}
		}
	}
	if mobile == "" {
		c.FailWithMessage("mobile 必传")
		return
	}
	mobile, err = url.QueryUnescape(mobile)
	if err != nil {
		c.FailWithMessage("mobile 必传")
		return
	}
	var dateTxt = []byte(mobile)
	resultDe := utils.DesBase64Decrypt(dateTxt)
	deMobile := string(resultDe)
	if deMobile == "" {
		c.FailWithMessage("手机号加密格式错误")
		return
	}
	totalFicc, err := tables.GetUserReportFiccCount(deMobile)
	if err != nil {
		c.FailWithMessage("获取失败")
		return
	}
	if totalFicc < 1 {
		c.FailWithMessage("用户不存在")
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND  enabled = 1 `
	if keyWord != "" {
		condition += ` AND  research_report_name LIKE '%` + keyWord + `%'`
	}
	//day：晨报 、week ：周报、two_week：双周报 、month：月报、other ：点评
	if reportType != "week" && reportType != "two_week" && reportType != "month" && reportType != "other" {
		reportType = "day"
	}
	if reportType != "" {
		condition += ` AND type = ? AND status = 'report' `
		pars = append(pars, reportType)
	}
	total, err := tables.GetReportListCount(condition, pars)
	if err != nil {
		c.FailWithMessage("获取失败")
		return
	}
	list, err := tables.GetReportList(condition, pars, startSize, pageSize)
	if err != nil {
		c.FailWithMessage("获取失败")
		return
	}
	mobile = url.QueryEscape(mobile) //转义 +
	nonceStr := common.GetRandString(10)
	timeUnix := strconv.FormatInt(time.Now().Unix(), 10)
	if len(list) > 0 {
		for k, v := range list {
			postData := make(map[string]string)
			reportId := strconv.Itoa(v.ResearchReportId)
			parameter := "mobile=" + mobile + "&research_report_id=" + reportId + "&nonce_str=" + nonceStr + "&timestamp=" + timeUnix
			postData["mobile"] = mobile
			postData["research_report_id"] = reportId
			postData["appid"] = utils.ReportAppid
			postData["nonce_str"] = nonceStr
			postData["timestamp"] = timeUnix
			sign := utils.GetSign(postData)
			list[k].HttpUrl = utils.ResearchReportUrl + "hzsl/report/detail?" + parameter + "&sign=" + sign
		}
	}
	page := utils.GetPaging(currentIndex, pageSize, total)
	resp := tables.ReportListResp{
		List:   list,
		Paging: page,
	}
	c.OkDetailed(resp, "获取成功")
}

// GetReportInfo
// @Title 获取报告详情
// @Description 获取报告详情
// @Param research_report_id query int true "报告ID"
// @Param   mobile   query   string  true       "用户手机号(加密后的)"
// @Success 200 {object} report.ResearchReportInfo
// @router /getReportInfo [get]
func (c *ReportControllerCommon) GetReportInfo() {
	researchReportId, _ := c.GetInt("research_report_id")
	//mobile := c.GetString("mobile")
	if researchReportId < 1 {
		c.FailWithMessage("请传入报告id")
		return
	}
	mobile := c.GetString("mobile")
	if mobile == "" {
		c.FailWithMessage("mobile 必传")
		return
	}
	var dateTxt = []byte(mobile)
	resultDe := utils.DesBase64Decrypt(dateTxt)
	deMobile := string(resultDe)
	if deMobile == "" {
		c.FailWithMessage("手机号加密格式错误")
		return
	}
	totalFicc, err := tables.GetUserReportFiccCount(deMobile)
	if err != nil {
		c.FailWithMessage("获取失败")
		return
	}
	if totalFicc < 1 {
		c.FailWithMessage("用户不存在")
		return
	}
	userInfo, err := wx_user.GetWxUserByMobileStr(deMobile)
	if err != nil {
		c.FailWithMessage("找不到该用户")
		return
	}
	reportInfo, hasPermission, err := tables.GetResearchReportInfo(researchReportId, userInfo.UserId)
	if err != nil {
		c.FailWithMessage("获取报告失败")
		return
	}
	if !hasPermission {
		c.FailWithMessage("无权限")
		return
	}
	mobile = url.QueryEscape(mobile) //转义 +
	nonceStr := common.GetRandString(10)
	timeUnix := strconv.FormatInt(time.Now().Unix(), 10)
	if len(reportInfo.ResearchReportTypeList) > 1 {
		for k, v := range reportInfo.ResearchReportTypeList {
			postData := make(map[string]string)
			reportId := strconv.Itoa(int(v.ResearchReportTypeId))
			parameter := "mobile=" + mobile + "&ResearchReportTypeId=" + reportId + "&appid=" + utils.ReportAppid + "&nonce_str=" + nonceStr + "&timestamp=" + timeUnix
			postData["mobile"] = mobile
			postData["ResearchReportTypeId"] = reportId
			postData["appid"] = utils.ReportAppid
			postData["nonce_str"] = nonceStr
			postData["timestamp"] = timeUnix
			sign := utils.GetSign(postData)
			reportInfo.ResearchReportTypeList[k].HttpUrl = utils.ResearchReportUrl + "report/?" + parameter + "&sign=" + sign
		}
	}
	c.OkDetailed(reportInfo, "获取成功")
}

// GetResearchReportChapter
// @Title 获取章节详情接口
// @Description 获取章节详情
// @Param ResearchReportTypeId query int true "章节ID"
// @Param   mobile   query   string  false       "用户手机号(加密后的)"
// @Success 200 {object} report.ResearchReportTypeContentInfo
// @router /getReportChapterInfo [get]
func (c *ReportControllerCommon) GetResearchReportChapter() {
	researchReportTypeId, _ := c.GetInt("ResearchReportTypeId")
	//mobile := c.GetString("mobile")
	if researchReportTypeId < 1 {
		c.FailWithMessage("请传入章节id")
		return
	}
	mobile := c.GetString("mobile")
	if mobile == "" {
		c.FailWithMessage("mobile 必传")
		return
	}
	var dateTxt = []byte(mobile)
	resultDe := utils.DesBase64Decrypt(dateTxt)
	deMobile := string(resultDe)
	if deMobile == "" {
		c.FailWithMessage("手机号加密格式错误")
		return
	}
	totalFicc, err := tables.GetUserReportFiccCount(deMobile)
	if err != nil {
		c.FailWithMessage("获取失败")
		return
	}
	if totalFicc < 1 {
		c.FailWithMessage("用户不存在")
		return
	}
	userInfo, err := wx_user.GetWxUserByMobileStr(deMobile)
	if err != nil {
		c.FailWithMessage("找不到该用户")
		return
	}

	reportInfo, hasPermission, err := tables.GetResearchReportTypeContentInfo(uint64(researchReportTypeId), uint64(userInfo.UserId))
	if err != nil {
		c.FailWithMessage("获取报告失败")
		return
	}
	if !hasPermission {
		c.FailWithMessage("无权限")
		return
	}
	c.OkDetailed(reportInfo, "获取成功")
}

// ArticleChange
// @Title 报告变更通知的插入点接口
// @Description 报告变更通知的插入点接口
// @Param	request	body article.CreatArticleCeluePushReq true "type json string"
// @Success 200 创建成功
// @router /article/change [post]
func (c *ReportController) ArticleChange() {

	var req article.CreatArticleCeluePushReq
	err := json.Unmarshal(c.Ctx.Input.RequestBody, &req)
	if err != nil {
		c.FailWithMessage("参数解析异常")
		return
	}
	//appid权限校验
	appid := req.Appid
	if utils.RunMode == "release" && appid != "XVuGlcyEEVNYVWx5" {
		c.FailWithMessage("无权限")
		return
	}
	articleId := req.ArticleId
	action := req.Action
	if articleId < 0 {
		c.FailWithMessage("缺少 article_id 参数")
		return
	}
	if action != "add" && action != "edit" && action != "move" {
		c.FailWithMessage("action参数类型错误")
		return
	}
	item := new(celuePushTable.CygxArticleCeluePush)
	item.ArticleId = articleId
	item.Action = action
	item.CreateTime = time.Now()
	item.ModifyTime = time.Now()
	err = celuePushTable.AddCygxArticleCeluePush(item)
	if err != nil {
		c.OkWithMessage("创建失败")
		return
	}
	c.OkWithMessage("创建成功")
}

// ClassifyList
// @Title 获取报告分类列表接口
// @Description 获取报告分类列表接口
// @Param   _page_size   query   int  true       "每页数据条数"
// @Param   _page   query   int  true       "当前页页码，从1开始"
// @Param   report_type   query   string  true       "类型 day：晨报 、week ：周报、two_week：双周报 、month：月报、other ：点评 (默认为day:晨报) "
// @Param   keyword   query   string  true       "搜索关键词"
// @Param   mobile   query   string  true       "用户手机号(加密后的)"
// @Success 200 {object} classify.ClassifyList
// @router /classify/list [get]
func (c *ReportController) ClassifyList() {
	list, err := classify.GetClassifyList()
	if err != nil {
		c.FailWithMessage("获取分类失败")
		return
	}
	for _, v := range list {
		childList, err := classify.GetClassifyListByParentId(v.Id)
		if err != nil {
			c.FailWithMessage("获取下级分类失败")
			return
		}
		for _, childV := range childList {
			childV.Child = make([]*classify.ClassifyList, 0)
		}
		if len(childList) == 0 {
			tmpClassifyList := *v
			tmpClassifyList.Child = make([]*classify.ClassifyList, 0)
			childList = []*classify.ClassifyList{&tmpClassifyList}
		}
		v.Child = childList
	}
	c.OkDetailed(list, "获取成功")
}

// ListReportV2
// @Title 获取报告列表接口
// @Description 获取报告列表
// @Param   _page_size   query   int  true       "每页数据条数"
// @Param   _page   query   int  true       "当前页页码，从1开始"
// @Param   classify_id   query   int  true       "分类id"
// @Param   keyword   query   string  true       "搜索关键词"
// @Param   mobile   query   string  true       "用户手机号(加密后的)"
// @Success 200 {object} report.ReportListResp
// @router /list/v2 [get]
func (c *ReportController) ListReportV2() {
	pageSize, _ := c.GetInt("_page_size")
	currentIndex, _ := c.GetInt("_page")
	keyword := c.GetString("keyword")
	classifyId, _ := c.GetInt("classify_id")
	//mobile := c.GetString("mobile")
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)
	//通过url获取mobile中的参数
	var mobile string
	URL, err := url.Parse(c.Ctx.Input.URI())
	if err != nil {
		c.FailWithMessage("获取报告失败")
		return
	}
	urlParameter := URL.RawQuery
	sliceUrl := strings.Split(urlParameter, "&")
	if len(sliceUrl) > 0 {
		for _, v := range sliceUrl {
			if strings.Contains(v, "mobile=") {
				mobile = strings.Replace(v, "mobile=", "", -1)
			}
		}
	}
	if mobile == "" {
		c.FailWithMessage("mobile 必传")
		return
	}
	mobile, err = url.QueryUnescape(mobile)
	if err != nil {
		c.FailWithMessage("mobile 必传")
		return
	}
	var dateTxt = []byte(mobile)
	resultDe := utils.DesBase64Decrypt(dateTxt)
	deMobile := string(resultDe)
	if deMobile == "" {
		c.FailWithMessage("手机号加密格式错误")
		return
	}
	if classifyId <= 0 {
		c.FailWithMessage("分类必传")
		return
	}

	total, list, err, errMsg := logic.GetReportList(classifyId, deMobile, keyword, startSize, pageSize)
	if err != nil {
		c.FailWithMessage(errMsg)
		return
	}

	page := utils.GetPaging(currentIndex, pageSize, total)
	resp := report.ReportListResp{
		List:   list,
		Paging: page,
	}
	c.OkDetailed(resp, "获取成功")
}

// GetReportInfoV2
// @Title 获取报告详情
// @Description 获取报告详情
// @Param report_id query int true "报告ID"
// @Param   mobile   query   string  true       "用户手机号(加密后的)"
// @Success 200 {object} report.ReportDetail
// @router /getReportInfo/v2 [get]
func (c *ReportControllerCommon) GetReportInfoV2() {
	reportId, _ := c.GetInt("report_id")
	//mobile := c.GetString("mobile")
	if reportId < 1 {
		c.FailWithMessage("请传入报告id")
		return
	}
	mobile := c.GetString("mobile")
	if mobile == "" {
		c.FailWithMessage("mobile 必传")
		return
	}
	var dateTxt = []byte(mobile)
	resultDe := utils.DesBase64Decrypt(dateTxt)
	deMobile := string(resultDe)
	if deMobile == "" {
		c.FailWithMessage("手机号加密格式错误")
		return
	}
	reportDetail, err, errMsg := logic.GetReportDetail(reportId, deMobile)
	if err != nil {
		//c.FailWithMessage(errMsg)
		c.FailWithMessageErr(errMsg, err.Error())
		return
	}
	c.OkDetailed(reportDetail, "获取成功")
}

// GetResearchReportChapterV2
// @Title 获取章节详情接口
// @Description 获取章节详情
// @Param report_chapter_id query int true "章节ID"
// @Param   mobile   query   string  false       "用户手机号(加密后的)"
// @Success 200 {object} report.ReportChapterDetail
// @router /getReportChapterInfo/v2 [get]
func (c *ReportControllerCommon) GetResearchReportChapterV2() {
	reportChapterId, _ := c.GetInt("report_chapter_id")
	if reportChapterId < 1 {
		c.FailWithMessage("请传入章节id")
		return
	}
	mobile := c.GetString("mobile")
	if mobile == "" {
		c.FailWithMessage("mobile 必传")
		return
	}
	var dateTxt = []byte(mobile)
	resultDe := utils.DesBase64Decrypt(dateTxt)
	deMobile := string(resultDe)
	if deMobile == "" {
		c.FailWithMessage("手机号加密格式错误")
		return
	}

	chapterDetail, err, errMsg := logic.GetChapterDetail(deMobile, reportChapterId)
	if err != nil {
		//c.FailWithMessage(errMsg)
		c.FailWithMessageErr(errMsg, err.Error())
		return
	}
	c.OkDetailed(chapterDetail, "获取成功")
}

// GetTickerData
// @Title 获取报告详情获取指标数据接口
// @Description 获取报告详情获取指标数据接口
// @Param report_chapter_id query int true "章节ID"
// @Success 200 {object} report.TickerData
// @router /getTickerData [get]
func (c *ReportControllerCommon) GetTickerData() {
	reportChapterId, _ := c.GetInt("report_chapter_id")
	if reportChapterId < 1 {
		c.FailWithMessage("请传入章节id")
		return
	}

	tickerData, err, errMsg := logic.GetTickerData(reportChapterId)
	if err != nil {
		//c.FailWithMessage(errMsg)
		c.FailWithMessageErr(errMsg, err.Error())
		return
	}
	c.OkDetailed(tickerData, "获取成功")
}
