package services

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

func AddCygxTagHistory(user *models.WxUserItem, tagId int) (err error) {
	if user.UserId == 0 {
		return
	}
	defer func() {
		if err != nil {
			go utils.SendAlarmMsg("tag点击信息记录失败"+err.Error()+"tagId"+strconv.Itoa(tagId)+"userId："+strconv.Itoa(user.UserId), 2)
		}
	}()
	historyRecord := new(models.CygxTagHistory)
	historyRecord.UserId = user.UserId
	historyRecord.TagId = tagId
	historyRecord.CreateTime = time.Now()
	historyRecord.Mobile = user.Mobile
	historyRecord.Email = user.Email
	historyRecord.CompanyId = user.CompanyId
	historyRecord.CompanyName = user.CompanyName
	historyRecord.RegisterPlatform = utils.REGISTER_PLATFORM
	sellerItem, err := models.GetSellerByCompanyIdCheckFicc(user.CompanyId, 2)
	if err != nil && err.Error() != utils.ErrNoRow() {
		return
	}
	historyRecord.RealName = user.RealName
	if sellerItem != nil {
		historyRecord.SellerName = sellerItem.RealName
	}
	_, err = models.AddCygxTagHistory(historyRecord)
	return
}

//func init() {
//	conditionInit, err := GetConditionInitByTagIds("20,21,26")
//	fmt.Println(err)
//	fmt.Println()
//	fmt.Println(conditionInit)
//}

