package egg_energy

import (
	"applet/app/db"
	"applet/app/e"
	md "applet/app/md/institutional_management/egg_energy"
	"applet/app/utils"
	"code.fnuoos.com/EggPlanet/egg_models.git/src/implement"
	"code.fnuoos.com/EggPlanet/egg_models.git/src/model"
	"code.fnuoos.com/EggPlanet/egg_system_rules.git/rule/egg_energy/enum"
	md2 "code.fnuoos.com/EggPlanet/egg_system_rules.git/rule/egg_energy/md"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

// GetVirtualCoinList
// @Summary      制度中心-蛋蛋能量-查询所有币种(获取)
// @Tags         蛋蛋能量
// @Description  查询所有币种(获取)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Success      200   {object}  []md.VirtualCoin	"成功返回"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/eggEnergy/getVirtualCoinList [get]
func GetVirtualCoinList(c *gin.Context) {
	virtualCoinDb := implement.NewVirtualCoinDb(db.Db)
	coins, err := virtualCoinDb.VirtualCoinFindAll()
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	list := make([]md.VirtualCoin, len(coins))
	for i, coin := range coins {
		list[i] = md.VirtualCoin{
			Id:            coin.Id,
			Name:          coin.Name,
			ExchangeRatio: coin.ExchangeRatio,
			IsUse:         coin.IsUse,
			CreateAt:      coin.CreateAt,
			UpdateAt:      coin.UpdateAt,
		}
	}

	e.OutSuc(c, list, nil)

}

// BatchAddVirtualCoins
// @Summary      制度中心-蛋蛋能量-批量新增币种
// @Tags         蛋蛋能量
// @Description  批量新增币种
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body	md.BatchAddVirtualCoinsReq 	true  "新增数据信息"
// @Success      200   {int} 	"新增数据数量"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/eggEnergy/batchAddVirtualCoins [POST]
func BatchAddVirtualCoins(c *gin.Context) {
	var req *md.BatchAddVirtualCoinsReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}
	now := time.Now()
	coins := make([]model.VirtualCoin, len(req.List))
	for i, node := range req.List {
		coins[i].Name = node.Name
		coins[i].ExchangeRatio = node.ExchangeRatio
		coins[i].IsUse = node.IsUse
		coins[i].CreateAt = now.Format("2006-01-02 15:04:05")
		coins[i].UpdateAt = now.Format("2006-01-02 15:04:05")
	}

	coinDb := implement.NewVirtualCoinDb(db.Db)
	affected, err := coinDb.VirtualCoinBatchAdd(coins)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	e.OutSuc(c, affected, nil)
	return
}

// UpdateVirtualCoin
// @Summary      制度中心-蛋蛋能量-更新币种信息
// @Tags         蛋蛋能量
// @Description  更新币种信息
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body	md.UpdateVirtualCoinReq 	true  "更新数据信息"
// @Success      200   {int} 	"更新数据数量"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/eggEnergy/updateVirtualCoin [POST]
func UpdateVirtualCoin(c *gin.Context) {
	var req *md.UpdateVirtualCoinReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}

	coinDb := implement.NewVirtualCoinDb(db.Db)
	coin, err := coinDb.VirtualCoinGetOneByParams(map[string]interface{}{
		"key":   "id",
		"value": req.Id,
	})
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	if coin == nil {
		e.OutErr(c, e.ERR_NO_DATA, errors.New("该币种不存在"))
		return
	}

	m := model.VirtualCoin{
		Id:            req.Id,
		Name:          req.Name,
		ExchangeRatio: req.ExchangeRatio,
		IsUse:         req.IsUse,
	}
	forceColumns := []string{"is_use"}
	affected, err := coinDb.VirtualCoinUpdate(&m, forceColumns...)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	e.OutSuc(c, affected, nil)
}

