/**
* @Author: jgl
* @Date: 2021/9/14 11:15
 */

package data

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"errors"
	"eta/eta_api/models/data_manage"
	"eta/eta_api/models/system"
	"eta/eta_api/utils"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"
)

type YsIndex struct {
	Code int64 `json:"code"`
	Data struct {
		Apis []struct {
			Aid           int64  `json:"aid"`
			APILabel      string `json:"api_label"`
			APIStartTime  string `json:"api_start_time"`
			APIType       int64  `json:"api_type"`
			APITypeAll    string `json:"api_type_all"`
			APIUpdate     int64  `json:"api_update"`
			APIUpdateTime string `json:"api_update_time"`
			APIUpdateType string `json:"api_update_type"`
			AuthDur       int64  `json:"auth_dur"`
			AuthDurType   string `json:"auth_dur_type"`
			AuthLang      string `json:"auth_lang"`
			AuthModule    string `json:"auth_module"`
			EditPerson    string `json:"edit_person"`
			EditTime      string `json:"edit_time"`
			Enable        string `json:"enable"`
			FinishTime    string `json:"finish_time"`
			Interface     string `json:"interface"`
			Name          string `json:"name"`
			StartTime     string `json:"start_time"`
			Type1         string `json:"type_1"`
			Type2         string `json:"type_2"`
			Type3         string `json:"type_3"`
		} `json:"apis"`
		Types []struct {
			Name string `json:"name"`
			Tid  int64  `json:"tid"`
		} `json:"types"`
	} `json:"data"`
	Msg string `json:"msg"`
}

