package controllers

import (
	"encoding/json"
	"eta/eta_api/models"
	"eta/eta_api/models/data_manage/request"
	"eta/eta_api/utils"
	"fmt"
	"github.com/tealeg/xlsx"
	"os"
	"path/filepath"
	"time"
)

// MeetingProbabilitiesController 加息概率
type MeetingProbabilitiesController struct {
	BaseAuthController
}

// Detail
// @Title 获取表格详情
// @Description 获取表格详情接口
// @Param   ExcelInfoId   query   int  true       "表格id"
// @Success 200 {object} data_manage.ExcelInfo
// @router /detail [get]
func (c *MeetingProbabilitiesController) Detail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		c.Data["json"] = br
		c.ServeJSON()
	}()
	sysUser := c.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录，SysUser Is Empty"
		br.Ret = 408
		return
	}

	date := c.GetString("DateTime")
	isExport, _ := c.GetInt("IsExport")

	// 获取数据详情bu
	excelDetail, err := models.GetMeetingInfoById(date)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Ret = 200
			br.Msg = "该日期无数据"
			br.Msg = "该日期无数据，Err:" + err.Error()
			return
		}
		br.ErrMsg = err.Error()
		return
	}

	if isExport == 1 {
		sheet := new(request.ISheet)
		err = json.Unmarshal([]byte(excelDetail.Content), &sheet)

		MeetingProbabilitiesExport(c,br,sheet)
		return
	}


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

// MeetingProbabilitiesExport 导出Excel
func MeetingProbabilitiesExport(this *MeetingProbabilitiesController, br *models.BaseResponse, sheetReq *request.ISheet) {
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请重新登录"
		return
	}

	dir, _ := os.Executable()
	exPath := filepath.Dir(dir)
	downloadPath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
	xlsxFile := xlsx.NewFile()
	sheet, e := xlsxFile.AddSheet("数据报表")
	if e != nil {
		br.Msg = "新增Sheet失败"
		br.ErrMsg = "新增Sheet失败, Err: " + e.Error()
		return
	}


	for _, v := range sheetReq.Data {
		addRow := sheet.AddRow()
		for _, s := range v {
			if s != nil {
				addRow.AddCell().SetString(s.M)
			}
		}
	}

	if e = xlsxFile.Save(downloadPath); e != nil {
		br.Msg = "导出失败"
		br.ErrMsg = "保存文件失败"
		return
	}
	fileName := fmt.Sprint("MeetingProbabilities", time.Now().Format("2006.01.02"), ".xlsx")
	this.Ctx.Output.Download(downloadPath, fileName)
	defer func() {
		_ = os.Remove(downloadPath)
	}()
	br.Ret = 200
	br.Success = true
	br.Msg = "success"
}

