package line_feature

import (
	"encoding/json"
	"eta/eta_mobile/controllers"
	"eta/eta_mobile/models"
	"eta/eta_mobile/models/data_manage"
	"eta/eta_mobile/models/data_manage/line_feature/request"
	"eta/eta_mobile/services/data"
	lineFeatureServ "eta/eta_mobile/services/data/line_feature"
	"eta/eta_mobile/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"strconv"
	"strings"
	"time"
)

// LineFeaturesChartInfoController 统计特征图表管理
type LineFeaturesChartInfoController struct {
	controllers.BaseAuthController
}

// List
// @Title 统计特征图表列表接口
// @Description 统计特征图表列表接口
// @Param   PageSize   query   int  true       "每页数据条数"
// @Param   CurrentIndex   query   int  true       "当前页页码，从1开始"
// @Param   ChartClassifyId   query   int  true       "分类id"
// @Param   Keyword   query   string  true       "搜索关键词"
// @Param   IsShowMe   query   bool  true       "是否只看我的，true、false"
// @Param   Source   query   int  true       "图表类型，3：统计特征，4：滚动统计特征"
// @Success 200 {object} data_manage.ChartListResp
// @router /chart_info/list [get]
func (this *LineFeaturesChartInfoController) List() {
	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
	}

	chartClassifyId, _ := this.GetInt("ChartClassifyId")

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")
	keyword := this.GetString("KeyWord")

	var total int
	page := paging.GetPaging(currentIndex, pageSize, total)

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

	var condition string
	var pars []interface{}

	// 普通图表
	condition += ` AND source in(?,?,?) `
	pars = append(pars, utils.CHART_SOURCE_LINE_FEATURE_STANDARD_DEVIATION, utils.CHART_SOURCE_LINE_FEATURE_PERCENTILE, utils.CHART_SOURCE_LINE_FEATURE_FREQUENCY)

	if chartClassifyId > 0 {
		chartClassifyId, err := data_manage.GetChartClassify(chartClassifyId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取图表信息失败"
			br.ErrMsg = "获取信息失败,GetChartClassify,Err:" + err.Error()
			return
		}
		condition += " AND chart_classify_id IN(" + chartClassifyId + ") "
	}
	if keyword != "" {
		condition += ` AND  ( chart_name LIKE '%` + keyword + `%' )`
	}

	//只看我的
	isShowMe, _ := this.GetBool("IsShowMe")
	if isShowMe {
		condition += ` AND sys_user_id = ? `
		pars = append(pars, sysUser.AdminId)
	}

	// 获取当前账号的不可见指标
	noPermissionChartIdList := make([]int, 0)
	{
		obj := data_manage.EdbInfoNoPermissionAdmin{}
		confList, err := obj.GetAllChartListByAdminId(this.SysUser.AdminId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取不可见指标配置数据失败，Err:" + err.Error()
			return
		}
		for _, v := range confList {
			noPermissionChartIdList = append(noPermissionChartIdList, v.ChartInfoId)
		}
	}

	lenNoPermissionChartIdList := len(noPermissionChartIdList)
	if lenNoPermissionChartIdList > 0 {
		condition += ` AND chart_info_id not in (` + utils.GetOrmInReplace(lenNoPermissionChartIdList) + `) `
		pars = append(pars, noPermissionChartIdList)
	}

	//获取图表信息
	list, err := data_manage.GetChartListByCondition(condition, pars, startSize, pageSize)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Success = true
		br.Msg = "获取图表信息失败"
		br.ErrMsg = "获取图表信息失败,Err:" + err.Error()
		return
	}

	myChartList, err := data_manage.GetMyChartListByAdminId(sysUser.AdminId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取图表信息失败"
		br.ErrMsg = "获取我的图表信息失败,Err:" + err.Error()
		return
	}
	myChartMap := make(map[int]*data_manage.MyChartView)
	for _, v := range myChartList {
		myChartMap[v.ChartInfoId] = v
	}
	listLen := len(list)
	chartEdbMap := make(map[int][]*data_manage.ChartEdbInfoMapping)
	if listLen > 0 {
		chartInfoIds := ""
		for _, v := range list {
			chartInfoIds += strconv.Itoa(v.ChartInfoId) + ","
		}
		if chartInfoIds != "" {
			chartInfoIds = strings.Trim(chartInfoIds, ",")
			//判断是否需要展示英文标识
			edbList, e := data_manage.GetChartEdbMappingListByChartInfoIds(chartInfoIds)
			if e != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取图表，指标信息失败，Err:" + e.Error()
				return
			}
			for _, v := range edbList {
				chartEdbMap[v.ChartInfoId] = append(chartEdbMap[v.ChartInfoId], v)
			}
		}
	}
	for i := 0; i < listLen; i++ {
		//判断是否需要展示英文标识
		if _, ok := chartEdbMap[list[i].ChartInfoId]; ok {
			list[i].IsEnChart = data.CheckIsEnChart(list[i].ChartNameEn, []*data_manage.ChartEdbInfoMapping{}, list[i].Source, list[i].ChartType)
		}

		if existItem, ok := myChartMap[list[i].ChartInfoId]; ok {
			list[i].IsAdd = true
			list[i].MyChartId = existItem.MyChartId
			list[i].MyChartClassifyId = existItem.MyChartClassifyId
		}
	}

	resp := new(data_manage.ChartListResp)
	if list == nil || len(list) <= 0 || (err != nil && err.Error() == utils.ErrNoRow()) {
		items := make([]*data_manage.ChartInfoView, 0)
		resp.Paging = page
		resp.List = items
		br.Ret = 200
		br.Success = true
		br.Msg = "获取成功"
		return
	}

	dataCount, err := data_manage.GetChartListCountByCondition(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取指标信息失败"
		br.ErrMsg = "获取指标数据总数失败,Err:" + err.Error()
		return
	}
	page = paging.GetPaging(currentIndex, pageSize, dataCount)
	resp.Paging = page
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// Refresh
// @Title 图表刷新接口
// @Description 图表刷新接口
// @Param   ChartInfoId   query   int  true       "图表id"
// @Param   UniqueCode   query   string  true       "唯一code"
// @Success Ret=200 刷新成功
// @router /chart_info/refresh [get]
func (this *LineFeaturesChartInfoController) Refresh() {
	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
	}
	chartInfoId, _ := this.GetInt("ChartInfoId")
	uniqueCode := this.GetString("UniqueCode")
	if chartInfoId <= 0 && uniqueCode == `` {
		br.Msg = "参数错误"
		br.ErrMsg = "参数错误:chartInfoId:" + strconv.Itoa(chartInfoId) + ",UniqueCode:" + uniqueCode
		return
	}

	var chartInfo *data_manage.ChartInfo
	var err error
	if chartInfoId > 0 {
		chartInfo, err = data_manage.GetChartInfoById(chartInfoId)
	} else {
		chartInfo, err = data_manage.GetChartInfoByUniqueCode(uniqueCode)
	}
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "图表已被删除，无需刷新"
			br.ErrMsg = "获取指标信息失败，Err:" + err.Error()
			return
		}
		br.Msg = "刷新失败"
		br.ErrMsg = "获取图表信息失败，Err:" + err.Error()
		return
	}

	// 刷新图表的指标信息
	err = data.ChartInfoRefreshV2(chartInfo.ChartInfoId)

	//清除图表缓存
	{
		key := utils.HZ_CHART_LIB_DETAIL + chartInfo.UniqueCode
		_ = utils.Rc.Delete(key)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "刷新成功"
}

