package data_source

import (
	"eta/eta_api/controllers"
	"eta/eta_api/models"
	"eta/eta_api/models/data_source"
	"eta/eta_api/utils"
	"fmt"
	"github.com/tealeg/xlsx"
	"os"
	"path/filepath"
	"strconv"
	"time"
)

type DataSourceController struct {
	controllers.BaseAuthController
}

// ComTradeCountryList
// @Title 获取广州期货交易所分类
// @Description 获取广州期货交易所分类
// @Success 200 {object} []data_manage.ComTradeCountryItem
// @router /gfex/classify/list [get]
func (this *DataSourceController) GfexClassifyList() {
	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
	}

	gzqhObj := new(data_source.BaseFromTradeGuangzhouIndex)
	classifyList, err := gzqhObj.GetBaseFromTradeGuangzhouClassifyAll()
	if err != nil {
		br.Msg = "获取分类失败"
		br.ErrMsg = "获取分类失败，Err:" + err.Error()
		return
	}

	classifyMap := make(map[int][]*data_source.BaseFromTradeGuangzhouClassifyView)
	for _, v := range classifyList {
		if v.ParentId == 0 {
			continue
		}
		if items, ok := classifyMap[v.ParentId]; !ok {
			list := make([]*data_source.BaseFromTradeGuangzhouClassifyView, 0)
			list = append(list, v)
			classifyMap[v.ParentId] = list
		} else {
			items = append(items, v)
			classifyMap[v.ParentId] = items
		}
	}

	classifyItems := make([]*data_source.BaseFromTradeGuangzhouClassifyView, 0)
	for _, v := range classifyList {
		if v.ParentId == 0 {
			v.Children = classifyMap[v.BaseFromTradeGuangzhouClassifyId]
			classifyItems = append(classifyItems, v)
		}
	}

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

// ComTradeCountryList
// @Title 获取广州期货交易所数据最大日期
// @Description 获取广州期货交易所数据最大日期
// @Success 200 {object} []data_source.ComTradeCountryItem
// @router /gfex/max/date [get]
func (this *DataSourceController) GfexMaxDate() {
	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
	}

	gzqhObj := new(data_source.BaseFromTradeGuangzhouIndex)
	maxDate, err := gzqhObj.GetBaseFromTradeGuangzhouMaxDate()
	if err != nil {
		br.ErrMsg = "获取最新日期失败,Err:" + err.Error()
		br.Msg = "获取最新日期失败"
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = maxDate
}

