package cygx

import (
	"encoding/json"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/utils"
	"strconv"
	"strings"
	"time"
)

// 标的管理
type IndustrialSubjectController struct {
	controllers.BaseAuthController
}

// @Title 添加标的
// @Description 添加标的接口
// @Param	request	body cygx.IndustrialSubjectAdd true "type json string"
// @Success Ret=200 添加标的成功  {object} cygx.NewId
// @router /industrialSubject/add [post]
func (this *IndustrialSubjectController) IndustrialSubjectAdd() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req cygx.IndustrialSubjectAdd
	var pars []interface{}
	var condition string
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	subjectName := req.SubjectName
	source := req.Source
	industrialManagementId := req.IndustrialManagementId
	if subjectName == "" {
		br.Msg = "请输标的名称"
		return
	}
	if source != 2 && source != 3 {
		source = 1
	}
	subjectName = strings.Replace(subjectName, " ", "", -1)
	item := new(cygx.CygxIndustrialSubject)
	var items []*cygx.CygxIndustrialSubject
	item.IndustrialManagementId = req.IndustrialManagementId
	item.SubjectName = subjectName
	item.CreateTime = time.Now()
	item.Source = source
	subjectNameList := strings.Split(subjectName, "{|}")
	if len(subjectNameList) > 1 {
		for _, v := range subjectNameList {
			condition = `AND subject_name = '` + v + `' AND industrial_management_id = ` + strconv.Itoa(req.IndustrialManagementId)
			total, _ := cygx.GetIndustrialSubjectCount(condition, pars)
			if total > 0 {
				br.Msg = "标的已经存在,请重新填写"
				br.ErrMsg = "名称已经存在,请重新填写:" + v
				return
			}
			item := new(cygx.CygxIndustrialSubject)
			item.IndustrialManagementId = req.IndustrialManagementId
			item.SubjectName = v
			item.CreateTime = time.Now()
			item.Source = source
			items = append(items, item)
		}
	} else {
		condition = `AND subject_name = '` + req.SubjectName + `' AND industrial_management_id = ` + strconv.Itoa(req.IndustrialManagementId)
		total, _ := cygx.GetIndustrialSubjectCount(condition, pars)
		if total > 0 {
			br.Msg = "标的已经存在,请重新填写"
			br.ErrMsg = "名称已经存在,请重新填写:" + req.SubjectName
			return
		}
	}
	condition = `AND industrial_management_id = ` + strconv.Itoa(req.IndustrialManagementId)
	totalIndustrialManagement, _ := cygx.GetIndustrialManagementCount(condition, pars)
	if totalIndustrialManagement < 1 {
		br.Msg = "产业名称不存在,请重新填写"
		br.ErrMsg = "产业名称不存在,请重新填写,IndustrialManagementId:" + strconv.Itoa(req.IndustrialManagementId)
		return
	}
	detail, err := cygx.GetIndustrialManagemenDetailById(industrialManagementId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	var newIdStr string
	if len(subjectNameList) > 1 {
		newId, err := cygx.AddIndustrialSubjectList(items)
		if err != nil {
			br.Msg = "新增失败"
			br.ErrMsg = "新增失败 Err:" + err.Error()
			return
		}
		newIdStr = newId
	} else {
		newId, err := cygx.AddIndustrialSubject(item)
		if err != nil {
			br.Msg = "新增失败"
			br.ErrMsg = "新增失败 Err:" + err.Error()
			return
		}
		newIdStr = strconv.Itoa(int(newId))
	}
	resp := new(cygx.NewId)
	resp.NewId = newIdStr
	go cygx.UpdateIndustrialManagementSubjectNames(industrialManagementId, detail.IndustryName)
	br.Ret = 200
	br.Success = true
	br.Data = resp
	br.Msg = "新增成功"
	br.IsAddLog = true
}