// DeleteVirtualCoin
// @Summary    	 制度中心-蛋蛋能量-删除币种
// @Tags         蛋蛋能量
// @Description  删除币种
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Accept       json
// @Produce      json
// @Success      200   {int}		   "删除数据数量"
// @Failure      400   {object}   md.Response              "具体错误"
// @Router       /api/institutionalManagement/eggEnergy/deleteVirtualCoin/{$id} [DELETE]
func DeleteVirtualCoin(c *gin.Context) {
	id := c.Param("id")

	coinDb := implement.NewVirtualCoinDb(db.Db)
	affected, err := coinDb.VirtualCoinDelete(id)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	e.OutSuc(c, affected, nil)
}

// GetEggEnergyBasic
// @Summary      制度中心-蛋蛋能量-基础设置(获取)
// @Tags         蛋蛋能量
// @Description  基础设置(获取)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Success      200   {object}   md.GetEggEnergyBasicResp  	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/eggEnergy/getBasic [get]
func GetEggEnergyBasic(c *gin.Context) {
	basicSettingDb := implement.NewEggEnergyBasicSettingDb(db.Db)
	basicSettings, err1 := basicSettingDb.EggEnergyBasicSettingGetOne()
	if err1 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err1.Error())
		return
	}
	if basicSettings == nil {
		e.OutErr(c, e.ERR_NO_DATA, errors.New("未能获取基础设置"))
		return
	}

	var videoRewardSystem md2.VideoRewardSystemStruct
	utils.Unserialize([]byte(basicSettings.VideoRewardSystem), &videoRewardSystem)

	var destructionSetting md2.DestructionSettingStruct
	utils.Unserialize([]byte(basicSettings.DestructionSetting), &destructionSetting)

	var priceSetting md2.PriceSettingStruct
	utils.Unserialize([]byte(basicSettings.PriceSetting), &priceSetting)

	var exchangeRules md2.ExchangeRulesStruct
	utils.Unserialize([]byte(basicSettings.ExchangeRules), &exchangeRules)

	var rewardSystem []md2.RewardSystemStruct
	utils.Unserialize([]byte(basicSettings.RewardSystem), &rewardSystem)

	var newUserRewardRules md2.NewUserRewardRules
	utils.Unserialize([]byte(basicSettings.NewUserIncentiveRules), &newUserRewardRules)

	var directPushReward md2.DirectPushRewardSettingStruct
	utils.Unserialize([]byte(basicSettings.DirectPushReward), &directPushReward)

	resp := md.GetEggEnergyBasicResp{
		BasicSetting: md.BasicSetting{
			IsOpen:                basicSettings.IsOpen,
			PersonEggEnergyCoinId: basicSettings.PersonEggEnergyCoinId,
			TeamEggEnergyCoinId:   basicSettings.TeamEggEnergyCoinId,
			PersonEggPointsCoinId: basicSettings.PersonEggPointsCoinId,
			TeamEggPointsCoinId:   basicSettings.TeamEggPointsCoinId,
			DirectPushReward: md2.DirectPushRewardSettingStruct{
				RewardRateValue:               directPushReward.RewardRateValue,
				MemberSelfIsOpenGetTeamReward: directPushReward.MemberSelfIsOpenGetTeamReward,
			},
		},
		VideoRewardSetting: md.VideoRewardSetting{
			VideoRewardIsOpen: basicSettings.VideoRewardIsOpen,
			VideoRewardSystem: md2.VideoRewardSystemStruct{
				RewardValue:     videoRewardSystem.RewardValue,
				RewardTotalNum:  videoRewardSystem.RewardTotalNum,
				IntervalMinutes: videoRewardSystem.IntervalMinutes,
				EachRoundHour:   videoRewardSystem.EachRoundHour,
			},
		},
		DataSetting: md.DataSetting{
			TotalIssuanceAmount:        basicSettings.TotalIssuanceAmount,
			TotalTechnologyTeam:        basicSettings.TotalTechnologyTeam,
			TotalAngelInvestor:         basicSettings.TotalAngelInvestor,
			TotalOperateFund:           basicSettings.TotalOperateFund,
			TotalEcologicalDevelopment: basicSettings.TotalEcologicalDevelopment,
			TotalTeamDividends:         basicSettings.TotalTeamDividends,
			TotalUserForPerson:         basicSettings.TotalUserForPerson,
			TotalUserForTeam:           basicSettings.TotalUserForTeam,
		},
		DestructionSetting:    destructionSetting,
		PriceSetting:          priceSetting,
		ExchangeRules:         exchangeRules,
		RewardSystem:          rewardSystem,
		NewUserIncentiveRules: newUserRewardRules,
		SystemID:              basicSettings.Id,
	}

	e.OutSuc(c, resp, nil)
}