// 已作废,暂时保留
func GetSmmIndexData() {
	list, err := data_manage.GetBaseFromSmmList()
	if err != nil {
		fmt.Println("GetBaseFromSmmList Err:" + err.Error())
		return
	}

	token, err := getToken("pqian@hzinsights.com", "hz123456")
	if err != nil {
		fmt.Println(err)
		return
	}

	endDate := time.Now().Format(utils.FormatDate)
	smmIndexAll, err := data_manage.GetBaseFromSmmIndex()
	if err != nil {
		fmt.Println("GetBaseFromSmmIndex Err:" + err.Error())
		return
	}
	existIndexMap := make(map[string]*data_manage.BaseFromSmmIndex)
	for _, item := range smmIndexAll {
		existIndexMap[item.IndexCode] = item
	}

	dataAllList, err := data_manage.GetBaseFromSmmDataAll()
	if err != nil {
		fmt.Println("GetBaseFromSmmData Err:" + err.Error())
		return
	}
	existDataMap := make(map[string]*data_manage.BaseFromSmmData)
	for _, item := range dataAllList {
		key := item.IndexCode + item.DataTime
		existDataMap[key] = item
	}

	for _, v := range list {
		edbCode := v.Interface
		startDate := v.ApiStartTime
		ysItem, err := getApiData(token, edbCode, startDate, endDate)
		if err != nil {
			fmt.Println(err)
			return
		}
		if ysItem != nil && ysItem.Code == 200 {
			frequency := ysItem.Data.Frequency
			var smmIndexIdArr []int64
			var indexCodeArr []string
			indexKey := 0
			containsCount := 0
			for fk, fv := range ysItem.Data.Field {
				if fk == 0 {
					continue
				}
				if strings.Contains(fv.Name, "产品名称") ||
					strings.Contains(fv.Name, "单位") ||
					strings.Contains(fv.Name, "时间") {
					containsCount++
				}
				if !strings.Contains(fv.Name, "产品名称") &&
					!strings.Contains(fv.Name, "单位") &&
					!strings.Contains(fv.Name, "时间") {

					indexKey += 1
					indexCode := v.Interface + "_" + strconv.Itoa(indexKey)
					if findItem, ok := existIndexMap[indexCode]; !ok {
						ssmIndex := new(data_manage.BaseFromSmmIndex)
						ssmIndex.Interface = v.Interface
						ssmIndex.Name = v.Name
						ssmIndex.IndexCode = indexCode
						ssmIndex.IndexName = v.Name + "_" + fv.Name
						ssmIndex.Type1 = v.Type1
						ssmIndex.Type2 = v.Type2
						ssmIndex.Type3 = v.Type3
						ssmIndex.Frequency = frequency
						ssmIndex.Unit = fv.Unit
						ssmIndex.ApiStartTime = v.ApiStartTime
						ssmIndex.ApiUpdateTime = v.ApiUpdateTime
						ssmIndex.StartTime = v.StartTime
						ssmIndex.FinishTime = v.FinishTime
						ssmIndex.CreateTime = time.Now()
						ssmIndex.ModifyTime = time.Now()
						lastIndexId, err := data_manage.AddBaseFromSmmIndex(ssmIndex)
						if err != nil {
							return
						}
						smmIndexIdArr = append(smmIndexIdArr, lastIndexId)
						indexCodeArr = append(indexCodeArr, indexCode)
					} else {
						smmIndexIdArr = append(smmIndexIdArr, int64(findItem.BaseFromSmmIndexId))
						indexCodeArr = append(indexCodeArr, findItem.IndexCode)
					}
				}
			}

			for _, dv := range ysItem.Data.Content {
				var dataTime string
				for dataK, dataV := range dv {
					fmt.Println(dataK, dataV)
					if dataK == 0 {
						dataTime = dataV

						if frequency == "月" {
							monthDate, err := time.Parse("2006-01", dataTime)
							if err != nil {
								fmt.Println("time.Parse:" + err.Error())
							}
							lastTime := monthDate.AddDate(0, 1, -1)
							lastYear, lastMonth, lastDay := lastTime.Date()
							var lastDate string
							if int(lastMonth) < 10 {
								lastDate = strconv.Itoa(lastYear) + "-" + "0" + strconv.Itoa(int(lastMonth)) + "-" + strconv.Itoa(lastDay)
							} else {
								lastDate = strconv.Itoa(lastYear) + "-" + strconv.Itoa(int(lastMonth)) + "-" + strconv.Itoa(lastDay)
							}
							dataTime = lastDate
						}

					} else {
						if !strings.Contains(ysItem.Data.Field[dataK].Name, "产品名称") &&
							!strings.Contains(ysItem.Data.Field[dataK].Name, "单位") &&
							!strings.Contains(ysItem.Data.Field[dataK].Name, "时间") {

							saveDataTime, err := time.Parse(utils.FormatDate, dataTime)
							if err != nil {

							}
							timestamp := saveDataTime.UnixNano() / 1e6
							var smmIndexId int64
							var indexCode string
							smmIndexId = smmIndexIdArr[dataK-(containsCount+1)]
							indexCode = indexCodeArr[dataK-(containsCount+1)]

							key := indexCode + dataTime
							val := strings.Replace(dataV, ",", "", -1)

							if findData, dataOk := existDataMap[key]; !dataOk {
								dataItem := new(data_manage.BaseFromSmmData)
								dataItem.BaseFromSmmIndexId = int(smmIndexId)
								dataItem.IndexCode = indexCode
								dataItem.DataTime = dataTime
								dataItem.Value = val
								dataItem.CreateTime = time.Now()
								dataItem.ModifyTime = time.Now()
								dataItem.DataTimestamp = timestamp
								_, err = data_manage.AddBaseFromSmmData(dataItem)
								if err != nil && !strings.Contains(err.Error(), "idx_index_code_date") {
									fmt.Println("AddBaseFromSmmData Err:" + err.Error())
									return
								}
							} else {
								if findData != nil && findData.Value != val { //修改
									err = data_manage.ModifyBaseFromSmmData(findData.SmmDataId, val)
									if err != nil {
										fmt.Println("ModifyBaseFromSmmData Err:" + err.Error())
										return
									}
								}
							}
						}
					}
				}
			}
		}

		//修改数据开始，结束日期
		{
			indexList, err := data_manage.GetBaseFromSmmIndexBySmmCode(v.Interface)
			if err != nil {
				fmt.Println("GetBaseFromSmmIndexByCode Err:" + err.Error())
			}
			for _, sv := range indexList {
				minDate, maxDate, err := data_manage.GetBaseFromSmmMaxOrMinDate(sv.IndexCode)
				if err != nil {
					fmt.Println("GetEdbDataSmmMaxOrMinDate Err:" + err.Error())
				} else {
					err = data_manage.ModifyBaseFromSmmMinDateAndMaxDate(sv.BaseFromSmmIndexId, minDate, maxDate)
					if err != nil {
						fmt.Println("GetEdbDataSmmMaxOrMinDate Err:" + err.Error())
					}
				}
			}
		}
		fmt.Println(v.Interface, v.Name)
		time.Sleep(3 * time.Second)
	}
}

const (
	dataUrl = "https://dataapi.smm.cn/GetData/" //data url (中文)
	//dataUrl = "https://dataapi.smm.cn/GetDataEn/" //data url (english edition)
	authUrl = "https://platform.smm.cn/usercenter/auth" // auth url (for all)
)

type TokenResp struct {
	Code int       `json:"Code"`
	Msg  string    `json:"Msg"`
	Data TokenData `json:"Data"`
}

type TokenData struct {
	Token string `json:"Token"`
}