// @Title 获取标的列表
// @Description 获取标的列表接口
// @Param   IndustrialManagementId   query   int  true       "分类ID"
// @Success Ret=200  {object} cygx.GetIndustrialSubjectList
// @router /industrialSubject/list [get]
func (this *IndustrialSubjectController) IndustrialSubjectlist() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}
	IndustrialManagementId, _ := this.GetInt("IndustrialManagementId")
	if IndustrialManagementId < 1 {
		br.Msg = "请输入分类ID"
		return
	}
	list, err := cygx.GetIndustrialSubjectAll(IndustrialManagementId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	for k, v := range list {
		if v.ArtNum > 0 {
			list[k].IsRelevance = true
		}
	}
	resp := new(cygx.GetIndustrialSubjectNumList)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 修改
// @Description 修改接口
// @Param	request	body cygx.CygxIndustrialSubject true "type json string"
// @Success Ret=200 修改成功
// @router /industrialSubject/edit [post]
func (this *IndustrialSubjectController) IndustrialSubjectEdit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req cygx.CygxIndustrialSubject
	var pars []interface{}
	var condition string
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.SubjectName == "" {
		br.Msg = "请输入名称"
		return
	}
	//industrialManagementId := req.IndustrialManagementId
	industrialSubjectId := req.IndustrialSubjectId
	condition = `AND industrial_subject_id = ` + strconv.Itoa(industrialSubjectId)
	totalIndustrialSubject, _ := cygx.GetIndustrialSubjectCount(condition, pars)
	if totalIndustrialSubject < 1 {
		br.Msg = "修改失败"
		br.ErrMsg = "修改失败,标的不存在,IndustrialSubjectId:" + strconv.Itoa(industrialSubjectId)
		return
	}
	condition = `AND industrial_management_id = ` + strconv.Itoa(req.IndustrialManagementId)
	detailSubjecj, err := cygx.GetIndustrialSubjectDetailById(industrialSubjectId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}

	detail, err := cygx.GetIndustrialManagemenDetailById(detailSubjecj.IndustrialManagementId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	item := new(cygx.CygxIndustrialSubject)
	item.IndustrialManagementId = req.IndustrialManagementId
	item.SubjectName = req.SubjectName
	item.IndustrialSubjectId = req.IndustrialSubjectId
	err = cygx.EditIndustrialSubject(item)
	if err != nil {
		br.Msg = "修改失败"
		br.ErrMsg = "修改失败 Err:" + err.Error()
		return
	}
	go cygx.UpdateIndustrialManagementSubjectNames(detail.IndustrialManagementId, detail.IndustryName)
	br.Ret = 200
	br.Success = true
	br.Msg = "修改成功"
	br.IsAddLog = true
}

// @Title 删除标的
// @Description 删除标的接口
// @Param   IndustrialSubjectId   query   int  true       "标的ID"
// @Success Ret=200   {object} cygx.NewId
// @router /industrialSubject/delete [post]
func (this *IndustrialSubjectController) IndustrialSubjectDelete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}
	var req cygx.IndustrialSubjectDelete
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	industrialSubjectId := req.IndustrialSubjectId
	if industrialSubjectId < 1 {
		br.Msg = "请输入标的ID"
		return
	}
	count, _ := cygx.GetIndustrialSubjectGroupArtCount(industrialSubjectId)
	if count > 0 {
		br.Ret = 460
		br.Msg = "当前标的下有关联报告,请将相关报告归类后再删除"
		return
	}
	detailSubjecj, err := cygx.GetIndustrialSubjectDetailById(industrialSubjectId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	detailIndustrialManagemen, err := cygx.GetIndustrialManagemenDetailById(detailSubjecj.IndustrialManagementId)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	err = cygx.DeleteIndustrialSubject(industrialSubjectId)
	if err != nil {
		br.Msg = "删除信息失败"
		br.ErrMsg = "删除信息失败,Err:" + err.Error()
		return
	}
	go cygx.UpdateIndustrialManagementSubjectNames(detailIndustrialManagemen.IndustrialManagementId, detailIndustrialManagemen.IndustryName)
	br.Ret = 200
	br.Success = true
	br.Msg = "删除成功"
	br.IsAddLog = true
}