// UpdateEggEnergyBasic
// @Summary      制度中心-蛋蛋能量-基础设置(更新)
// @Tags         蛋蛋能量
// @Description  基础设置(更新)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body	md.UpdateEggEnergyBasicReq 	true  "system_id 必填"
// @Success      200   {int}   	"修改数据条数"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/eggEnergy/updateBasic [post]
func UpdateEggEnergyBasic(c *gin.Context) {
	var req *md.UpdateEggEnergyBasicReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}

	destructionSettingStr := utils.SerializeStr(req.DestructionSetting)
	priceSettingStr := utils.SerializeStr(req.PriceSetting)
	videoRewardSystemStr := utils.SerializeStr(req.VideoRewardSetting.VideoRewardSystem)
	exchangeRulesStr := utils.SerializeStr(req.ExchangeRules)
	rewardSystemStr := utils.SerializeStr(req.RewardSystem)
	newUserIncentiveRulesStr := utils.SerializeStr(req.NewUserIncentiveRules)
	directPushRewardStr := utils.SerializeStr(req.BasicSetting.DirectPushReward)

	m := model.EggEnergyBasicSetting{
		Id:                         req.SystemID,
		IsOpen:                     req.BasicSetting.IsOpen,
		PersonEggEnergyCoinId:      req.BasicSetting.PersonEggEnergyCoinId,
		TeamEggEnergyCoinId:        req.BasicSetting.TeamEggEnergyCoinId,
		PersonEggPointsCoinId:      req.BasicSetting.PersonEggPointsCoinId,
		TeamEggPointsCoinId:        req.BasicSetting.TeamEggPointsCoinId,
		TotalIssuanceAmount:        req.DataSetting.TotalIssuanceAmount,
		TotalTechnologyTeam:        req.DataSetting.TotalTechnologyTeam,
		TotalAngelInvestor:         req.DataSetting.TotalAngelInvestor,
		TotalOperateFund:           req.DataSetting.TotalOperateFund,
		TotalEcologicalDevelopment: req.DataSetting.TotalEcologicalDevelopment,
		TotalUserForPerson:         req.DataSetting.TotalUserForPerson,
		TotalUserForTeam:           req.DataSetting.TotalUserForTeam,
		DestructionSetting:         destructionSettingStr,
		DirectPushReward:           directPushRewardStr,
		PriceSetting:               priceSettingStr,
		VideoRewardIsOpen:          req.VideoRewardSetting.VideoRewardIsOpen,
		VideoRewardSystem:          videoRewardSystemStr,
		ExchangeRules:              exchangeRulesStr,
		RewardSystem:               rewardSystemStr,
		NewUserIncentiveRules:      newUserIncentiveRulesStr,
		TotalTeamDividends:         req.DataSetting.TotalTeamDividends,
	}

	forceColums := []string{"is_open", "video_reward_is_open"}
	energyBasicSettingDb := implement.NewEggEnergyBasicSettingDb(db.Db)
	session := db.Db.NewSession()
	defer session.Close()
	affected, err := energyBasicSettingDb.EggEnergyBasicSettingUpdate(session, req.SystemID, &m, forceColums...)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	e.OutSuc(c, affected, nil)
}