// Copy
// @Title 复制并新增图表接口
// @Description 复制并新增图表接口
// @Param	request	body data_manage.CopyAddChartInfoReq true "type json string"
// @Success 200 {object} data_manage.AddChartInfoResp
// @router /chart_info/copy [post]
func (this *LineFeaturesChartInfoController) Copy() {
	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
	}
	deleteCache := true
	cacheKey := "CACHE_CHART_INFO_ADD_" + strconv.Itoa(sysUser.AdminId)
	defer func() {
		if deleteCache {
			utils.Rc.Delete(cacheKey)
		}
	}()
	if !utils.Rc.SetNX(cacheKey, 1, 30*time.Second) {
		deleteCache = false
		br.Msg = "系统处理中，请稍后重试！"
		br.ErrMsg = "系统处理中，请稍后重试！" + sysUser.RealName + ";data:" + string(this.Ctx.Input.RequestBody)
		return
	}
	var req data_manage.CopyAddChartInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}

	// 获取原图表信息
	oldChartInfo, err := data_manage.GetChartInfoById(req.ChartInfoId)
	if err != nil {
		br.Msg = "获取原图表信息失败"
		br.ErrMsg = "获取原图表信息失败,Err:" + err.Error()
		return
	}
	if !utils.InArrayByInt([]int{utils.CHART_SOURCE_LINE_FEATURE_STANDARD_DEVIATION, utils.CHART_SOURCE_LINE_FEATURE_PERCENTILE, utils.CHART_SOURCE_LINE_FEATURE_FREQUENCY}, oldChartInfo.Source) {
		br.Msg = `错误的图表类型`
		br.IsSendEmail = false
		return
	}

	multipleGraphConfigChartMapping, err := data_manage.GetMultipleGraphConfigChartMappingByChartId(oldChartInfo.ChartInfoId)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = `保存失败`
		br.ErrMsg = "获取配置与图表的关联关系失败，ERR:" + err.Error()
		return
	}

	// 获取图表关联指标
	edbMappingList, err := data_manage.GetChartEdbMappingList(oldChartInfo.ChartInfoId)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取图表关联指标信息失败，Err:" + err.Error()
		return
	}
	if len(edbMappingList) != 1 {
		br.Msg = "获取失败"
		br.ErrMsg = fmt.Sprint("获取图表关联指标信息异常，数量:", len(edbMappingList))
		return
	}
	edbInfoMapping := edbMappingList[0]

	// 批量设置图
	chartInfo, err, errMsg, isSendEmail := lineFeatureServ.CopyChartInfo(multipleGraphConfigChartMapping.MultipleGraphConfigId, multipleGraphConfigChartMapping.Source, req.ChartClassifyId, req.ChartName, edbInfoMapping, oldChartInfo, sysUser)

	if err != nil {
		br.Msg = "复制失败"
		if errMsg != `` {
			br.Msg = errMsg
		}
		br.ErrMsg = "复制失败，ERR:" + err.Error()
		br.IsSendEmail = isSendEmail
		return
	}

	resp := data_manage.AddChartInfoResp{
		ChartInfoId: chartInfo.ChartInfoId,
		UniqueCode:  chartInfo.UniqueCode,
		ChartType:   chartInfo.ChartType,
	}

	//新增操作日志
	{

		chartLog := new(data_manage.ChartInfoLog)
		chartLog.ChartInfoId = chartInfo.ChartInfoId
		chartLog.ChartName = chartInfo.ChartName
		chartLog.ChartClassifyId = chartInfo.ChartClassifyId
		chartLog.SysUserId = sysUser.AdminId
		chartLog.SysUserRealName = sysUser.RealName
		chartLog.UniqueCode = chartInfo.UniqueCode
		chartLog.CreateTime = time.Now()
		chartLog.Content = string(this.Ctx.Input.RequestBody)
		chartLog.Status = "新增统计特征图表"
		chartLog.Method = this.Ctx.Input.URI()
		go data_manage.AddChartInfoLog(chartLog)
	}

	br.Ret = 200
	br.Data = resp
	br.Success = true
	br.Msg = "保存成功"
	br.IsAddLog = true
}