// @Title 通过多个产业获取标的列表
// @Description 通过多个产业获取标的列表接口
// @Param   IndustrialManagementIdStr   query   string  true       "分类ID,多个使用 ,隔开列如 1,3,5"
// @Param   ArticleId   int   string  false       "文章ID"
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Success Ret=200  {object} cygx.GetIndustrialSubjectList
// @router /industrialSubject/listIds [get]
func (this *IndustrialSubjectController) IndustrialSubjectlistIds() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}
	industrialManagementIdStr := this.GetString("IndustrialManagementIdStr")
	keyWord := this.GetString("KeyWord")
	articleId, _ := this.GetInt("ArticleId")
	if industrialManagementIdStr == "" {
		br.Msg = "请输入分类ID"
		return
	}
	var industrialMap = make(map[int]string)

	var condition string
	if keyWord != "" {
		condition += ` AND (sub.subject_name LIKE '%` + keyWord + `%' )  `
	}
	if industrialManagementIdStr != "" {
		condition += ` AND sub.industrial_management_id IN (` + industrialManagementIdStr + `) `
	}
	list, err := cygx.GetIndustrialSubjectAllByIds(condition)
	if err != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取品种信息失败,Err:" + err.Error()
		return
	}
	for k, v := range list {
		if v.ArtNum > 0 {
			list[k].IsRelevance = true
		}
		industrialMap[v.IndustrialSubjectId] = v.SubjectName
	}
	if articleId > 0 {
		subjectList, err := cygx.GetSubjectArticleGroupManagementList(articleId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取信息失败"
			br.ErrMsg = "获取活动关联的标的列表信息失败,Err:" + err.Error() + "activityId:" + strconv.Itoa(articleId)
			return
		}
		for _, v := range subjectList {
			if industrialMap[v.IndustrialSubjectId] == "" {
				item := new(cygx.CygxIndustrialSubjectNum)
				item.IndustrialSubjectId = v.IndustrialSubjectId
				item.SubjectName = v.SubjectName
				list = append(list, item)
			}
		}
	}
	resp := new(cygx.GetIndustrialSubjectNumList)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 获取关联标的列表
