package cygx

import (
	"encoding/json"
	"github.com/rdlucklib/rdluck_tools/paging"
	"github.com/tealeg/xlsx"
	"hongze/hz_crm_api/controllers"
	"hongze/hz_crm_api/models"
	"hongze/hz_crm_api/models/cygx"
	"hongze/hz_crm_api/models/data_manage/request"
	cygxService "hongze/hz_crm_api/services/cygx"
	"hongze/hz_crm_api/utils"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// 标签管理
type TagManagementController struct {
	controllers.BaseAuthController
}

// @Title 获取标签列表
// @Description 获取标签列表接口
// @Param   CurrentIndex   query   int  true       "当前页码"
// @Param   PageSize   query   int  true       "每页数据数"
// @Param   Status   query   string  false       "发布状态，1，上线，0下线"
// @Param   SortParam   query   string  false       "排序字段参数，用来排序的字段， 枚举值： 'pv':总Pv/Uv "
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @Success 200 {object} cygx.ChartPermissionResp
// @router /tag/list [get]
func (this *TagManagementController) TagList() {
	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
	}
	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	status, _ := this.GetInt("Status", 1)
	//排序参数
	sortParam := this.GetString("SortParam")
	sortType := this.GetString("SortType")

	var condition string
	var startSize int
	if pageSize <= 0 {
		pageSize = utils.PageSize20
	}
	if currentIndex <= 0 {
		currentIndex = 1
	}
	startSize = utils.StartIndex(currentIndex, pageSize)

	if status == 1 {
		condition += ` AND status=1 `
	} else {
		condition += ` AND status=0  `
	}

	total, err := cygx.GetCygxTagListCount(condition)
	if err != nil {
		br.Msg = "获取标签总数失败"
		br.ErrMsg = "获取标签总数失败,Err:" + err.Error()
		return
	}
	page := paging.GetPaging(currentIndex, pageSize, total)

	//排序字段以及排序方式处理
	var sortStr string
	if sortParam != "" && sortType != "" {
		if sortParam == "pv" {
			if sortType == "asc" {
				sortStr = " ORDER BY pv ASC,  online_time DESC "
			} else {
				sortStr = " ORDER BY pv  DESC,  online_time DESC "
			}
		}
	} else {
		sortStr = "  ORDER BY online_time DESC "
	}
	condition += sortStr
	list, err := cygx.GetCygxTagListPage(condition, startSize, pageSize)
	if err != nil {
		br.Msg = "获取标签失败"
		br.ErrMsg = "获取标签信息失败,Err:" + err.Error()
		return
	}

	var resp request.TagListResp
	resp.Paging = page
	resp.List = list

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

// @Title 获取标签列表-自定义顺序
// @Description 获取标签列表-自定义顺序接口
// @Param   SearchType   query   string  false       "搜索类型 1:自定义标签 、 2：固定标签 ，-1查询所有 默认-1"
// @Success 200 {object} cygx.ChartPermissionResp
// @router /tag/list/custom [get]
func (this *TagManagementController) TagCustomizeList() {
	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
	}
	searchType, _ := this.GetInt("SearchType", -1)
	var condition string
	if searchType == 1 {
		condition = " AND  tag_type = 0 "
	}
	if searchType == 2 {
		condition = " AND  tag_type > 0 "
	}
	list, err := cygx.GetCygxTagList(condition)
	if err != nil {
		br.Msg = "获取标签失败"
		br.ErrMsg = "获取标签信息失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// @Title 撤下或上线标签
// @Description 撤下或上线标签接口
// @Param   Status   query   string  false       "状态，1，上线，0下线"
// @Param   TagId   query   int  false       "标签id"
// @Success 200 {object} cygx.ChartPermissionResp
// @router /tag/enable [get]
func (this *TagManagementController) TagEnable() {
	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
	}

	status, _ := this.GetInt("Status", 1)
	tagId, _ := this.GetInt("TagId")

	if tagId < 1 {
		br.Msg = "标签不存在"
		return
	}
	err := cygx.UpdateCygxTagStatus(tagId, status)
	if err != nil {
		br.Msg = "上下线标签失败"
		br.ErrMsg = "上下线标签失败,Err:" + err.Error()
		return
	}

	if status == 1 {
		br.Msg = "上线成功"
	} else {
		br.Msg = "撤下成功"
	}
	br.Ret = 200
	br.Success = true
}

// MoveTag
// @Title 移动标签
// @Description 移动标签接口
// @Success 200 {object} data_manage.MoveBaseFromBaiinfoReq
// @router /tag/move [post]
func (this *TagManagementController) MoveTag() {
	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 request.MoveTagReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.TagId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "标签id小于等于0"
		br.IsSendEmail = false
		return
	}

	err, errMsg := cygxService.MoveCygxTag(req.TagId, req.PrevTagId, req.NextTagId)
	if errMsg != `` {
		br.Msg = errMsg
		br.ErrMsg = errMsg
		if err != nil {
			br.ErrMsg = err.Error()
		} else {
			br.IsSendEmail = false
		}
		return
	}
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "移动成功"
}