// 获取token
func getToken(userName string, password string) (string, error) {
	encryptAuth := md5.New()
	encryptAuth.Write([]byte(password)) //encrypt password with md5
	newPassword := hex.EncodeToString(encryptAuth.Sum(nil))

	resp, err := http.PostForm(authUrl, url.Values{"user_name": {userName}, "password": {newPassword}})
	if err != nil {
		return "", err
	}

	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("reponse error", err)
		return "", err
	}

	var bodyJsonContent TokenResp

	if err = json.Unmarshal([]byte(body), &bodyJsonContent); err != nil {
		fmt.Println(err, "unmarsal failure")
		return "", err
	}

	var token string
	if bodyJsonContent.Code == 0 {
		token = bodyJsonContent.Data.Token
	}

	//print(token)
	return token, nil
}

// request response
type DataResp struct {
	Code int      `json:"Code"`
	Msg  string   `json:"Msg"`
	Data *ApiData `json:"Data"`
}

// api data response
type ApiData struct {
	Status  int        `json:"Status"` //0 no permission，1 ok
	Field   []ApiField `json:"Field"`
	Content [][]string `json:"Content"`
}

// api title
type ApiField struct {
	Unit       string `json:"Unit"`
	Info       string `json:"Info"`
	Name       string `json:"Name"`
	ColumnType string `json:"ColumnType"`
	ColIndex   uint   `json:"ColIndex"`
	IsDate     string `json:"IsDate"`
}

type YsResult struct {
	Code int64 `json:"Code"`
	Data struct {
		CompanyList []interface{} `json:"CompanyList"`
		Content     [][]string    `json:"Content"`
		Field       []struct {
			ColIndex   int64  `json:"ColIndex"`
			ColumnType string `json:"ColumnType"`
			Info       string `json:"Info"`
			IsDate     string `json:"IsDate"`
			Name       string `json:"Name"`
			Unit       string `json:"Unit"`
			DBColName  string `json:"db_col_name"`
		} `json:"Field"`
		CountPage   int64  `json:"count_page"`
		CurrentPage int64  `json:"current_page"`
		Frequency   string `json:"frequency"`
		Mindate     string `json:"mindate"`
		PageNum     int64  `json:"page_num"`
		Status      int64  `json:"status"`
		TotalNum    int64  `json:"total_num"`
	} `json:"Data"`
	Msg string `json:"Msg"`
}

/*
 * request data
 * sdatetime,edatetime ==>format:yyyy-mm-dd,
 * apiName ==> data.metal.com(for english)/data.smm.cn (for chinese)
 */
func getApiData(token string, apiName string, sdatetime string, edatetime string) (item *YsResult, err error) {
	reqUrl := dataUrl + apiName
	resp, err := http.PostForm(reqUrl, url.Values{"token": {token}, "sdatetime": {sdatetime}, "edatetime": {edatetime}})
	if err != nil {
		return nil, err
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("response error")
		return nil, err
	}
	utils.FileLog.Info("ys result:" + string(body))
	dataJsonContent := new(YsResult)
	if err = json.Unmarshal([]byte(body), &dataJsonContent); err != nil {
		fmt.Println(err, "data unmarshal failure")
		return nil, err
	}

	if dataJsonContent.Code == 200 && len(dataJsonContent.Data.Content) > 0 {
		return dataJsonContent, nil
	} else {
		err = errors.New("code:" + strconv.Itoa(int(dataJsonContent.Code)) + "msg:" + dataJsonContent.Msg)
	}
	return nil, nil
}

// AddSmmClassify 添加SMM分类
func AddSmmClassify(classifyName string, parentId, sysUserId int, sysUserName, lang string) (classifyInfo *data_manage.BaseFromSmmClassify, err error, errMsg string) {
	// 校验分类名称相同的数量
	{
		var count int
		switch lang {
		case utils.EnLangVersion:
			count, err = data_manage.GetBaseFromSmmClassifyEnCount(classifyName, parentId)
		default:
			count, err = data_manage.GetBaseFromSmmClassifyCount(classifyName, parentId)
		}
		if err != nil {
			errMsg = `判断名称是否已存在失败`
			return
		}
		if count > 0 {
			errMsg = `分类名称已存在，请重新输入`
			err = errors.New(errMsg)
			return
		}
	}

	level := 1
	if parentId > 0 {
		parentClassify, e := data_manage.GetBaseFromSmmClassifyById(parentId)
		if e != nil {
			if e.Error() == utils.ErrNoRow() {
				err = e
				errMsg = `一级分类不存在`
				return
			}
			err = e
			errMsg = `查询一级分类失败`
			return
		}
		level = parentClassify.Level + 1
	}
	classifyInfo = &data_manage.BaseFromSmmClassify{
		ClassifyName:    classifyName,
		ClassifyNameEn:  classifyName,
		ParentId:        parentId,
		SysUserId:       sysUserId,
		SysUserRealName: sysUserName,
		Sort:            0,
		Level:           level,
		ModifyTime:      time.Now(),
		CreateTime:      time.Now(),
	}
	classifyId, err := data_manage.AddBaseFromSmmClassify(classifyInfo)
	if err != nil {
		errMsg = "保存分类失败"
		return
	}
	classifyInfo.ClassifyId = int(classifyId)
	//更新sort为classifyId
	err = data_manage.UpdateBaseFromSmmClassifySort(int(classifyId))
	return
}

