package data_manage

import (
	"encoding/json"
	"eta/eta_api/models"
	"eta/eta_api/models/data_manage"
	"eta/eta_api/utils"
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"strconv"
	"strings"
)

// SmmIndexList
// @Title 有色api数据指标列表
// @Description 有色api数据指标列表
// @Success 200 {object} data_manage.SmmClassify
// @router /smm/api/list [post]
func (this *EdbInfoController) SmmApiList() {
	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 data_manage.SmmIndexListReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}

	types := req.Types
	frequency := req.Frequency
	dataState := req.DataState
	keyword := req.Keyword
	indexCodes := req.IndexCodes
	sortType := req.SortType
	sortParam := req.SortParam
	pageSize := req.PageSize
	currentIndex := req.CurrentIndex

	if sortType == "" {
		sortType = "desc"
	}

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

	var condition string
	var pars []interface{}

	if len(types) > 0 {
		condition += " AND ( "
		for _, v := range types {
			typeArr := strings.Split(v,",")
			for i, v := range typeArr {
				if i == 0 {
					condition += " ( "
				}
				typeStr := "type_"
				typeStr += fmt.Sprintf("%d", i+1)
				condition += typeStr+" =? "
				pars = append(pars, v)
				if i == len(typeArr) - 1 {
					condition += " ) "
				} else {
					condition += " AND "
				}
			}
			condition += " OR "
		}
		condition = strings.Trim(condition, "OR ")
		condition += " ) "
	}

	if frequency != "" {
		frequencyArr := strings.Split(frequency,",")
		condition += ` AND frequency IN (` + utils.GetOrmInReplace(len(frequencyArr)) + `) `
		pars = append(pars, frequencyArr)
	}

	if dataState != "" {
		stateArr := strings.Split(dataState,",")
		if strings.Contains(dataState, "normal") {
			stateArr = append(stateArr, "")
			condition += ` AND data_state IN (` + utils.GetOrmInReplace(len(stateArr)) + `) `
			pars = append(pars, stateArr)
		} else {
			condition += ` AND data_state IN (` + utils.GetOrmInReplace(len(stateArr)) + `) `
			pars = append(pars, stateArr)
		}
	}

	sortStr := ``

	if keyword != "" {
		keyWordArr := strings.Split(keyword, " ")
		if len(keyWordArr) > 0 {
			condition += " AND ( "
			keywordStr := strings.Replace(keyword, " ", "", -1)
			condition += ` CONCAT(index_name,index_code) LIKE '%` + keywordStr + `%' OR `
			sortStr += ` CASE WHEN CONCAT(index_name,index_code) LIKE '%` + keywordStr + `%' THEN 1 `
			for i, v := range keyWordArr {
				condition += ` CONCAT(index_name,index_code) LIKE '%` + v + `%' OR`
				sortStr += ` WHEN CONCAT(index_name,index_code) LIKE '%` + v + `%' THEN  ` + strconv.Itoa(i+2) + ` `
			}
			sortStr += ` END, `
			condition = strings.TrimRight(condition, "OR")
			condition += " ) "
		}
	}

	if indexCodes != "" {
		indexCodeArr := strings.Split(indexCodes,",")
		indexCodeStr := ""
		for _, v := range indexCodeArr {
			indexCodeStr += "'" + v + "',"
		}
		indexCodeStr = strings.TrimRight(indexCodeStr, ",")
		condition += " AND index_code IN (" + indexCodeStr + ") "
	}

	if sortParam != `` {
		sortStr += fmt.Sprintf("%s %s,modify_time desc ", utils.PascalToSnake(sortParam), sortType)
	} else {
		sortStr += " modify_time desc "
	}

	total, err := data_manage.GetSmmIndexDataListCount(condition, pars)
	if err!= nil {
		br.Msg = "获取指标总数失败"
		br.ErrMsg = "获取指标总数失败,Err:" + err.Error()
		return
	}

	indexList, err := data_manage.GetSmmIndexDataList(condition, sortStr, pars, startSize, pageSize)
	if err != nil {
		br.Msg = "获取指标列表失败"
		br.ErrMsg = "获取指标列表失败,Err:" + err.Error()
		return
	}

	for _, v := range indexList {
		v.TypeAll = v.Type1 + "/" + v.Type2 + "/" + v.Type3
	}

	page := paging.GetPaging(currentIndex, pageSize, total)
	var ret data_manage.BaseFromSmmIndexListResp
	ret.List = indexList
	ret.Paging = page
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = ret
}

// SmmApiTypeList
// @Title 有色api数据分类列表
// @Description 有色api数据分类列表
// @Success 200 {object} data_manage.SmmClassify
// @router /smm/api/type/list [get]
func (this *EdbInfoController) SmmApiTypeList() {
	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
	}

	typeList, err := data_manage.GetBaseFromSmmIndexTypeList()
	if err != nil {
		br.Msg = "获取指标列表失败"
		br.ErrMsg = "获取指标列表失败,Err:" + err.Error()
		return
	}

	resp := make([]data_manage.TypeListRespItem, 0)

	typeMap := make(map[string]map[string][]string)
	//type2Map := make(map[string][]string)

	//type2Map := make(map[string]data_manage.TypeListRespItem)

	// 初始化
	for _, v := range typeList {
		if v.Type1 != ""{
			if _, ok := typeMap[v.Type1];!ok {
				typeMap[v.Type1] = make(map[string][]string)
			} else {
				if _, ok := typeMap[v.Type1][v.Type2];!ok {
					typeMap[v.Type1][v.Type2] = make([]string, 0)
				}
			}
		}
	}

	for _, v := range typeList {
		if v.Type1 != ""{
			typeMap[v.Type1][v.Type2] = append(typeMap[v.Type1][v.Type2], v.Type3)
		}
	}

	for type1, type2Map := range typeMap {
		var item data_manage.TypeListRespItem
		item.Type = type1
		for type2, type3List := range type2Map {
			var child data_manage.TypeListRespItem
			child.Type = type2
			for _, type3 := range type3List {
				child.Child = append(child.Child, data_manage.TypeListRespItem{type3,nil})
			}
			item.Child = append(item.Child, child)
		}
		resp = append(resp, item)
	}

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