// SubCategoryNameList
// @Title 搜索所有的报告系列
// @Description 搜索所有的报告系列接口
// @Success 200 {object} data_manage.MoveBaseFromBaiinfoReq
// @router /tag/subCategoryName/list [get]
func (this *TagManagementController) SubCategoryNameList() {
	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
	}

	keyword := this.GetString("KeyWord")

	list, err := cygx.GetMatchTypeNameByKeyword(keyword)
	if err != nil {
		br.Msg = "获取标签失败"
		br.ErrMsg = "获取标签信息失败,Err:" + err.Error()
		return
	}
	//todo 严选沙龙+精华

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// @Title 获取关联产业列表
// @Description 获取关联产业列表接口
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Success Ret=200  {object} cygx.GetCygxIndustrialManagementList
// @router /tag/industrialManagement/listByName [get]
func (this *TagManagementController) IndustrialManagementlistByName() {
	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")
	if keyWord != "" {
		condition = ` AND industry_name LIKE '%` + keyWord + `%'  `
	} else {
		condition = ` AND industrial_management_id = 0 `
	}
	listIndustrial, err := cygx.GetIndustrialManagement(condition)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	resp := new(cygx.GetCygxIndustrialManagementList)
	resp.List = listIndustrial
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 新增标签
// @Description 新增标签接口
// @Success Ret=200  {object} cygx.GetCygxIndustrialManagementList
// @router /tag/save [post]
func (this *TagManagementController) TagSave() {
	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 request.SaveTagReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	if req.TagName == "" {
		br.Msg = "参数错误"
		br.ErrMsg = "标签名为空"
		return
	}

	tagName := req.TagName
	tagId := req.TagId
	var condition string
	var pars []interface{}
	condition = " AND tag_name = ? AND tag_id != ?  "
	pars = append(pars, tagName, tagId)
	total, err := cygx.GetCygxTagListCountByCondition(condition, pars)
	if err != nil {
		br.Msg = "编辑标签失败"
		br.ErrMsg = "获取标签总数失败,Err:" + err.Error()
		return
	}
	if total > 0 {
		br.Msg = "标签名称已存在"
		br.ErrMsg = "标签名称已存在,TagName:" + tagName
		return
	}
	if req.TagId > 0 {
		item := cygx.CygxTag{
			TagId:         int64(req.TagId),
			TagName:       req.TagName,
			ArticleTypes:  req.ArticleTypes,
			ActivityTypes: req.ActivityTypes,
			Industries:    req.Industries,
			SubjectNames:  req.SubjectNames,
			ModifyTime:    time.Now(),
		}
		detail, err := cygx.GetCygxTagInfoById(req.TagId)
		if err != nil {
			br.Msg = "编辑标签失败！"
			br.ErrMsg = "编辑标签失败，Err:" + err.Error()
			return
		}

		if detail.TagType > 0 {
			br.Msg = "固定标签无法编辑！"
			return
		}
		err = item.Update([]string{"TagName", "ArticleTypes", "ActivityTypes", "Industries", "SubjectNames", "ModifyTime"})
		if err != nil {
			br.Msg = "编辑标签失败！"
			br.ErrMsg = "编辑标签失败，Err:" + err.Error()
			return
		}
	} else {
		item := cygx.CygxTag{
			TagName:       req.TagName,
			ArticleTypes:  req.ArticleTypes,
			ActivityTypes: req.ActivityTypes,
			Industries:    req.Industries,
			SubjectNames:  req.SubjectNames,
			ModifyTime:    time.Now(),
			CreateTime:    time.Now(),
			OnlineTime:    time.Now(),
			Status:        1,
		}

		maxSort, err := cygx.GetCygxTagMaxSort()
		if err != nil {
			br.Msg = "查询最大排序失败"
			br.ErrMsg = "查询最大排序失败" + err.Error()
			return
		}
		item.Sort = maxSort + 1

		_, err = cygx.AddCygxTag(&item)
		if err != nil {
			br.Msg = "新增标签失败！"
			br.ErrMsg = "新增标签失败，Err:" + err.Error()
			return
		}
	}

	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "操作成功"
}

// @Title  下载PV
// @Description 下载PV接口
// @Param   TagId   query   int  true       "TagId"
// @router /tag/PvExport [get]
func (this *TagManagementController) PvExport() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	AdminUser := this.SysUser
	if AdminUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，用户信息为空"
		br.Ret = 408
		return
	}
	tagId, _ := this.GetInt("TagId")
	if tagId < 1 {
		br.Msg = "请输入标签ID"
		return
	}
	var condition string
	var pars []interface{}
	condition = ` AND tag_id = ? AND  company_id != 16  `
	pars = append(pars, tagId)
	var respList []*cygx.CygxTagHistory
	//respList := new(cygx.CygxTacticsTimeLineHistory)
	list, err := cygx.GetCygxTagHistoryList(condition, pars)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	//超级管理员和权益管理员、权益研究员可以下载所有客户，销售组长能下载本组客户，销售只能下载本人名下客户
	//resp := new(cygx.CanDownload)
	//adminInfo, errAdmin := system.GetSysUserById(AdminUser.AdminId)
	//if errAdmin != nil {
	//	br.Msg = "获取失败"
	//	br.ErrMsg = "获取失败，Err:" + errAdmin.Error()
	//	return
	//}
	//if adminInfo.Role == "admin" || adminInfo.Role == "researcher" {
	//	resp.IsCanDownload = true
	//}
	////销售查看自己客户，销售组长查看组员
	//if resp.IsCanDownload == false {
	//	mapMobile, err := cygxService.GetAdminLookUserMobile(adminInfo)
	//	if err != nil {
	//		br.Msg = "获取失败"
	//		br.ErrMsg = "获取失败,销售对应权限，Err:" + err.Error()
	//		return
	//	}
	//	for _, v := range list {
	//		if _, ok := mapMobile[v.Mobile]; ok {
	//			respList = append(respList, v)
	//		}
	//	}
	//} else {
	//	respList = list
	//}
	respList = list
	//创建excel
	dir, err := os.Executable()
	exPath := filepath.Dir(dir)
	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	if err != nil {
		br.Msg = "生成文件失败"
		br.ErrMsg = "生成文件失败"
		return
	}
	style := xlsx.NewStyle()
	alignment := xlsx.Alignment{
		Horizontal: "center",
		Vertical:   "center",
		WrapText:   true,
	}
	style.Alignment = alignment
	style.ApplyAlignment = true
	sheet, err := xlsxFile.AddSheet("阅读明细")
	if err != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
		return
	}
	rowTitle := sheet.AddRow()
	cellA := rowTitle.AddCell()
	cellA.Value = "姓名"
	cellB := rowTitle.AddCell()
	cellB.Value = "手机号"
	cellC := rowTitle.AddCell()
	cellC.Value = "公司名称"
	cellD := rowTitle.AddCell()
	cellD.Value = "所属权益销售"
	cellE := rowTitle.AddCell()
	cellE.Value = "点击时间"
	cellF := rowTitle.AddCell()
	cellF.Value = "来源"

	for _, item := range respList {
		row := sheet.AddRow()
		cellA := row.AddCell()
		cellA.Value = item.RealName
		cellB := row.AddCell()
		cellB.Value = item.Mobile
		cellC := row.AddCell()
		cellC.Value = item.CompanyName
		cellD := row.AddCell()
		cellD.Value = item.SellerName
		cellE := row.AddCell()
		cellE.Value = item.CreateTime.Format(utils.FormatDateTime)

		cellF := row.AddCell()
		if item.RegisterPlatform == 1 {
			cellF.Value = "小程序"
		} else {
			cellF.Value = "网页版"
		}
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		br.Msg = "保存文件失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	downloadFileName := time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
}

