package data_manage

import (
	"fmt"
	"github.com/rdlucklib/rdluck_tools/paging"
	"eta/eta_api/models"
	"eta/eta_api/models/data_manage"
	"eta/eta_api/utils"
	"time"
)

// ComTradeCountryList
// @Title UN国家列表
// @Description UN国家列表接口
// @Success 200 {object} []data_manage.ComTradeCountryItem
// @router /com_trade/country/list [get]
func (this *EdbInfoController) ComTradeCountryList() {
	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
	}

	list, err := data_manage.GetComTradeCountryItemAll()
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

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

// ComTradeDataList
// @Title UN数据列表
// @Description UN数据列表接口
// @Param   PageSize   query   int  true       "每页页码数"
// @Param   CurrentIndex   query   int  true       "当前页码"
// @Param   IndexCode   query   string  true       "指标code"
// @Param   Year   query   string  true       "年份"
// @Param   Date   query   string  true       "日期"
// @Param   Flow   query   string  true       "贸易流向：X（Export：出口）；M（Import：进口）"
// @Param   ReporterCode   query   string  true       "出口国id"
// @Param   PartnerCode   query   string  true       "进口国id"
// @Param   Partner2Code   query   string  true       "第2进口国id"
// @Param   DateType   query   int  true       "日期类型，0:所有，1：年度，2：月度"
// @Param   SortParam   query   string  false       "排序字段参数，用来排序的字段， 枚举值：'data_time':日期"
// @Param   SortType   query   string  true       "如何排序，是正序还是倒序，枚举值：`asc 正序`,`desc 倒叙`"
// @Success 200 {object} data_manage.ComTradeDataListResp
// @router /com_trade/data/list [get]
func (this *EdbInfoController) ComTradeDataList() {
	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
	}

	pageSize, _ := this.GetInt("PageSize")
	currentIndex, _ := this.GetInt("CurrentIndex")

	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{}

	// @Param   IndexCode   query   string  true       "指标code"
	indexCode := this.GetString("IndexCode")
	if indexCode != `` {
		condition += ` AND index_code = ? `
		pars = append(pars, indexCode)
	}
	// @Param   Flow   query   string  true       "贸易流向：X（Export：出口）；M（Import：进口）"
	flow := this.GetString("Flow")
	if flow != `` {
		condition += ` AND flow = ? `
		pars = append(pars, flow)
	}
	// @Param   DateType   query   int  true       "日期类型，0:所有，1：年度，2：月度"
	dateType, _ := this.GetInt("DateType", 0)
	if dateType > 0 {
		condition += ` AND date_type = ? `
		pars = append(pars, dateType)
	}
	// @Param   Date   query   string  true       "日期"
	date := this.GetString("Date")
	if date != `` {
		switch dateType {
		case 1:
			condition += ` AND data_time = ? `
			pars = append(pars, date+"-12-31")
		case 2:
			condition += ` AND data_time = ? `
			dateTime, tmpErr := time.ParseInLocation(utils.FormatDate, date+"-01", time.Local)
			if tmpErr != nil {
				br.Msg = "日期异常"
				br.ErrMsg = "日期异常：" + tmpErr.Error()
				return
			}
			pars = append(pars, dateTime.AddDate(0, 1, -1).Format(utils.FormatDate))
		}

	}

	// @Param   ReporterCode   query   string  true       "出口国id"
	reporterCode := this.GetString("ReporterCode")
	if reporterCode != `` && reporterCode != `-1` {
		condition += ` AND reporter_code = ? `
		pars = append(pars, reporterCode)
	}
	// @Param   PartnerCode   query   string  true       "进口国id"
	partnerCode := this.GetString("PartnerCode")
	if partnerCode != `` && partnerCode != `-1` {
		condition += ` AND partner_code = ? `
		pars = append(pars, partnerCode)
	}
	// @Param   Partner2Code   query   string  true       "第2进口国id"
	partner2Code := this.GetString("Partner2Code")
	if partner2Code != `` && partner2Code != `-1` {
		condition += ` AND partner2_code = ? `
		pars = append(pars, partner2Code)
	}

	sortParam := this.GetString("SortParam")
	sortType := this.GetString("SortType")
	sortStr := ``
	if sortParam != `` {
		sortStr = fmt.Sprintf("%s %s,modify_time desc ", sortParam, sortType)
	} else {
		sortStr = " data_time desc,modify_time desc "
	}

	total, err := data_manage.GetComTradeListCount(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	list, err := data_manage.GetComTradeList(condition, pars, startSize, pageSize, sortStr)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}

	var lastUpdateTime time.Time
	lastUpdateTimeStr := ``
	// 获取用到的指标信息
	comTradeList, err := data_manage.GetAllComTradeIndexList()
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	comTradeMap := make(map[int]*data_manage.ComTradeIndex)
	for _, v := range comTradeList {
		comTradeMap[v.ComTradeId] = v
		if lastUpdateTime.IsZero() || lastUpdateTime.Before(v.UpdateTime) {
			lastUpdateTime = v.UpdateTime
			lastUpdateTimeStr = lastUpdateTime.Format(utils.FormatDateTime)
		}
	}

	if len(list) > 0 {
		// 给指标数据赋值指标名称
		for _, v := range list {
			if comTradeInfo, ok := comTradeMap[v.ComTradeId]; ok {
				v.IndexNameCn = comTradeInfo.IndexNameCn
			}
			v.Date = fmt.Sprint(v.DataTime.Year())
			if v.DateType == 2 {
				v.Date = v.DataTime.Format(utils.FormatYearMonthDate)
			}
		}
	}
	page := paging.GetPaging(currentIndex, pageSize, total)
	resp := data_manage.ComTradeDataListResp{
		Paging:         page,
		List:           list,
		LastUpdateTime: lastUpdateTimeStr,
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// ComTradeList
// @Title UN指标列表
// @Description UN指标列表接口
// @Param   Keyword   query   string  true       "关键字搜索"
// @Success 200 {object} []data_manage.ComTradeIndex
// @router /com_trade/list [get]
func (this *EdbInfoController) ComTradeList() {
	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 condition string
	var pars []interface{}

	// @Param   IndexCode   query   string  true       "指标code"
	keyword := this.GetString("Keyword")
	if keyword != `` {
		condition += ` AND ( index_name_cn like ? or index_code like ? ) `
		pars = append(pars, "%"+keyword+"%", "%"+keyword+"%")
	}

	list, err := data_manage.GetComTradeIndexList(condition, pars)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败，Err:" + err.Error()
		return
	}
	if len(list) <= 0 {
		list = make([]*data_manage.ComTradeIndex, 0)
	}

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