// GetEggEnergyVipSetting
// @Summary      制度中心-蛋蛋能量-基础会员设置(获取)
// @Tags         蛋蛋能量
// @Description  基础会员设置(获取)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Success      200   {object}   md.GetEggEnergyVipSettingResp  	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/eggEnergy/getVipSetting [get]
func GetEggEnergyVipSetting(c *gin.Context) {
	basicSettingDb := implement.NewEggEnergyBasicSettingDb(db.Db)
	basicSettings, err1 := basicSettingDb.EggEnergyBasicSettingGetOne()
	if err1 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err1.Error())
		return
	}
	if basicSettings == nil {
		e.OutErr(c, e.ERR_NO_DATA, errors.New("未能获取基础设置"))
		return
	}

	var vipEquitySetting []md2.VipEquitySettingStruct
	utils.Unserialize([]byte(basicSettings.VipEquitySetting), &vipEquitySetting)

	levelDb := implement.NewUserLevelDb(db.Db)
	levels, err1 := levelDb.UserLevelAllByAsc()
	if err1 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err1.Error())
		return
	}
	levelsList := make([]map[string]interface{}, 0)
	levelsMap := make(map[int]string)
	for _, level := range levels {
		levelsList = append(levelsList, map[string]interface{}{
			"id":   level.Id,
			"name": level.LevelName,
		})
		levelsMap[level.Id] = level.LevelName
	}

	list := make([]md.VipEquitySettingNode, len(vipEquitySetting))
	for i, settingStruct := range vipEquitySetting {
		list[i].VipLevelName = levelsMap[utils.StrToInt(settingStruct.VipLevelId)]
		list[i].ExchangeAccountBalanceFee = settingStruct.ExchangeAccountBalanceFee
		list[i].DividendRatio = settingStruct.DividendRatio
		list[i].VipLevelID = settingStruct.VipLevelId
	}

	resp := md.GetEggEnergyVipSettingResp{
		LevelList: levelsList,
		List:      list,
	}

	e.OutSuc(c, resp, nil)
}

// AddEggEnergyVipSetting
// @Summary      制度中心-蛋蛋能量-会员设置(新增)
// @Tags         蛋蛋能量
// @Description  会员设置(新增)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body	md.UpdateEggEnergyVipSettingReq 	true  "system_id 必填"
// @Success      200   {int}   	"修改数据条数"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/eggEnergy/addVipSetting [post]
func AddEggEnergyVipSetting(c *gin.Context) {
	var req *md.AddEggEnergyVipSettingReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}

	setting := md2.VipEquitySettingStruct{
		VipLevelId:                req.VipLevelId,
		ExchangeAccountBalanceFee: req.ExchangeAccountBalanceFee,
		DividendRatio:             req.DividendRatio,
	}

	basicSettingDb := implement.NewEggEnergyBasicSettingDb(db.Db)
	basicSettings, err1 := basicSettingDb.EggEnergyBasicSettingGetOne()
	if err1 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err1.Error())
		return
	}
	if basicSettings == nil {
		e.OutErr(c, e.ERR_NO_DATA, errors.New("未能获取基础设置"))
		return
	}

	var vipEquitySetting []md2.VipEquitySettingStruct
	utils.Unserialize([]byte(basicSettings.VipEquitySetting), &vipEquitySetting)

	vipEquitySetting = append(vipEquitySetting, setting)
	vipEquitySettingStr := utils.SerializeStr(vipEquitySetting)
	basicSettings.VipEquitySetting = vipEquitySettingStr

	session := db.Db.NewSession()
	affected, err := basicSettingDb.EggEnergyBasicSettingUpdate(session, basicSettings.Id, basicSettings, "vip_equity_setting")
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	e.OutSuc(c, affected, nil)
}

