package data

import (
	"eta/eta_api/models/data_manage"
	"eta/eta_api/services/elastic"
	"eta/eta_api/utils"
	"fmt"
	"strconv"
	"strings"
)

func CreateChartInfoIndex() {
	indexName := utils.CHART_INDEX_NAME
	mappingJson := `{
  "mappings": {
    "dynamic": true,
    "properties": {
      "ChartInfoId": {
        "type": "integer"
      },
      "ChartName": {
        "type": "text",
        "term_vector": "with_positions_offsets",
        "analyzer": "ik_smart"
      },
      "ChartClassifyId": {
        "type": "integer"
      },
      "SysUserId": {
        "type": "integer"
      },
      "SysUserRealName": {
        "type": "text",
        "term_vector": "with_positions_offsets",
        "analyzer": "ik_smart"
      },
      "UniqueCode": {
        "type": "text",
        "term_vector": "with_positions_offsets"
      },
      "Unit": {
        "type": "text",
        "term_vector": "with_positions_offsets"
      },
      "CreateTime": {
        "type": "date"
      },
      "ModifyTime": {
        "type": "date"
      },
      "DateType": {
        "type": "integer"
      },
      "StartDate": {
        "type": "text",
        "term_vector": "with_positions_offsets"
      },
      "EndDate": {
        "type": "text",
        "term_vector": "with_positions_offsets"
      },
      "IsSetName": {
        "type": "integer"
      },
      "EdbInfoIds": {
        "type": "text",
        "term_vector": "with_positions_offsets"
      },
      "ChartType": {
        "type": "integer"
      },
      "Calendar": {
        "type": "text",
        "term_vector": "with_positions_offsets"
      },
      "ChartImage": {
        "type": "text",
        "term_vector": "with_positions_offsets"
      }
    }
  }
}`
	elastic.EsCreateIndex(indexName, mappingJson)
}

func AddAllChartInfo() {
	allList, err := data_manage.GetChartInfoAllList()
	if err != nil {
		fmt.Println("GetArticleAll Err:", err.Error())
		return
	}
	total := len(allList)
	for k, v := range allList {
		EsAddOrEditChartInfo(v.ChartInfoId)
		//fmt.Println(v.ChartInfoId)
		fmt.Println("剩余", total-k-1, "条数据,当前图表id:", v.ChartInfoId)
	}
}

// EsAddOrEditChartInfo 新增和修改ES中的图表数据
func EsAddOrEditChartInfo(chartInfoId int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println("新增和修改ES中的图表数据失败:", err.Error())
		}
	}()
	itemInfo, _ := data_manage.GetChartInfoById(chartInfoId)
	//添加es
	err = elastic.EsAddOrEditChartInfoData(utils.CHART_INDEX_NAME, strconv.Itoa(itemInfo.ChartInfoId), itemInfo)
	return
}

// EsDeleteChartInfo 删除ES中的图表数据
func EsDeleteChartInfo(chartInfoId int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println("删除ES中的图表数据失败:", err.Error())
		}
	}()
	//添加es
	err = elastic.EsDeleteDataV2(utils.CHART_INDEX_NAME, strconv.Itoa(chartInfoId))
	return
}

// EsSearchChartInfo 搜索图表信息
func EsSearchChartInfo(keyword string, showSysId int, sourceList []int, noPermissionChartIdList []int, startSize, pageSize int) (list []*data_manage.ChartInfo, total int64, err error) {
	list, total, err = elastic.SearchChartInfoData(utils.CHART_INDEX_NAME, keyword, showSysId, sourceList, noPermissionChartIdList, startSize, pageSize)
	return
}

// AddAllMyChartInfo 添加所有的我的图库数据
func AddAllMyChartInfo() {
	errMsg := make([]string, 0)
	defer func() {
		if len(errMsg) > 0 {
			fmt.Println("新增和修改ES中的图表数据失败:", strings.Join(errMsg, "\n"))
		}
	}()
	var condition string
	var pars []interface{}

	allList, err := data_manage.GetMyChartListGroupByCharyInfoIdAndAdminIdByCondition(condition, pars)
	if err != nil {
		fmt.Println("AddAllMyChartInfo Err:", err.Error())
		return
	}

	for _, v := range allList {
		//添加es
		err = elastic.EsAddOrEditDataInterface(utils.MY_CHART_INDEX_NAME, strconv.Itoa(v.MyChartId), v)
		if err != nil {
			errMsg = append(errMsg, fmt.Sprintf("myChartId:%d,添加Es失败,err:%s", v.MyChartId, err.Error()))
		}
	}
}