// EditSmmClassify 编辑Smm分类
func EditSmmClassify(classifyId int, classifyName, lang string, sysUser *system.Admin) (err error, errMsg string) {
	item, err := data_manage.GetBaseFromSmmClassifyById(classifyId)
	if err != nil {
		errMsg = `保存失败`
		return
	}

	switch lang {
	case utils.EnLangVersion:
		// 名字相同，那么就直接返回
		if item.ClassifyNameEn == classifyName {
			return
		}

		// 判断名称是否已存在
		count, tmpErr := data_manage.GetBaseFromSmmClassifyEnCount(classifyName, item.ParentId)
		if tmpErr != nil {
			err = tmpErr
			errMsg = "判断名称是否已存在失败"
			return
		}
		if count > 0 {
			errMsg = "分类名称已存在，请重新输入"
			err = errors.New(errMsg)
			return
		}

		// 修改数据
		err = data_manage.EditBaseFromSmmClassifyEn(classifyId, classifyName)
		if err != nil {
			errMsg = "保存失败"
		}
	default:
		// 名字相同，那么就直接返回
		if item.ClassifyName == classifyName {
			return
		}

		// 判断名称是否已存在
		count, tmpErr := data_manage.GetBaseFromSmmClassifyCount(classifyName, item.ParentId)
		if tmpErr != nil {
			err = tmpErr
			errMsg = "判断名称是否已存在失败"
			return
		}
		if count > 0 {
			errMsg = "分类名称已存在，请重新输入"
			err = errors.New(errMsg)
			return
		}

		// 修改数据
		err = data_manage.EditBaseFromSmmClassify(classifyId, classifyName)
		if err != nil {
			errMsg = "保存失败"
		}
	}

	return
}

// MoveSmmClassify 移动Smm分类
func MoveSmmClassify(classifyId, parentClassifyId, prevClassifyId, nextClassifyId int) (err error, errMsg string) {
	//判断分类是否存在
	classifyInfo, err := data_manage.GetBaseFromSmmClassifyById(classifyId)
	if err != nil {
		errMsg = "移动失败"
		err = errors.New("获取分类信息失败,Err:" + err.Error())
		return
	}

	updateCol := make([]string, 0)

	//判断上级id是否一致，如果不一致的话，那么需要移动该分类层级
	if classifyInfo.ParentId != parentClassifyId && parentClassifyId != 0 {
		parentClassifyInfo, tmpErr := data_manage.GetBaseFromSmmClassifyById(parentClassifyId)
		if tmpErr != nil {
			errMsg = "移动失败"
			err = errors.New("获取上级分类信息失败,Err:" + tmpErr.Error())
			return
		}
		classifyInfo.ParentId = parentClassifyInfo.ClassifyId
		classifyInfo.Level = parentClassifyInfo.Level + 1
		updateCol = append(updateCol, "ParentId", "Level")
	}
	var currentSort, prevSort, nextSort int
	currentSort = classifyInfo.Sort

	var prevClassify *data_manage.BaseFromSmmClassify
	var nextClassify *data_manage.BaseFromSmmClassify
	//如果有传入 上一个兄弟节点分类id
	if prevClassifyId > 0 {
		prevClassify, err = data_manage.GetBaseFromSmmClassifyById(prevClassifyId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				errMsg = "移动失败"
				err = errors.New("上一个兄弟节点分类信息不存在" + err.Error())
				return
			}
			errMsg = "移动失败"
			err = errors.New("获取上一个兄弟节点分类信息失败,Err:" + err.Error())
			return
		}
		prevSort = prevClassify.Sort
	}
	if nextClassifyId > 0 {
		//下一个兄弟节点
		nextClassify, err = data_manage.GetBaseFromSmmClassifyById(nextClassifyId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				errMsg = "移动失败"
				err = errors.New("下一个兄弟节点分类信息不存在" + err.Error())
				return
			}
			errMsg = "移动失败"
			err = errors.New("获取下一个兄弟节点分类信息失败,Err:" + err.Error())
			return
		}
		nextSort = nextClassify.Sort
	}
	// 修改历史数据中的排序为0的情况
	if prevSort == 0 && nextSort == 0 { //目标是让当前分类处于目录的最顶部
		//更新为0排序的数据为当前最小排序
		if nextClassify != nil {
			minSort, e := data_manage.GetSmmIndexClassifyMinSort(parentClassifyId)
			if e != nil {
				errMsg = "移动失败"
				err = errors.New("获取下一个兄弟节点分类信息失败,Err:" + e.Error())
				return
			}
			if minSort > 1 {
				minSort -= 1
			}
			nextClassify.Sort = minSort
			err = nextClassify.Update([]string{"Sort"})
			if err != nil {
				errMsg = "移动失败"
				err = errors.New("更新下一个兄弟节点分类信息失败,Err:" + err.Error())
				return
			}
			nextSort = minSort
		}
	}
	//移到两个排序值中间操作
	if prevSort >= currentSort {
		//往下移动
		err = data_manage.MoveDownSmmIndexClassifyBySort(parentClassifyId, prevSort, currentSort)
		if err != nil {
			err = errors.New("向下移动出错:" + err.Error())
			return
		}
		classifyInfo.Sort = prevSort
	} else if nextSort <= currentSort && nextSort != 0 {
		//往上移动
		err = data_manage.MoveUpSmmIndexClassifyBySort(parentClassifyId, nextSort, currentSort)
		if err != nil {
			err = errors.New("向上移动出错:" + err.Error())
			return
		}
		classifyInfo.Sort = nextSort
	}
	classifyInfo.ModifyTime = time.Now()
	updateCol = append(updateCol, "Sort", "ModifyTime")
	err = classifyInfo.Update(updateCol)
	if err != nil {
		errMsg = "移动失败"
		err = errors.New("修改失败,Err:" + err.Error())
		return
	}
	return
}