// UpdateEggEnergyVipSetting
// @Summary      制度中心-蛋蛋能量-会员设置(更新)
// @Tags         蛋蛋能量
// @Description  会员设置(更新)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body	md.UpdateEggEnergyVipSettingReq 	true  "填入修改后的列表(会员等级名称、兑换余额手续费、分红比例)"
// @Success      200   {int}   	"修改数据条数"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/eggEnergy/updateVipSetting [post]
func UpdateEggEnergyVipSetting(c *gin.Context) {
	var req *md.UpdateEggEnergyVipSettingReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}

	basicSettingDb := implement.NewEggEnergyBasicSettingDb(db.Db)
	basicSettings, err1 := basicSettingDb.EggEnergyBasicSettingGetOne()
	if err1 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err1.Error())
		return
	}
	if basicSettings == nil {
		e.OutErr(c, e.ERR_NO_DATA, errors.New("未能获取基础设置"))
		return
	}

	levelDb := implement.NewUserLevelDb(db.Db)
	levels, err1 := levelDb.UserLevelAllByAsc()
	if err1 != nil {
		e.OutErr(c, e.ERR_DB_ORM, err1.Error())
		return
	}
	levelsList := make([]map[string]interface{}, 0)
	for _, level := range levels {
		levelsList = append(levelsList, map[string]interface{}{
			"id":   level.Id,
			"name": level.LevelName,
		})
	}

	vipEquitySetting := make([]md2.VipEquitySettingStruct, len(req.List))
	for i, node := range req.List {
		vipEquitySetting[i] = md2.VipEquitySettingStruct{
			VipLevelId:                node.VipLevelID,
			ExchangeAccountBalanceFee: node.ExchangeAccountBalanceFee,
			DividendRatio:             node.DividendRatio,
		}
	}

	vipEquitySettingStr := utils.SerializeStr(vipEquitySetting)
	basicSettings.VipEquitySetting = vipEquitySettingStr
	session := db.Db.NewSession()
	affected, err := basicSettingDb.EggEnergyBasicSettingUpdate(session, basicSettings.Id, basicSettings, "vip_equity_setting")
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	e.OutSuc(c, affected, nil)
}

// GetEggCoreDataList
// @Summary      制度中心-蛋蛋能量-数据概览(获取)
// @Tags         蛋蛋能量
// @Description  数据概览(获取)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Success      200   {object} md.GetEggCoreDataListResp   	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/eggEnergy/globalData/coreDataList [get]
func GetEggCoreDataList(c *gin.Context) {
	coreDataDb := implement.NewEggEnergyCoreDataDb(db.Db)
	coreData, err := coreDataDb.EggEnergyCoreDataGet()
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	if coreData == nil {
		e.OutErr(c, e.ERR_NO_DATA, errors.New("数据不存在"))
		return
	}

	sql := "SELECT SUM(amount) AS total, coin_id FROM `user_virtual_amount` GROUP BY (coin_id)"
	results, err := db.Db.QueryString(sql)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	settingDb := implement.NewEggEnergyBasicSettingDb(db.Db)
	setting, err := settingDb.EggEnergyBasicSettingGetOne()
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, nil)
		return
	}

	var userHoldTotalNums float64
	for _, result := range results {
		switch utils.StrToInt(result["coin_id"]) {
		case setting.PersonEggEnergyCoinId, setting.TeamEggEnergyCoinId, setting.PersonEggPointsCoinId, setting.TeamEggPointsCoinId:
			userHoldTotalNums += utils.StrToFloat64(result["total"])
		}
	}

	resp := md.GetEggCoreDataListResp{
		PlanetTotalValue:   coreData.PlanetTotalValue,
		NowPrice:           coreData.NowPrice,
		NowEnergyTotalNums: coreData.NowEnergyTotalNums,
		UserHoldTotalNums:  utils.Float64ToStr(userHoldTotalNums),
	}

	e.OutSuc(c, resp, nil)
}