// EnInfoEdit
// @Title 编辑图表英文信息接口
// @Description 编辑图表英文信息接口
// @Param	request	body data_manage.EditChartEnInfoReq true "type json string"
// @Success Ret=200 编辑成功
// @router /chart_info/en/edit [post]
func (this *LineFeaturesChartInfoController) EnInfoEdit() {
	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.EditChartEnInfoReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常！"
		br.ErrMsg = "参数解析失败，Err:" + err.Error()
		return
	}
	req.ChartNameEn = strings.Trim(req.ChartNameEn, " ")
	if req.ChartInfoId <= 0 {
		br.Msg = "请选择图表"
		return
	}
	if req.ChartNameEn == "" {
		br.Msg = "请输入英文图表名称"
		return
	}

	//判断指标名称是否存在
	chartItem, err := data_manage.GetChartInfoById(req.ChartInfoId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "图表已被删除，请刷新页面"
			br.ErrMsg = "图表已被删除，请刷新页面"
			return
		}
		br.Msg = "获取图表信息失败"
		br.ErrMsg = "获取图表信息失败,Err:" + err.Error()
		return
	}

	// 校验名称是否有重复
	{
		var condition string
		var pars []interface{}
		condition += " AND chart_info_id <> ?  AND chart_name_en = ? AND source in (?,?,?)"
		pars = append(pars, req.ChartInfoId, req.ChartNameEn, utils.CHART_SOURCE_LINE_FEATURE_STANDARD_DEVIATION, utils.CHART_SOURCE_LINE_FEATURE_PERCENTILE, utils.CHART_SOURCE_LINE_FEATURE_FREQUENCY)
		existItem, err := data_manage.GetChartInfoByCondition(condition, pars)
		if err != nil {
			if err.Error() != utils.ErrNoRow() {
				br.Msg = "判断英文图表名称是否存在失败"
				br.ErrMsg = "判断英文图表名称是否存在失败,Err:" + err.Error()
				return
			}
		}
		if err == nil && existItem.ChartInfoId > 0 {
			br.Msg = existItem.ChartName + "：" + req.ChartNameEn + "图表名称已存在"
			return
		}
	}

	chartItem.ChartNameEn = req.ChartNameEn
	chartItem.ModifyTime = time.Now().Local()
	if e := chartItem.Update([]string{"ChartNameEn", "ModifyTime"}); e != nil {
		br.Msg = "操作失败"
		br.ErrMsg = "更新图表信息失败, Err: " + e.Error()
		return
	}

	//添加es数据
	go data.EsAddOrEditChartInfo(chartItem.ChartInfoId)
	//修改my eta es数据
	go data.EsAddOrEditMyChartInfoByChartInfoId(chartItem.ChartInfoId)

	//指标 修改es信息
	//go data.AddOrEditEdbInfoToEs(edbInfo.EdbInfoId)

	//新增操作日志
	{
		chartLog := new(data_manage.ChartInfoLog)
		chartLog.ChartName = chartItem.ChartName
		chartLog.ChartInfoId = req.ChartInfoId
		chartLog.ChartClassifyId = chartItem.ChartClassifyId
		chartLog.SysUserId = sysUser.AdminId
		chartLog.SysUserRealName = sysUser.RealName
		chartLog.UniqueCode = chartItem.UniqueCode
		chartLog.CreateTime = time.Now()
		chartLog.Content = string(this.Ctx.Input.RequestBody)
		chartLog.Status = "编辑统计特征图表英文信息"
		chartLog.Method = this.Ctx.Input.URL()
		go data_manage.AddChartInfoLog(chartLog)
	}
	// 清除缓存
	if utils.Re == nil && utils.Rc != nil {
		_ = utils.Rc.Delete(utils.HZ_CHART_LIB_DETAIL + chartItem.UniqueCode) //图表分享链接缓存
		_ = utils.Rc.Delete(data.GetChartInfoDataKey(req.ChartInfoId))
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
	br.IsAddLog = true
}