// DelSmmClassify 删除SMM分类
func DelSmmClassify(classifyId int, sysUser *system.Admin) (err error, errMsg string) {
	//判断分类是否存在
	classifyInfo, err := data_manage.GetBaseFromSmmClassifyById(classifyId)
	if err != nil {
		errMsg = "删除失败"
		err = errors.New("获取分类信息失败,Err:" + err.Error())
		return
	}

	// 需要删除的分类id集合
	classifyIdList := make([]int, 0)
	classifyIdList = append(classifyIdList, classifyId)
	// 查找所有的子集id
	if classifyInfo.ParentId <= 0 {
		childrenClassifyInfoList, tmpErr := data_manage.GetBaseFromSmmClassifyByParentId(classifyId)
		if tmpErr != nil {
			errMsg = "删除失败"
			err = errors.New("获取分类信息失败,Err:" + tmpErr.Error())
			return
		}
		for _, v := range childrenClassifyInfoList {
			classifyIdList = append(classifyIdList, v.ClassifyId)
		}
	}

	// 获取分类下的所有指标
	count, err := data_manage.GetBaseFromSmmIndexCountByClassifyIds(classifyIdList)
	if err != nil {
		errMsg = "删除失败"
		err = errors.New("获取分类下的指标信息失败,Err:" + err.Error())
		return
	}

	if count > 0 {
		errMsg = "该分类下有指标，不可删除"
		err = errors.New("该分类下有指标，不可删除")
		return
	}

	// 删除对应的分类
	err = data_manage.DeleteSmmClassifyByClassifyId(classifyIdList)
	if err != nil {
		return
	}
	return
}