// GetPriceCurve
// @Summary      制度中心-蛋蛋能量-价格趋势(获取)
// @Tags         蛋蛋能量
// @Description  价格趋势(获取)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    kind    query	string 	false  "1:按天 2:按小时 3:按周"
// @Success      200   {object}  md.GetPriceCurveResp  	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/eggEnergy/globalData/pointsCenterPriceCurve [get]
func GetPriceCurve(c *gin.Context) {
	kind := c.DefaultQuery("kind", "1")
	now := time.Now()

	var yData []interface{}
	var xData []interface{}

	priceDb := implement.NewEggEnergyPriceDb(db.Db)
	m, has, err := priceDb.EggEnergyPriceGetLastOne()
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	if has == false {
		e.OutSuc(c, md.GetPriceCurveResp{
			YData: yData,
			XData: xData,
		}, nil)
		return
	}

	switch kind {
	case "1":
		var date = now.AddDate(0, 0, -30).Format("2006-01-02")
		var sql = fmt.Sprintf("SELECT price,date FROM `egg_energy_price` WHERE HOUR = 23 AND DATE >= \"%s\" AND DATE != \"%s\" ORDER BY DATE ASC ", date, now.Format("2006-01-02"))
		results, _ := db.Db.QueryString(sql)
		for _, v := range results {
			tmpDate := utils.TimeParseStd(v["date"])
			yData = append(yData, v["price"])
			xData = append(xData, tmpDate.Format("01-02"))
		}
		yData = append(yData, m.Price)
		tmpDate := utils.TimeParseStd(m.Date)
		xData = append(xData, tmpDate.Format("01-02"))
		break
	case "2":
		for i := 29; i >= 1; i-- {
			date := now.Add(-time.Hour * 4 * time.Duration(i)).Format("2006-01-02")
			hour := now.Add(-time.Hour * 4 * time.Duration(i)).Hour()
			var sql = "SELECT price,date,hour FROM `egg_energy_price` WHERE HOUR = %d AND DATE = \"%s\" "
			sql = fmt.Sprintf(sql, hour, date)
			results, _ := db.Db.QueryString(sql)
			if results != nil {
				//if results[0]["date"] != now.Format("2006-01-02") {
				//	continue
				//}
				yData = append(yData, results[0]["price"])
				xData = append(xData, results[0]["hour"]+":00")
			}
		}
		yData = append(yData, m.Price)
		xData = append(xData, m.Hour+":00")
		break
	case "3":
		var nums = 29
		for i := nums; i >= 1; i-- {
			var date = now.AddDate(0, 0, -7*i).Format("2006-01-02")
			var sql = "SELECT price,date FROM `egg_energy_price` WHERE HOUR = 23 AND DATE = \"%s\" "
			sql = fmt.Sprintf(sql, date)
			results, _ := db.Db.QueryString(sql)
			if results != nil {
				tmpDate := utils.TimeParseStd(results[0]["date"])
				yData = append(yData, results[0]["price"])
				xData = append(xData, tmpDate.Format("01-02"))
			}
		}
		yData = append(yData, m.Price)
		tmpDate := utils.TimeParseStd(m.Date)
		xData = append(xData, tmpDate.Format("01-02"))
		break
	}

	e.OutSuc(c, md.GetPriceCurveResp{
		YData: yData,
		XData: xData,
	}, nil)
	return
}

// GetFundDataList
// @Summary      制度中心-蛋蛋能量-新增数据列表(获取)
// @Tags         蛋蛋能量
// @Description  新增数据列表(获取)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body	md.GetFundDataListReq 	true  "分页信息必填"
// @Success      200   {object} md.GetFundDataListResp   	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/eggEnergy/globalData/fundDataList [post]
func GetFundDataList(c *gin.Context) {
	var req *md.GetFundDataListReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}

	var kindList = []map[string]interface{}{
		{
			"name":  enum.EggEnergyFundDataKind.String(enum.CompanySubsidies),
			"value": enum.CompanySubsidies,
		},
		{
			"name":  enum.EggEnergyFundDataKind.String(enum.InvestmentByInvestors),
			"value": enum.InvestmentByInvestors,
		},
		{
			"name":  enum.EggEnergyFundDataKind.String(enum.MarketExpectations),
			"value": enum.MarketExpectations,
		},
	}

	fundDataDb := implement.NewEggEnergyFundDataDb(db.Db)
	fundDataList, total, err := fundDataDb.EggEnergyFundDataFindAndCount(req.Page, req.Limit, req.Kind, req.StartAt, req.EndAt)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	list := make([]md.FundDataNode, len(fundDataList))
	for i, fundData := range fundDataList {
		list[i].Kind = fundData.Kind
		list[i].TotalAmount = fundData.TotalAmount
		list[i].Hours = fundData.Hours
		list[i].Memo = fundData.Memo
		list[i].BalanceTimes = fundData.BalanceTimes
		list[i].BalanceAmount = fundData.BalanceAmount
		list[i].CreateAt = fundData.CreateAt
		list[i].SystemID = fundData.Id
	}

	resp := md.GetFundDataListResp{
		KindList: kindList,
		Paginate: md.Paginate{
			Limit: req.Limit,
			Page:  req.Page,
			Total: total,
		},
		List: list,
	}
	e.OutSuc(c, resp, nil)
}