// ComTradeCountryList
// @Title 获取广州期货交易所-分类下合约
// @Description 获取广州期货交易所-分类下合约
// @Param   BaseFromTradeGuangzhouClassifyId   query   int  true       "分类id"
// @Param   TradeDate   query   string  true       "日期"
// @Success 200 {object} []data_source.BaseFromTradeGuangzhouContract
// @router /gfex/contract [get]
func (this *DataSourceController) GfexContract() {
	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
	}

	baseFromTradeGuangzhouClassifyId, _ := this.GetInt("BaseFromTradeGuangzhouClassifyId", 0)
	if baseFromTradeGuangzhouClassifyId <= 0 {
		br.Msg = "参数错误"
		br.Msg = "分类id错误"
		return
	}
	tradeDate := this.GetString("TradeDate")
	if tradeDate == "" {
		br.Msg = "参数错误"
		br.Msg = "交易日期不能为空"
		return
	}
	gzqhObj := new(data_source.BaseFromTradeGuangzhouIndex)
	list, err := gzqhObj.GetBaseFromTradeGuangzhouContract(baseFromTradeGuangzhouClassifyId, tradeDate)
	if err != nil {
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		br.Msg = "获取数据失败"
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// ComTradeCountryList
// @Title 获取广州期货交易所-分类下指标信息
// @Description 获取广州期货交易所-分类下指标信息
// @Param   BaseFromTradeGuangzhouClassifyId   query   int  true       "分类id"
// @Param   BaseFromTradeGuangzhouContractId   query   int  true       "合约id"
// @Param   TradeDate   query   string  true       "日期"
// @Success 200 {object} []data_source.BaseFromTradeGuangzhouIndexView
// @router /gfex/index_data [get]
func (this *DataSourceController) GfexIndexData() {
	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
	}

	baseFromTradeGuangzhouClassifyId, _ := this.GetInt("BaseFromTradeGuangzhouClassifyId", 0)
	if baseFromTradeGuangzhouClassifyId <= 0 {
		br.Msg = "参数错误"
		br.ErrMsg = "分类id错误"
		return
	}
	tradeDate := this.GetString("TradeDate")
	if tradeDate == "" {
		br.Msg = "参数错误"
		br.ErrMsg = "交易日期不能为空"
		return
	}
	baseFromTradeGuangzhouContractId, err := this.GetInt("BaseFromTradeGuangzhouContractId", 0)
	fmt.Println(err)
	fmt.Println(baseFromTradeGuangzhouContractId)

	var condition string
	var pars []interface{}

	if baseFromTradeGuangzhouContractId > 0 {
		condition += `  b.data_time=? `
		pars = append(pars, tradeDate)
		condition += ` AND a.base_from_trade_guangzhou_classify_id=? `
		pars = append(pars, baseFromTradeGuangzhouClassifyId)
	} else {
		if baseFromTradeGuangzhouClassifyId == 11 || baseFromTradeGuangzhouClassifyId == 12 { //月度数据处理
			td, err := time.Parse(utils.FormatDate, tradeDate)
			if err != nil {
				br.Msg = "日期格式错误"
				br.ErrMsg = "日期格式错误,Err:" + err.Error()
				return
			}
			_, monthEndDay := utils.GetMonthStartAndEnd(strconv.Itoa(td.Year()), strconv.Itoa(int(td.Month())))
			condition += `  a.data_time=? `
			pars = append(pars, monthEndDay)
		} else {
			condition += `  a.data_time=? `
			pars = append(pars, tradeDate)
		}

		condition += ` AND b.base_from_trade_guangzhou_classify_id=? `
		pars = append(pars, baseFromTradeGuangzhouClassifyId)
	}

	//if baseFromTradeGuangzhouContractId > 0 {
	//	condition += ` AND c.base_from_trade_guangzhou_contract_id=? `
	//	pars = append(pars, baseFromTradeGuangzhouContractId)
	//}

	gzqhObj := new(data_source.BaseFromTradeGuangzhouIndex)
	list, err := gzqhObj.GetBaseFromTradeGuangzhouIndex(condition, pars, baseFromTradeGuangzhouContractId)
	if err != nil {
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		br.Msg = "获取数据失败"
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// @Title 获取广州期货交易所-一次性交割卖方仓单明细
// @Description 获取广州期货交易所-一次性交割卖方仓单明细
// @Param   BaseFromTradeGuangzhouIndexId   query   int  true       "指标id"
// @Param   TradeDate   query   string  true       "日期"
// @Success 200 {object} []data_source.BaseFromTradeGuangzhouIndexView
// @router /gfex/index/detail [get]
func (this *DataSourceController) GfexIndexDetail() {
	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
	}
	baseFromTradeGuangzhouIndexId, _ := this.GetInt("BaseFromTradeGuangzhouIndexId", 0)
	if baseFromTradeGuangzhouIndexId < 0 {
		br.Msg = "参数错误"
		return
	}
	tradeDate := this.GetString("TradeDate")
	if tradeDate == "" {
		br.Msg = "参数错误"
		br.ErrMsg = "交易日期不能为空"
		return
	}

	var condition string
	var pars []interface{}

	condition += ` a.base_from_trade_guangzhou_classify_id = ? `
	pars = append(pars, baseFromTradeGuangzhouIndexId)

	td, err := time.Parse(utils.FormatDate, tradeDate)
	if err != nil {
		br.Msg = "日期格式错误"
		br.ErrMsg = "日期格式错误,Err:" + err.Error()
		return
	}
	_, monthEndDay := utils.GetMonthStartAndEnd(strconv.Itoa(td.Year()), strconv.Itoa(int(td.Month())))
	condition += ` AND a.end_date = ? `
	pars = append(pars, monthEndDay)

	gzqhObj := new(data_source.BaseFromTradeGuangzhouIndex)
	list, err := gzqhObj.GetBaseFromTradeGuangzhouIndexDetail(condition, pars)
	if err != nil {
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		br.Msg = "获取数据失败"
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// @Title 导出广州期货交易所-一次性交割卖方仓单明细
// @Description 导出广州期货交易所-一次性交割卖方仓单明细
// @Param   BaseFromTradeGuangzhouIndexId   query   int  true       "指标id"
// @Param   TradeDate   query   string  true       "日期"
// @Success 200  导出成功
// @router /gfex/index/detail/export [get]
func (this *DataSourceController) ExportGfexIndexDetail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请重新登录"
		return
	}

	baseFromTradeGuangzhouIndexId, _ := this.GetInt("BaseFromTradeGuangzhouIndexId", 0)
	if baseFromTradeGuangzhouIndexId < 0 {
		br.Msg = "参数错误"
		return
	}
	tradeDate := this.GetString("TradeDate")
	if tradeDate == "" {
		br.Msg = "参数错误"
		br.ErrMsg = "交易日期不能为空"
		return
	}

	var condition string
	var pars []interface{}

	condition += ` a.base_from_trade_guangzhou_classify_id = ? `
	pars = append(pars, baseFromTradeGuangzhouIndexId)

	td, err := time.Parse(utils.FormatDate, tradeDate)
	if err != nil {
		br.Msg = "日期格式错误"
		br.ErrMsg = "日期格式错误,Err:" + err.Error()
		return
	}
	_, monthEndDay := utils.GetMonthStartAndEnd(strconv.Itoa(td.Year()), strconv.Itoa(int(td.Month())))
	condition += ` AND a.end_date = ? `
	pars = append(pars, monthEndDay)

	gzqhObj := new(data_source.BaseFromTradeGuangzhouIndex)
	list, err := gzqhObj.GetBaseFromTradeGuangzhouIndexDetail(condition, pars)
	if err != nil {
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		br.Msg = "获取数据失败"
		return
	}

	dir, _ := os.Executable()
	exPath := filepath.Dir(dir)

	downLoadnFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	sheetNew, err := xlsxFile.AddSheet("详情")
	if err != nil {
		br.ErrMsg = "导出失败,Err:" + err.Error()
		br.Msg = "导出失败"
		return
	}
	titleRow := sheetNew.AddRow()
	titleRow.AddCell().SetValue("指标ID")
	titleRow.AddCell().SetValue("指标名称")
	titleRow.AddCell().SetValue("数值")
	titleRow.AddCell().SetValue("单位")
	titleRow.AddCell().SetValue("频度")
	titleRow.AddCell().SetValue("起始日期")
	titleRow.AddCell().SetValue("最新日期")

	var indexCode string
	for _, sv := range list {
		dataRow := sheetNew.AddRow()
		dataRow.AddCell().SetValue(sv.IndexCode)
		dataRow.AddCell().SetValue(sv.IndexName)
		dataRow.AddCell().SetValue(sv.Value)
		dataRow.AddCell().SetValue(sv.Unit)
		dataRow.AddCell().SetValue(sv.Frequency)
		dataRow.AddCell().SetValue(sv.StartDate)
		dataRow.AddCell().SetValue(sv.EndDate)

		indexCode = sv.IndexCode
	}
	err = xlsxFile.Save(downLoadnFilePath)
	if err != nil {
		//有指标无数据时先导出一遍空表
		sheet, err := xlsxFile.AddSheet("无数据")
		if err != nil {
			br.Msg = "新增Sheet失败"
			br.ErrMsg = "新增Sheet失败,Err:" + err.Error()
			return
		}
		rowSecName := sheet.AddRow()
		celSecName := rowSecName.AddCell()
		celSecName.SetValue("")
		err = xlsxFile.Save(downLoadnFilePath)
		if err != nil {
			br.Msg = "保存文件失败"
			br.ErrMsg = "保存文件失败"
			return
		}
	}
	fileName := `一次性交割卖方仓单详情`
	fileName = indexCode[:6] + fileName + `.xlsx` //文件名称
	this.Ctx.Output.Download(downLoadnFilePath, fileName)
	defer func() {
		os.Remove(downLoadnFilePath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "success"

}