// MoveSmmData 移动SMM指标
func MoveSmmData(indexId, classifyId, prevIndexId, nextIndexId int) (err error, errMsg string) {
	//分类信息
	smmIndex, err := data_manage.GetBaseFromSmmIndexByIndexId(indexId)
	if err != nil {
		errMsg = `获取数据失败`
		if err.Error() == utils.ErrNoRow() {
			errMsg = `该指标未入库`
			err = nil
		}
		return
	}

	//判断分类是否存在
	if classifyId > 0 {
		_, err = data_manage.GetBaseFromSmmClassifyById(classifyId)
		if err != nil {
			errMsg = "移动失败"
			err = errors.New("获取分类信息失败,Err:" + err.Error())
			if err.Error() == utils.ErrNoRow() {
				errMsg = "找不到该分类"
				err = nil
			}
			return
		}
	}

	//如果改变了分类，那么移动该图表数据
	if smmIndex.ClassifyId != classifyId {
		tmpErr := data_manage.MoveBaseFromSmmIndex(indexId, classifyId)
		if tmpErr != nil {
			errMsg = "移动失败"
			err = errors.New("移动失败,Err:" + tmpErr.Error())
			return
		}
	}

	//移动排序
	updateCol := make([]string, 0)
	//如果有传入 上一个兄弟节点分类id
	if prevIndexId > 0 {
		prevIndex, tmpErr := data_manage.GetBaseFromSmmIndexByIndexId(prevIndexId)
		if tmpErr != nil {
			errMsg = "移动失败"
			err = errors.New("获取上一个兄弟节点指标信息失败,Err:" + tmpErr.Error())
			return
		}

		//如果是移动在两个兄弟节点之间
		if nextIndexId > 0 {
			//下一个兄弟节点
			nextIndex, tmpErr := data_manage.GetBaseFromSmmIndexByIndexId(nextIndexId)
			if tmpErr != nil {
				errMsg = "移动失败"
				err = errors.New("获取下一个兄弟节点指标信息失败,Err:" + tmpErr.Error())
				return
			}
			//如果上一个兄弟与下一个兄弟的排序权重是一致的，那么需要将下一个兄弟（以及下个兄弟的同样排序权重）的排序权重+2，自己变成上一个兄弟的排序权重+1
			if prevIndex.Sort == nextIndex.Sort || prevIndex.Sort == smmIndex.Sort {
				//变更兄弟节点的排序
				updateSortStr := `sort + 2`
				err = data_manage.UpdateBaseFromSmmIndexByClassifyId(prevIndex.ClassifyId, prevIndex.Sort, prevIndex.BaseFromSmmIndexId, updateSortStr)
				if err != nil {
					errMsg = "移动失败"
					err = errors.New("变更兄弟节点排序指标信息失败,Err:" + err.Error())
					return
				}
			} else {
				//如果下一个兄弟的排序权重正好是上个兄弟节点的下一层，那么需要再加一层了
				if nextIndex.Sort-prevIndex.Sort == 1 {
					//变更兄弟节点的排序
					updateSortStr := `sort + 1`
					err = data_manage.UpdateBaseFromSmmIndexByClassifyId(prevIndex.ClassifyId, prevIndex.Sort, prevIndex.BaseFromSmmIndexId, updateSortStr)
					if err != nil {
						errMsg = "移动失败"
						err = errors.New("变更兄弟节点排序指标信息失败,Err:" + err.Error())
						return
					}
				}
			}
		}

		smmIndex.Sort = prevIndex.Sort + 1
		smmIndex.ModifyTime = time.Now()
		updateCol = append(updateCol, "Sort", "ModifyTime")

	} else {
		firstClassify, tmpErr := data_manage.GetFirstBaseFromSmmIndexByClassifyId(classifyId)
		if tmpErr != nil && tmpErr.Error() != utils.ErrNoRow() {
			errMsg = "移动失败"
			err = errors.New("获取获取当前父级分类下的排序第一条的分类信息失败,Err:" + tmpErr.Error())
			return
		}

		//如果该分类下存在其他分类，且第一个其他分类的排序等于0，那么需要调整排序
		if firstClassify != nil && firstClassify.Sort == 0 {
			updateSortStr := ` sort + 1 `
			_ = data_manage.UpdateBaseFromSmmIndexByClassifyId(firstClassify.ClassifyId, 0, firstClassify.BaseFromSmmIndexId-1, updateSortStr)
		}

		smmIndex.Sort = 0 //那就是排在第一位
		smmIndex.ModifyTime = time.Now()
		updateCol = append(updateCol, "Sort", "ModifyTime")
	}

	//更新
	if len(updateCol) > 0 {
		err = smmIndex.Update(updateCol)
		if err != nil {
			errMsg = "移动失败"
			err = errors.New("修改失败,Err:" + err.Error())
			return
		}
	}

	return
}