func GetConditionInitByTagIds(tagIds string, chartPermissionId int) (conditionInit string, err error) {
	if tagIds == "" {
		return
	}
	var condition string
	var pars []interface{}
	var searchTag, industries, subjectNames []string
	tagslice := strings.Split(tagIds, ",")
	condition = ` AND tag_id IN (` + utils.GetOrmInReplace(len(tagslice)) + `)`
	pars = append(pars, tagslice)
	listTag, e := models.GetCygxTagListCondition(condition, pars, 0, 0)
	if e != nil {
		err = errors.New("GetCygxTagListCondition, Err: " + e.Error())
		return
	}

	var tagType int // 定义特殊标签的类型，判断传过来的参数是否有固定标签的搜索
	var tagName string
	for _, tagInfo := range listTag {
		//ActivityTypes 与 ArticleTypes 进行合并
		if tagInfo.ActivityTypes != "" {
			sliceObj := strings.Split(tagInfo.ActivityTypes, ",")
			for _, v := range sliceObj {
				searchTag = append(searchTag, v)
			}
		}
		if tagInfo.ArticleTypes != "" {
			sliceObj := strings.Split(tagInfo.ArticleTypes, ",")
			for _, v := range sliceObj {
				searchTag = append(searchTag, v)
			}
		}
		if tagInfo.Industries != "" {
			sliceObj := strings.Split(tagInfo.Industries, ",")
			for _, v := range sliceObj {
				industries = append(industries, v)
			}
			//industries = append(industries, tagInfo.Industries)
		}
		if tagInfo.SubjectNames != "" {
			sliceObj := strings.Split(tagInfo.SubjectNames, ",")
			for _, v := range sliceObj {
				subjectNames = append(subjectNames, v)
			}
			//subjectNames = append(subjectNames, tagInfo.SubjectNames)
		}

		if tagType == 0 && tagInfo.TagType > 0 {
			tagType = tagInfo.TagType
		}
		tagName = tagInfo.TagName
	}

	switch tagType {
	case 0: // 无固定标签
		//拼接search_tag 搜索内容
		if len(searchTag) > 0 {
			//search_tag_two 兼容报告类型一对多的这种，时间不够，产品也有可能变先这么做
			conditionInit += " AND ( search_tag IN  ('" + strings.Join(searchTag, "','") + "')  OR search_tag_two IN( '" + strings.Join(searchTag, "','") + "' )  )"
		}

		var resourceDataIds []int //cygx_resource_data 主键ID
		//如果产业有组合，那么就去捞产业相关的内容
		if len(industries) > 0 {
			var conditionIndustry string
			var parsIndustry []interface{}
			conditionIndustry += " AND industry_name IN  ('" + strings.Join(industries, "','") + "')"
			listIndustry, e := models.GetTopOneMonthArtReadNumIndustryAll(conditionIndustry, parsIndustry)
			if e != nil {
				err = errors.New("GetTopOneMonthArtReadNumIndustryAll, Err: " + e.Error())
				return
			}
			var industrialManagementIds []int // 产业ID合集
			for _, v := range listIndustry {
				industrialManagementIds = append(industrialManagementIds, v.IndustrialManagementId)
			}

			var conditionIndustryResource string
			var parsIndustryResource []interface{}
			lenArrindustrial := len(industrialManagementIds)
			conditionIndustryResource = ` AND industrial_management_id IN (` + utils.GetOrmInReplace(lenArrindustrial) + `)`
			parsIndustryResource = append(parsIndustryResource, industrialManagementIds)

			if lenArrindustrial > 0 {
				listResourceDataIndustrial, e := models.GetCygxResourceDataIndustrialGroupManagementList(conditionIndustryResource, parsIndustryResource, 0, 0)
				//return
				if e != nil {
					err = errors.New("GetCygxResourceDataIndustrialGroupManagementList, Err: " + e.Error())
					return
				}
				for _, v := range listResourceDataIndustrial {
					resourceDataIds = append(resourceDataIds, v.ResourceDataId)
				}
			}
		}
		//return
		//如果标的有组合，那么就去捞标的相关的内容
		if len(subjectNames) > 0 {
			var conditionsubject string
			var parssubject []interface{}
			conditionsubject += " AND subject_name IN  ('" + strings.Join(subjectNames, "','") + "')"
			listsubject, e := models.GetCygxIndustrialSubjectListCondition(conditionsubject, parssubject)
			if e != nil {
				err = errors.New("GetTopOneMonthArtReadNumIndustry, Err: " + e.Error())
				return
			}
			var industrialsubjectIds []int // 标的ID集合
			for _, v := range listsubject {
				industrialsubjectIds = append(industrialsubjectIds, v.IndustrialSubjectId)
			}
			var conditionsubjectResource string
			var parssubjectResource []interface{}
			lenArrsubject := len(industrialsubjectIds)
			conditionsubjectResource = ` AND industrial_subject_id IN (` + utils.GetOrmInReplace(lenArrsubject) + `)`
			parssubjectResource = append(parssubjectResource, industrialsubjectIds)
			if lenArrsubject > 0 {
				listResourceDatasubject, e := models.GetCygxResourceDataIndustrialGroupSubjectList(conditionsubjectResource, parssubjectResource, 0, 0)
				if e != nil {
					err = errors.New("GetCygxResourceDataIndustrialGroupSubjectList, Err: " + e.Error())
					return
				}
				for _, v := range listResourceDatasubject {
					resourceDataIds = append(resourceDataIds, v.ResourceDataId)
				}
			}
		}

		//拼接 cygx_resource_data 表主键查询ID
		if len(resourceDataIds) > 0 {
			var resourceDataIdStrs []string
			resourceDataIdMap := make(map[int]bool)
			for _, v := range resourceDataIds {
				if resourceDataIdMap[v] {
					continue
				}
				resourceDataIdStrs = append(resourceDataIdStrs, strconv.Itoa(v))
				resourceDataIdMap[v] = true
			}
			conditionInit += " AND id IN  (" + strings.Join(resourceDataIdStrs, ",") + ")   "
		}

		var tagNames = []string{"纪要", "深度", "概览", "点评"}
		if utils.InArrayByStr(tagNames, tagName) { //如果是这个四个类型的标签搜索单独针对FICC研报的周期行业进行筛选
			conditionInit += " OR (  tag_name IN ('" + tagName + "')   AND  chart_permission_id =   " + strconv.Itoa(chartPermissionId) + ")  "
		}
	case 1: // 热门活动
		conf, e := models.GetConfigByCode(utils.CYGX_TAG_HOT_ACTIVITY_ID)
		if e != nil {
			err = errors.New("GetConfigByCode, Err: " + e.Error())
			return
		}
		//主键ID赋值为0，进行空查询
		if conf.ConfigValue == "" {
			conditionInit += " AND id = 0  "
			return
		}
		pars = make([]interface{}, 0)
		condition = " AND activity_id IN ( " + conf.ConfigValue + ")  AND publish_status = 1   AND active_state  IN (1,2) "
		listActivity, e := models.GetActivityListByCondition(condition, pars)
		if e != nil {
			err = errors.New("GetActivityListByCondition, Err: " + e.Error())
			return
		}
		if len(listActivity) == 0 {
			conditionInit += " AND id = 0  "
			return
		}

		//拼接查询热门活动的SQL、
		var activityIds []string
		for _, v := range listActivity {
			activityIds = append(activityIds, strconv.Itoa(v.ActivityId))
		}
		conditionInit = " AND source_id IN ( " + strings.Join(activityIds, ",") + ")  AND source = '" + utils.CYGX_OBJ_ACTIVITY + "'"

	case 2: //海外研究 查询海外研究的文章，以及海外的活动
		condition = " AND category_id IN ( SELECT category_id_celue FROM cygx_report_mapping_group WHERE id_cygx IN ( 35,39 ) ) AND publish_status = 1"
		pars = make([]interface{}, 0)
		articleList, e := models.GetArticleList(condition, pars)
		if e != nil {
			err = errors.New("GetArticleList, Err: " + e.Error())
			return
		}
		//文章一定会有值，这里就不做为空判断了 。。。
		var articleIds []string
		for _, v := range articleList {
			articleIds = append(articleIds, strconv.Itoa(v.ArticleId))
		}

		//海外举办的活动查询
		condition = " AND  area_type = 2  AND publish_status = 1   "
		listActivity, e := models.GetActivityListByCondition(condition, pars)
		if e != nil {
			err = errors.New("GetActivityListByCondition, Err: " + e.Error())
			return
		}
		//判断是否有海外活动，如果有就拼接，报告与活动的查询SQL
		if len(listActivity) == 0 {
			conditionInit = " AND source_id IN ( " + strings.Join(articleIds, ",") + ")  AND source = '" + utils.CYGX_OBJ_ARTICLE + "'"
		} else {
			var activityIds []string
			for _, v := range listActivity {
				activityIds = append(activityIds, strconv.Itoa(v.ActivityId))
			}
			var conditionchartInit string
			//行业筛选
			if chartPermissionId > 0 {
				conditionchartInit += " AND chart_permission_id  =  " + strconv.Itoa(chartPermissionId)
			}
			conditionInit = " AND  ( source_id IN ( " + strings.Join(articleIds, ",") + ") " + conditionchartInit + "  AND source = '" + utils.CYGX_OBJ_ARTICLE + "') OR   (source_id IN ( " + strings.Join(activityIds, ",") + ") " + conditionchartInit + "   AND source = '" + utils.CYGX_OBJ_ACTIVITY + " ' )"
		}

	case 3: // 路演回放
		conditionInit = "  AND source  IN('activityvoice','activityvideo')  AND  search_tag = '路演回放' "

	case 4: // 语音问答
		conditionInit = "   AND source = '" + utils.CYGX_OBJ_ASKSERIEVIDEO + "'"

	case 5: //固定标签【跟踪】，包含以下系列：医药-趋势观察 ，科技-产业跟踪 ，智造-产业跟踪 ，消费-月度调研 ，周期-（周度观点,产业跟踪），策略-（每日复盘），固收-（债市复盘）
		condition = `   AND category_name IN ( '医药行业', '智造行业', '消费行业', '科技行业', '周期', '策略思考', '固收研究' )  
						AND IF  ( category_name IN ( '医药行业' ), sub_category_name IN ( '趋势观察' ), 1 = 1 ) 
						AND IF	( category_name IN ( '科技行业' ), sub_category_name IN ( '产业跟踪' ), 1 = 1 ) 
						AND IF	( category_name IN ( '智造行业' ), sub_category_name IN ( '产业跟踪' ), 1 = 1 ) 
						AND IF	( category_name IN ( '消费行业' ), sub_category_name IN ( '月度调研' ,'产业跟踪' ), 1 = 1 ) 
						AND IF	( category_name IN ( '策略思考' ), sub_category_name IN ( '每日复盘' ), 1 = 1 ) 
						AND IF	( category_name IN ( '固收研究' ), sub_category_name IN ( '债市复盘' ), 1 = 1 ) 
						AND IF	( category_name IN ( '周期' ), sub_category_name IN ( '周度观点', '产业跟踪' ), 1 = 1 ) AND publish_status = 1 `
		pars = make([]interface{}, 0)
		articleList, e := models.GetArticleListHomeTag(condition, pars)
		if e != nil {
			err = errors.New("GetArticleList, Err: " + e.Error())
			return
		}
		//文章一定会有值，这里就不做为空判断了 。。。
		var articleIds []string
		for _, v := range articleList {
			articleIds = append(articleIds, strconv.Itoa(v.ArticleId))
		}
		conditionInit = " AND source IN ('article','ficcreport')  AND  IF (  source = 'article'  , source_id IN ( " + strings.Join(articleIds, ",") + ")  ,1=1 )  AND IF   ( source =  'ficcreport' , tag_name IN ('跟踪')  ,1=1 )  "
	}

	return
}
