package controller

import (
	"encoding/json"
	"net/http"

	"be.ems/lib/services"
	"be.ems/src/framework/datasource"
	"be.ems/src/framework/i18n"
	"be.ems/src/framework/utils/ctx"
	"be.ems/src/modules/crontask/processor/exportUEData"
	"be.ems/features/ue/model"
	"github.com/gin-gonic/gin"
)

var NewFileSource = &FileSource{}

type FileSource struct {
	SysJob			model.SysJob
	TableName    	string `json:"tableName"`
	TableDisplay 	string `json:"tableDisplay"`
	FilePath     	string `json:"filePath"`
}

// GetFileExportTable 获取文件导出任务列表
func (m *FileSource) GetFileExportTable(c *gin.Context) {
	var results []model.SysJob

	err := datasource.DefaultDB().Table(m.SysJob.TableName()).
		Where("invoke_target=? and status=1", model.INVOKE_FILE_EXPORT).
		Find(&results).Error
	if err != nil {
		c.JSON(http.StatusOK, services.ErrResp(err.Error()))
		return
	}
	language := ctx.AcceptLanguage(c)
	var response []FileSource
	for _, job := range results {
		params := make([]exportUEData.BarParams, 0)
		if err := json.Unmarshal([]byte(job.TargetParams), &params); err != nil {
			c.JSON(http.StatusOK, services.ErrResp(err.Error()))
			return
		}
		for _, param := range params {
			TableDisplay := i18n.TKey(language, "table."+param.TableName)
			if TableDisplay == "" {
				TableDisplay = param.TableName
			}
			response = append(response, FileSource{
				SysJob: 		job,
				TableName:    	param.TableName,
				TableDisplay: 	TableDisplay,
				FilePath:     	param.FilePath,
			})
		}
	}
	c.JSON(http.StatusOK, services.DataResp(response))
}