// MoveSmmData2 移动SMM指标
func MoveSmmData2(indexId, classifyId, prevIndexId, nextIndexId int) (err error, errMsg string) {
	//分类信息
	smmIndex, err := data_manage.GetBaseFromSmmIndexByIndexId(indexId)
	if err != nil {
		errMsg = `获取数据失败`
		if err.Error() == utils.ErrNoRow() {
			errMsg = `该指标未入库`
			err = nil
		}
		return
	}

	//判断分类是否存在
	if classifyId > 0 {
		_, err = data_manage.GetBaseFromSmmClassifyById(classifyId)
		if err != nil {
			errMsg = "移动失败"
			err = errors.New("获取分类信息失败,Err:" + err.Error())
			if err.Error() == utils.ErrNoRow() {
				errMsg = "找不到该分类"
				err = nil
			}
			return
		}
	}

	//如果改变了分类，那么移动该图表数据
	if smmIndex.ClassifyId != classifyId {
		tmpErr := data_manage.MoveBaseFromSmmIndex(indexId, classifyId)
		if tmpErr != nil {
			errMsg = "移动失败"
			err = errors.New("移动失败,Err:" + tmpErr.Error())
			return
		}
	}

	//移动排序
	updateCol := make([]string, 0)
	var currentSort, prevSort, nextSort int
	currentSort = smmIndex.Sort
	//如果有传入 上一个兄弟节点分类id
	var prevIndex *data_manage.BaseFromSmmIndex
	var nextIndex *data_manage.BaseFromSmmIndex
	if prevIndexId > 0 {
		prevIndex, err = data_manage.GetBaseFromSmmIndexByIndexId(prevIndexId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				errMsg = "移动失败"
				err = errors.New("上一个兄弟节点指标信息不存在" + err.Error())
				return
			}
			errMsg = "移动失败"
			err = errors.New("获取上一个兄弟节点指标信息失败,Err:" + err.Error())
			return
		}
		prevSort = prevIndex.Sort
	}

	if nextIndexId > 0 {
		//下一个兄弟节点
		nextIndex, err = data_manage.GetBaseFromSmmIndexByIndexId(nextIndexId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				errMsg = "移动失败"
				err = errors.New("下一个兄弟节点指标信息不存在" + err.Error())
				return
			}
			errMsg = "移动失败"
			err = errors.New("获取下一个兄弟节点指标信息失败,Err:" + err.Error())
			return
		}
		nextSort = nextIndex.Sort
	}

	// 修改历史数据中的排序为0的情况
	if prevSort == 0 && nextSort == 0 { //目标是让当前分类处于目录的最顶部, 但是历史数据里下个节点的sort为0的情况
		//更新为0排序的数据为当前最小排序
		if nextIndex != nil {
			minSort, e := data_manage.GetBaseFromSmmIndexMinSortByClassifyId(classifyId)
			if e != nil {
				errMsg = "移动失败"
				err = errors.New("获取下一个兄弟节点分类信息失败,Err:" + e.Error())
				return
			}
			if minSort > 1 {
				minSort -= 1
			}
			nextIndex.Sort = minSort
			err = nextIndex.Update([]string{"Sort"})
			if err != nil {
				errMsg = "移动失败"
				err = errors.New("更新下一个兄弟节点分类信息失败,Err:" + err.Error())
				return
			}
			nextSort = minSort
		}
	}
	//移到两个排序值中间操作
	if prevSort >= currentSort {
		//往下移动
		err = data_manage.MoveDownSmmIndexBySort(classifyId, prevSort, currentSort)
		if err != nil {
			err = errors.New("向下移动出错:" + err.Error())
			return
		}
		smmIndex.Sort = prevSort
	} else if nextSort <= currentSort && nextSort != 0 {
		//往上移动
		err = data_manage.MoveUpSmmIndexBySort(classifyId, nextSort, currentSort)
		if err != nil {
			err = errors.New("向上移动出错:" + err.Error())
			return
		}
		smmIndex.Sort = nextSort
	}

	//更新
	smmIndex.ModifyTime = time.Now()
	updateCol = append(updateCol, "Sort", "ModifyTime")
	err = smmIndex.Update(updateCol)
	if err != nil {
		errMsg = "移动失败"
		err = errors.New("修改失败,Err:" + err.Error())
		return
	}
	return
}

// EditSmmIndex 编辑SMM指标
func EditSmmIndex(indexId, classifyId int, sysUser *system.Admin) (baseFromSmmIndex *data_manage.BaseFromSmmIndex, err error, errMsg string) {
	baseFromSmmIndex, err = data_manage.GetBaseFromSmmIndexByIndexId(indexId)
	if err != nil {
		errMsg = `获取数据失败`
		if err.Error() == utils.ErrNoRow() {
			errMsg = `该指标未入库`
			err = nil
		}
		return
	}

	baseFromSmmIndex.ClassifyId = classifyId
	baseFromSmmIndex.ModifyTime = time.Now()
	err = baseFromSmmIndex.Update([]string{"ClassifyId", "ModifyTime"})
	if err != nil {
		errMsg = "保存分类失败"
	}

	return
}