// @Description 获取关联标的列表接口
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Success Ret=200  {object} cygx.ArtGroupIndustrialSubjectRepList
// @router /industrialSubject/listByName [get]
func (this *IndustrialSubjectController) IndustrialSubjectByName() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}
	var condition string
	var conditionKeyWord string
	keyWord := this.GetString("KeyWord")
	if keyWord != "" {
		keyWord = strings.Replace(keyWord, "'", "", -1)
		keyWord = strings.Replace(keyWord, "%", "", -1)
		condition = ` AND s.subject_name LIKE '%` + keyWord + `%'  `
	} else {
		condition = ` AND industrial_subject_id = 0 `
	}
	listSubject, err := cygx.GetIndustrialSubjectListName(condition)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	for _, v := range listSubject {
		conditionKeyWord += "'" + v.SubjectName + "',"
	}
	if conditionKeyWord != "" {
		conditionKeyWord = strings.TrimRight(conditionKeyWord, ",")
		conditionKeyWord = ` AND  industry_map_name NOT IN ( ` + conditionKeyWord + `)`
	}
	if keyWord != "" {
		condition = ` AND industry_map_name LIKE '%` + keyWord + `%'  AND  level = 5 ` + conditionKeyWord
	} else {
		condition = ` AND industry_map_id = 0 `
	}
	listMap, err := cygx.GetIndustrialMapListName(condition)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	resp := new(cygx.ArtGroupIndustrialSubjectRepList)
	for _, v := range listMap {
		item := new(cygx.ArtGroupIndustrialSubjectRep)
		item.SubjectName = v.IndustryMapName
		listSubject = append(listSubject, item)
	}
	resp.List = listSubject
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 通过行业获取关联标的列表
// @Description 通过行业获取关联标的列表接口
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Param   ChartPermissionId   query   int  true       "分类ID"
// @Success Ret=200  {object} cygx.CygxIndustrialSubjectList
// @router /industrialSubject/search [get]
func (this *IndustrialSubjectController) IndustrialSubjectSearch() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}
	var condition string
	keyWord := this.GetString("KeyWord")
	chartPermissionId, _ := this.GetInt("ChartPermissionId")
	if keyWord != "" {
		condition = ` AND s.subject_name LIKE '%` + keyWord + `%'  `
	}
	if chartPermissionId > 0 {
		condition += ` AND m.chart_permission_id = ` + strconv.Itoa(chartPermissionId)
	}

	listSubject, err := cygx.GetIndustrialSubjectListNameByChartId(condition)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	resp := new(cygx.CygxIndustrialSubjectList)
	resp.List = listSubject
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 获取标的关联产业详情
// @Description 获取标的关联产业详情接口
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Success Ret=200  {object} cygx.IndustrialNameListRep
// @router /industrialSubject/searchInfo [get]
func (this *IndustrialSubjectController) SearchInfo() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}
	var nameList []*cygx.SubjectNameListRep
	var condition string
	keyWord := this.GetString("KeyWord")
	if keyWord != "" {
		condition = ` AND subject_name ='` + keyWord + `'  `
	} else {
		br.Msg = "请输入搜索内容"
		return
	}
	listSubject, err := cygx.GetIndustrialSubjectListNameByName(condition)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败,Err:" + err.Error()
		return
	}
	if len(listSubject) > 0 {
		mapIndustrial := make(map[int]string)
		mapIndustrialName := make(map[string]string)
		mapSubjectName := make(map[string]string)
		listIndustrial, err := cygx.GetIndustrialManagement("")
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,Err:" + err.Error()
			return
		}
		listSubjectAll, err := cygx.GetIndustrialSubjectListNameByName("")
		if err != nil {
			br.Msg = "获取失败"
			br.ErrMsg = "获取失败,Err:" + err.Error()
			return
		}
		for _, v := range listIndustrial {
			if v.IndustryName != "" {
				mapIndustrial[v.IndustrialManagementId] = v.IndustryName
			}
		}
		for _, v := range listSubject {
			item := new(cygx.SubjectNameListRep)
			if mapIndustrial[v.IndustrialManagementId] != "" {
				if mapIndustrialName[mapIndustrial[v.IndustrialManagementId]] == "" {
					item.Name = mapIndustrial[v.IndustrialManagementId]
					for _, v2 := range listSubjectAll {
						itemV2 := new(cygx.SubjectNameRep)
						if v2.IndustrialManagementId == v.IndustrialManagementId {
							if mapSubjectName[v2.SubjectName+mapIndustrial[v.IndustrialManagementId]] == "" {
								itemV2.Name = v2.SubjectName
								item.List = append(item.List, itemV2)
								mapSubjectName[v2.SubjectName+mapIndustrial[v.IndustrialManagementId]] = v2.SubjectName
							}
						}
					}
					nameList = append(nameList, item)
				}
				mapIndustrialName[mapIndustrial[v.IndustrialManagementId]] = mapIndustrial[v.IndustrialManagementId]
			}
		}
	}
	resp := new(cygx.IndustrialNameListRep)
	resp.List = nameList
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 标的关联的报告活动数量详情
// @Description 标的关联的报告活动数量详情
// @Param   SubjectId   query   string  true       "标的ID"
// @Success Ret=200  {object} cygx.IndustrySubjectCountDetail
// @router /industrialSubject/countDetail [get]
func (this *IndustrialSubjectController) CountDetail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}
	subjectId, _ := this.GetInt("SubjectId")
	if subjectId < 1 {
		br.Msg = "参数有误"
		return
	}

	resp := new(cygx.IndustrySubjectCountDetail)
	// 文章数量统计
	artCountList, e := cygx.GetIndustrySubjectArtTypeCountList(subjectId)
	if e != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取标的关联的报告数失败, Err: " + e.Error()
		return
	}
	totalNum := 0
	for i := range artCountList {
		totalNum += artCountList[i].ArtNum
	}
	// 活动数量统计-细分活动类型为"弘则活动"和"研选活动"
	actCountList, e := cygx.GetIndustrySubjectActCountGroupByType(subjectId)
	if e != nil {
		br.Msg = "获取信息失败"
		br.ErrMsg = "获取标的关联的活动数失败, Err: " + e.Error()
		return
	}
	hzCount := new(cygx.IndustrySubjectArtTypeCountList)
	hzCount.MatchTypeName = utils.CYGX_ACTIVITY_TYPE_NAME_HZ
	yxCount := new(cygx.IndustrySubjectArtTypeCountList)
	yxCount.MatchTypeName = utils.CYGX_ACTIVITY_TYPE_NAME_YX
	for i := range actCountList {
		if actCountList[i].ActivityType == utils.CYGX_ACTIVITY_TYPE_NAME_HZ {
			hzCount.ArtNum = actCountList[i].ActivityCount
		}
		if actCountList[i].ActivityType == utils.CYGX_ACTIVITY_TYPE_NAME_YX {
			yxCount.ArtNum = actCountList[i].ActivityCount
		}
	}
	artCountList = append(artCountList, hzCount, yxCount)

	resp.ArtTotalNum = totalNum
	resp.List = artCountList
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}