package eta_forum

import (
	"encoding/json"
	"eta/eta_mobile/models/data_manage"
	"eta/eta_mobile/utils"
	"fmt"
)

// ChartClassifySave 上传图表分类信息
func ChartClassifySave(chartClassifyId int) (err error) {
	if utils.BusinessCode == "" || (utils.BusinessCode != utils.BusinessCodeRelease && utils.BusinessCode != utils.BusinessCodeDebug && utils.BusinessCode != utils.BusinessCodeSandbox) {
		return
	}
	//查询分类信息
	chartClassifyInfo, err := data_manage.GetChartClassifyById(chartClassifyId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			err = fmt.Errorf("分类不存在")
			return
		}
		err = fmt.Errorf("获取分类信息失败,Err:" + err.Error())
		return
	}
	if chartClassifyInfo.IsSelected != utils.ChartClassifyIsSelected {
		return
	}

	reqJson, err := json.Marshal(chartClassifyInfo) 
	if err != nil {
		err = fmt.Errorf("参数解析异常,Err:" + err.Error())
		return
	}
	respItem, err := ChartClassifySaveLib(string(reqJson))
	if err != nil {
		err = fmt.Errorf("上传图表分类信息失败,Err:" + err.Error())
		return
	}
	if respItem.Ret != 200 {
		err = fmt.Errorf("上传图表分类信息失败,Err:%v,errMsg:%v", respItem.Msg, respItem.ErrMsg)
		return
	}
	return
}

type ChartClassifySaveBatchReq struct {
	List []*data_manage.ChartClassify
}

//批量上传图表分类信息
func ChartClassifySaveBatch(source int) (err error) {
	if utils.BusinessCode == "" || (utils.BusinessCode != utils.BusinessCodeRelease && utils.BusinessCode != utils.BusinessCodeDebug && utils.BusinessCode != utils.BusinessCodeSandbox) {
		return
	}

	//查询分类信息
	chartClassifyList, err := data_manage.GetChartClassifyInfoSelectedBySource(source)
	if err != nil {
		err = fmt.Errorf("获取分类信息失败,Err:" + err.Error())
		return
	}
	req := ChartClassifySaveBatchReq{
		List: chartClassifyList,
	}
	reqJson, err := json.Marshal(req)
	if err != nil {
		err = fmt.Errorf("参数解析异常,Err:" + err.Error())
		return
	}
	respItem, err := ChartClassifySaveBatchLib(string(reqJson))
	if err != nil {
		err = fmt.Errorf("上传图表分类信息失败,Err:" + err.Error())
		return
	}	
	if respItem.Ret != 200 {
		err = fmt.Errorf("上传图表分类信息失败,Err:%v,errMsg:%v", respItem.Msg, respItem.ErrMsg)
		return
	}
	return
}


type DeleteChartReq struct {
	ChartInfoId int `description:"图表id"`
}

// DeleteChart 上传图表接口
func DeleteChartByForumChartInfoId(forumChartInfoId int) (err error, errMsg string) {
	// 查询图表信息
	req := new(DeleteChartReq)
	req.ChartInfoId = forumChartInfoId

	// 添加计算指标
	reqJson, err := json.Marshal(req)
	if err != nil {
		errMsg = "参数解析异常"
		err = fmt.Errorf("参数解析异常,Err:" + err.Error())
		return
	}
	respItem, err := ChartDeleteLib(string(reqJson))
	if err != nil {
		errMsg = "撤回失败"
		err = fmt.Errorf("撤回失败,Err:" + err.Error())
		return
	}
	if respItem.Ret != 200 {
		errMsg = "撤回失败"
		err = fmt.Errorf(respItem.ErrMsg)
		return
	}

	return
}