// EsAddOrEditMyChartInfoByChartInfoId 根据图表id 新增和修改ES中的图表数据
func EsAddOrEditMyChartInfoByChartInfoId(chartInfoId int) {
	errMsg := make([]string, 0)
	defer func() {
		if len(errMsg) > 0 {
			fmt.Println("新增和修改ES中的图表数据失败:", strings.Join(errMsg, "\n"))
		}
	}()

	var condition string
	var pars []interface{}
	condition += " and a.chart_info_id = ? "
	pars = append(pars, chartInfoId)

	allList, err := data_manage.GetMyChartListGroupByCharyInfoIdAndAdminIdByCondition(condition, pars)
	if err != nil {
		errMsg = append(errMsg, fmt.Sprintf("EsAddOrEditMyChartInfoByChartInfoId Err:%s", err.Error()))
		return
	}
	for _, v := range allList {
		//添加es
		err = elastic.EsAddOrEditDataInterface(utils.MY_CHART_INDEX_NAME, strconv.Itoa(v.MyChartId), v)
		if err != nil {
			errMsg = append(errMsg, fmt.Sprintf("myChartId:%d,添加Es失败,err:%s", v.MyChartId, err.Error()))
		}

	}
	return
}

// EsDeleteMyChartInfoByChartInfoId 根据图表id 删除ES中的图表数据
func EsDeleteMyChartInfoByChartInfoId(chartInfoId int) {
	errMsg := make([]string, 0)
	defer func() {
		if len(errMsg) > 0 {
			fmt.Println("新增和修改ES中的图表数据失败:", strings.Join(errMsg, "\n"))
		}
	}()

	var condition string
	var pars []interface{}
	condition += " AND a.chart_info_id = ? "
	pars = append(pars, chartInfoId)

	allList, err := data_manage.GetMyChartListGroupByCharyInfoIdAndAdminIdByCondition(condition, pars)
	if err != nil {
		errMsg = append(errMsg, fmt.Sprintf("AddAllMyChartInfo Err:%s", err.Error()))
		return
	}
	for _, v := range allList {
		//删除es
		err = elastic.EsDeleteDataV2(utils.MY_CHART_INDEX_NAME, strconv.Itoa(v.MyChartId))
		if err != nil {
			errMsg = append(errMsg, fmt.Sprintf("myChartId:%d,删除Es失败,err:%s", v.MyChartId, err.Error()))
		}
	}
	return
}

// EsAddOrEditMyChartInfoByMyChartId 根据我的图库id 新增和修改ES中的图表数据
func EsAddOrEditMyChartInfoByMyChartId(myChartId int) {
	errMsg := make([]string, 0)
	defer func() {
		if len(errMsg) > 0 {
			fmt.Println("新增和修改ES中的图表数据失败:", strings.Join(errMsg, "\n"))
		}
	}()

	var condition string
	var pars []interface{}
	condition += " AND a.my_chart_id = ? "
	pars = append(pars, myChartId)

	allList, err := data_manage.GetMyChartListGroupByCharyInfoIdAndAdminIdByCondition(condition, pars)
	if err != nil {
		errMsg = append(errMsg, fmt.Sprintf("EsAddOrEditMyChartInfoByMyChartId Err:%s", err.Error()))
		return
	}
	for _, v := range allList {
		//添加es
		err = elastic.EsAddOrEditDataInterface(utils.MY_CHART_INDEX_NAME, strconv.Itoa(v.MyChartId), v)
		if err != nil {
			errMsg = append(errMsg, fmt.Sprintf("myChartId:%d,添加Es失败,err:%s", v.MyChartId, err.Error()))
		}
	}
	return
}

// EsDeleteMyChartInfoByMyChartId 根据我的图库id 删除ES中的图表数据
func EsDeleteMyChartInfoByMyChartId(myChartId int) {
	var err error
	defer func() {
		if err != nil {
			fmt.Println("删除ES中的图表数据失败:", err.Error())
		}
	}()
	//添加es
	err = elastic.EsDeleteDataV2(utils.MY_CHART_INDEX_NAME, strconv.Itoa(myChartId))
	return
}

// EsSearchMyChartInfo 搜索图表信息
func EsSearchMyChartInfo(keyword string, adminId int, noPermissionChartIdList []int, startSize, pageSize int) (list []*data_manage.MyChartList, total int64, err error) {
	list, total, err = elastic.SearchMyChartInfoData(utils.MY_CHART_INDEX_NAME, keyword, adminId, noPermissionChartIdList, startSize, pageSize)
	return
}

// EsDeleteMyChartInfoByMyChartIds 根据我的图表IDs删除ES中的我的图表
func EsDeleteMyChartInfoByMyChartIds(ids []int) {
	if len(ids) == 0 {
		return
	}
	errMsg := make([]string, 0)
	defer func() {
		if len(errMsg) > 0 {
			fmt.Println("EsDeleteMyChartInfoByMyChartIds, 删除ES中的我的图表数据失败:", strings.Join(errMsg, "\n"))
		}
	}()
	for _, v := range ids {
		id := strconv.Itoa(v)
		if e := elastic.EsDeleteDataV2(utils.MY_CHART_INDEX_NAME, id); e != nil {
			errMsg = append(errMsg, fmt.Sprintf("myChartId:%d,删除Es失败,err:%s", v, e.Error()))
		}
	}
	return
}