// GetFundDataRecordList
// @Summary      制度中心-蛋蛋能量-新增数据列表详情(查询)
// @Tags         蛋蛋能量
// @Description  新增数据列表详情(查询)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body	md.GetFundDataRecordListReq 	true  "获取到的 system_id 以及分页信息"
// @Success      200   {object} md.GetFundDataRecordListResp   	"具体数据"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/eggEnergy/globalData/fundDataRecordList [post]
func GetFundDataRecordList(c *gin.Context) {
	var req *md.GetFundDataRecordListReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}

	recordsDb := implement.NewEggEnergyFundDataRecordsDb(db.Db)
	records, total, err := recordsDb.EggEnergyFundDataRecordsFindAndCount(req.Page, req.Limit, req.SystemID)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}
	var list []md.FundDataRecordNode
	for i, record := range records {
		list[i].TotalAmount = record.TotalAmount
		list[i].BalanceAmount = record.BalanceAmount
		list[i].BalanceTimes = record.BalanceTimes
		list[i].BeforePrice = record.BeforePrice
		list[i].AfterPrice = record.AfterPrice
		list[i].BeforePlanetTotalValue = record.BeforePlanetTotalValue
		list[i].AfterPlanetTotalValue = record.AfterPlanetTotalValue
		list[i].CreateAt = record.CreateAt
	}

	resp := md.GetFundDataRecordListResp{
		Paginate: md.Paginate{
			Limit: req.Limit,
			Page:  req.Page,
			Total: total,
		},
		List: list,
	}

	e.OutSuc(c, resp, nil)
}

// AddFundData
// @Summary      制度中心-蛋蛋能量-价值明细数据(新增)
// @Tags         蛋蛋能量
// @Description  价值明细数据(新增)
// @Accept       json
// @Produce      json
// @param Authorization header string true "验证参数Bearer和token空格拼接"
// @Param    req    body	md.AddFundDataReq 	true  "数据种类、金额、时长(最长24h)、执行次数必填,备注选填"
// @Success      200   {int}   	"插入数据 id"
// @Failure      400   {object}   md.Response              	"具体错误"
// @Router       /api/institutionalManagement/eggEnergy/globalData/fundDataAdd [post]
func AddFundData(c *gin.Context) {
	var req *md.AddFundDataReq
	if err1 := c.ShouldBindJSON(&req); err1 != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err1.Error())
		return
	}

	fundDataDb := implement.NewEggEnergyFundDataDb(db.Db)
	now := time.Now()
	hour := now.Hour()
	if req.Hours > 24 {
		hour = 24
	}
	times := req.Hours * 60 / req.Frequency
	m := model.EggEnergyFundData{
		Kind:          req.Kind,
		TotalAmount:   req.TotalAmount,
		BalanceAmount: req.TotalAmount,
		Hours:         hour,
		BalanceTimes:  times,
		Frequency:     req.Frequency,
		Memo:          req.Memo,
		CreateAt:      now.Format("2006-01-02 15:04:05"),
		UpdateAt:      now.Format("2006-01-02 15:04:05"),
	}
	id, err := fundDataDb.EggEnergyFundDataInsert(&m)
	if err != nil {
		e.OutErr(c, e.ERR_DB_ORM, err.Error())
		return
	}

	e.OutSuc(c, id, nil)
}