// SearchByEs
// @Title 图表模糊搜索（从es获取）
// @Description  图表模糊搜索（从es获取）
// @Param   Keyword   query   string  true       "图表名称"
// @Param   IsShowMe   query   bool  true       "是否只看我的，true、false"
// @Param   Source   query   int  true       "来源，3：统计特征，4：滚动统计特征，默认0：全部"
// @Success 200 {object} data_manage.ChartInfo
// @router /chart_info/search_by_es [get]
func (this *LineFeaturesChartInfoController) SearchByEs() {
	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")

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

	keyword := this.GetString("Keyword")

	//只看我的
	isShowMe, _ := this.GetBool("IsShowMe")
	showSysId := 0
	if isShowMe {
		showSysId = sysUser.AdminId
	}

	sourceList := []int{utils.CHART_SOURCE_LINE_FEATURE_STANDARD_DEVIATION, utils.CHART_SOURCE_LINE_FEATURE_PERCENTILE, utils.CHART_SOURCE_LINE_FEATURE_FREQUENCY}

	var searchList []*data_manage.ChartInfo
	var total int64
	var err error

	// 获取当前账号的不可见指标
	noPermissionChartIdList := make([]int, 0)
	{
		obj := data_manage.EdbInfoNoPermissionAdmin{}
		confList, err := obj.GetAllChartListByAdminId(this.SysUser.AdminId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取不可见指标配置数据失败，Err:" + err.Error()
			return
		}
		for _, v := range confList {
			noPermissionChartIdList = append(noPermissionChartIdList, v.ChartInfoId)
		}
	}

	if keyword != "" {
		searchList, total, err = data.EsSearchChartInfo(keyword, showSysId, sourceList, noPermissionChartIdList, startSize, pageSize)
	} else {
		total, searchList, err = data_manage.ChartInfoSearchByEmptyKeyWord(showSysId, sourceList, noPermissionChartIdList)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取失败"
			br.ErrMsg = "获取图表信息失败，Err:" + err.Error()
			return
		}
	}

	finalList := make([]*data_manage.ChartInfoMore, 0)
	if len(searchList) > 0 {
		chartInfoIds := ""
		chartEdbMap := make(map[int][]*data_manage.ChartEdbInfoMapping)
		for _, v := range searchList {
			chartInfoIds += strconv.Itoa(v.ChartInfoId) + ","
		}
		if chartInfoIds != "" {
			chartInfoIds = strings.Trim(chartInfoIds, ",")
			//判断是否需要展示英文标识
			edbList, e := data_manage.GetChartEdbMappingListByChartInfoIds(chartInfoIds)
			if e != nil {
				br.Msg = "获取失败"
				br.ErrMsg = "获取图表，指标信息失败，Err:" + e.Error()
				return
			}
			for _, v := range edbList {
				chartEdbMap[v.ChartInfoId] = append(chartEdbMap[v.ChartInfoId], v)
			}
		}

		for _, v := range searchList {
			tmp := new(data_manage.ChartInfoMore)
			tmp.ChartInfo = *v
			//判断是否需要展示英文标识
			if _, ok := chartEdbMap[v.ChartInfoId]; ok {
				tmp.IsEnChart = data.CheckIsEnChart(v.ChartNameEn, []*data_manage.ChartEdbInfoMapping{}, v.Source, v.ChartType)
			}
			finalList = append(finalList, tmp)
		}
	}
	//新增搜索词记录
	{
		searchKeyword := new(data_manage.SearchKeyword)
		searchKeyword.KeyWord = keyword
		searchKeyword.CreateTime = time.Now()
		go data_manage.AddSearchKeyword(searchKeyword)
	}

	page := paging.GetPaging(currentIndex, pageSize, int(total))
	resp := data_manage.ChartInfoListByEsResp{
		Paging: page,
		List:   finalList,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}