// @Title 热门活动
// @Description 热门活动接口
// @Param   KeyWord   query   string  false       "搜索关键词"
// @Success 200 {object} cygx.GetCygxActivityListRep
// @router /tag/hot_activity/list [get]
func (this *TagManagementController) TagHotActivityList() {
	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
	}
	keyWord := this.GetString("KeyWord")
	resp := new(cygx.GetCygxActivityListRep)
	var condition string
	var pars []interface{}
	if keyWord == "" {
		conf, err := cygx.GetCygxConfigDetailByCode(utils.CYGX_TAG_HOT_ACTIVITY_ID)
		if err != nil {
			br.Msg = "获取数据失败"
			br.ErrMsg = "买方研选产品介绍信息失败，Err:" + err.Error()
			return
		}
		if conf.ConfigValue == "" {
			conf.ConfigValue = "0"
		}
		condition += " AND art.activity_id IN  (" + conf.ConfigValue + ") "
	} else {
		condition += ` AND art.activity_name LIKE '%` + keyWord + `%'   `
	}
	condition += ` AND art.publish_status = 1  AND art.active_state IN (1,2) `
	list, err := cygx.GetActivityListAll(condition, pars, 0, 1000)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取失败，Err:" + err.Error()
		return
	}
	if len(list) == 0 {
		list = make([]*cygx.CygxActivityList, 0)
	}
	resp.List = list

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

// @Title 更新热门活动
// @Description 更新热门活动接口
// @router /tag/hot_activity/update [post]
func (this *TagManagementController) TagHotActivityUpdate() {
	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.ActivityIdsResp
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	activityIdList := req.ActivityIds
	var activityIds []string
	for _, v := range activityIdList {
		activityIds = append(activityIds, strconv.Itoa(v))
	}
	err = cygx.CygxConfigUpdateByCode(strings.Join(activityIds, ","), utils.CYGX_TAG_HOT_ACTIVITY_ID)
	if err != nil {
		br.Msg = "保存失败"
		br.ErrMsg = "保存失败，Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "保存成功"
}