func InitBaseFromSmmClassify() (err error) {
	//查询历史数据所有分类
	typeList, err := data_manage.GetBaseFromSmmIndexType()
	if err != nil {
		return
	}
	classifyList := make([]*data_manage.BaseFromSmmClassify, 0)
	classifyMap := make(map[string][]string, 0)
	parentClassifyMap := make(map[string]struct{}, 0)
	now := time.Now()
	for _, v := range typeList {
		if _, ok := parentClassifyMap[v.Type2]; !ok {
			parentClassifyMap[v.Type2] = struct{}{}
			tmp := new(data_manage.BaseFromSmmClassify)
			tmp.ClassifyName = v.Type2
			tmp.Level = 1
			tmp.ModifyTime = now
			tmp.CreateTime = now
			classifyList = append(classifyList, tmp)
		}
		classifyMap[v.Type2] = append(classifyMap[v.Type2], v.Type3)
	}
	//添加一级分类
	err = data_manage.AddSmmClassifyMulti(classifyList)
	if err != nil {
		err = errors.New("新增分类出错:" + err.Error())
		return
	}
	//查询分类表的所有父级
	rootList, err := data_manage.GetBaseFromSmmClassifyByParentId(0)
	if err != nil {
		return
	}
	classifyIdMap := make(map[string]int)
	for _, v := range rootList {
		classifyIdMap[v.ClassifyName] = v.ClassifyId
	}
	classifyList2 := make([]*data_manage.BaseFromSmmClassify, 0)
	for _, v := range typeList {
		if parentId, ok := classifyIdMap[v.Type2]; ok {
			tmp := new(data_manage.BaseFromSmmClassify)
			tmp.ParentId = parentId
			tmp.ClassifyName = v.Type3
			tmp.Level = 2
			tmp.ModifyTime = now
			tmp.CreateTime = now
			classifyList2 = append(classifyList2, tmp)
		}
	}
	//添加二级分类
	err = data_manage.AddSmmClassifyMulti(classifyList2)
	if err != nil {
		err = errors.New("新增二级分类出错:" + err.Error())
		return
	}
	//初始化sort字段
	err = data_manage.InitSmmClassifySort()
	if err != nil {
		return
	}
	//更新index表里的分类id
	err = data_manage.InitSmmIndexClassifyId()
	return
}

// DelSmmData 删除SMM指标
func DelSmmData(indexId int) (err error, errMsg string) {
	baseFromSmmIndex, err := data_manage.GetBaseFromSmmIndexByIndexId(indexId)
	if err != nil {
		errMsg = `获取数据失败`
		if err.Error() == utils.ErrNoRow() {
			errMsg = `该指标未入库`
			err = nil
		}
		return
	}

	// 获取已经加入到EDB指标库的Smm指标
	edbInfo, err := data_manage.GetEdbInfoByEdbCode(utils.DATA_SOURCE_YS, baseFromSmmIndex.IndexCode)
	if err != nil && err.Error() != utils.ErrNoRow() {
		errMsg = "删除失败"
		err = errors.New("获取分类下的指标信息失败,Err:" + err.Error())
		return
	}
	if edbInfo != nil {
		errMsg = "当前指标已被引用，不可删除"
		err = nil
		return
	}

	// 删除对应的分类和指标
	err = data_manage.DeleteBaseFromSmmIndexById(indexId)
	if err != nil {
		return
	}

	return
}

// ResetSmmData 指标数据清除分类接口
func ResetSmmData(indexId int) (err error, errMsg string) {
	smmIndex, err := data_manage.GetBaseFromSmmIndexByIndexId(indexId)
	if err != nil {
		errMsg = `获取数据失败`
		if err.Error() == utils.ErrNoRow() {
			errMsg = `该指标未入库`
			err = nil
		}
		return
	}

	// 更新指标在未分类下的排序，永远排在未分类的最后一个
	//移动排序
	classifyId := 0
	updateCol := make([]string, 0)
	var currentSort, prevSort int
	currentSort = smmIndex.Sort
	//未分类的最大的sort值
	prevSort, err = data_manage.GetBaseFromSmmIndexMaxSortByClassifyId(classifyId)
	if err != nil {
		errMsg = "移动失败"
		err = errors.New("获取上一个兄弟节点指标信息失败,Err:" + err.Error())
		return
	}

	//如果前面一个节点的sort值比当前大，则当前节点往下移动
	if prevSort >= currentSort {
		//往下移动
		err = data_manage.MoveDownSmmIndexBySort(classifyId, prevSort, currentSort)
		if err != nil {
			err = errors.New("向下移动出错:" + err.Error())
			return
		}
		smmIndex.Sort = prevSort
	}

	//更新
	smmIndex.ModifyTime = time.Now()
	smmIndex.ClassifyId = classifyId
	updateCol = append(updateCol, "Sort", "ModifyTime", "ClassifyId")
	err = smmIndex.Update(updateCol)
	if err != nil {
		errMsg = "移动失败"
		err = errors.New("修改失败,Err:" + err.Error())
		return
	}
	return
}
