package excel

import (
	"eta/eta_chart_lib/global"
	"eta/eta_chart_lib/models"
	"eta/eta_chart_lib/utils"
	"fmt"
	"time"
)

type ExcelChartData struct {
	//ExcelChartDataId int `orm:"column(excel_chart_data_id);pk"`
	ExcelChartDataId int `gorm:"column:excel_chart_data_id;primaryKey"`
	ExcelInfoId      int `description:"表格id"`
	ExcelChartEdbId  int `description:"指标ID"`
	ChartInfoId      int `description:"图表id"`
	DataTime         string
	Value            float64
	ModifyTime       time.Time `description:"修改时间"`
	CreateTime       time.Time `description:"创建时间"`
	DataTimestamp    int64
}

func (e *ExcelChartData) TableName() string {
	return "excel_chart_data"
}

// 新增
func (e *ExcelChartData) Add() (err error) {
	//o := orm.NewOrmUsingDB("data")
	//_, err = o.Insert(e)
	err = global.DbMap[utils.DbNameIndex].Create(&e).Error
	return
}

// 修改
func (e *ExcelChartData) Update(cols []string) (err error) {
	//o := orm.NewOrmUsingDB("data")
	//_, err = o.Update(e, cols...)
	err = global.DbMap[utils.DbNameIndex].Model(&e).Select(cols).Updates(&e).Error
	return
}

// 删除
func (e *ExcelChartData) Delete() (err error) {
	//o := orm.NewOrmUsingDB("data")
	//_, err = o.Delete(e)
	err = global.DbMap[utils.DbNameIndex].Delete(&e).Error
	return
}

// 查询
func GetExcelChartDataByExcelInfoId(excelInfoId int) (list []*ExcelChartData, err error) {
	//o := orm.NewOrmUsingDB("data")
	sql := ` SELECT *
             FROM excel_chart_data
			 WHERE excel_info_id=? 
            ORDER BY excel_chart_edb_id ASC, data_time desc, excel_chart_data_id ASC `
	//_, err = o.Raw(sql, excelInfoId).QueryRows(&list)
	err = global.DbMap[utils.DbNameIndex].Raw(sql, excelInfoId).Find(&list).Error
	return
}

func BatchUpdateChartEdbData(excelInfoId int, excelEdbMap map[int]*ExcelChartEdb, excelDataMap map[int][]*models.EdbDataList) (err error) {
	//o, err := orm.NewOrmUsingDB("data").Begin()
	o := global.DbMap[utils.DbNameIndex].Begin()
	if err != nil {
		return
	}
	defer func() {
		if err != nil {
			_ = o.Rollback()
		} else {
			_ = o.Commit()
		}
	}()
	//如果有数据则删除所有的数据
	sql := `delete from excel_chart_data where excel_info_id = ?`
	//_, err = o.Raw(sql, excelInfoId).Exec()
	err = o.Exec(sql, excelInfoId).Error
	if err != nil {
		return
	}

	// 图表指标数据入库
	addList := make([]*ExcelChartData, 0)
	for chartEdbId, dataList := range excelDataMap {
		chartEdb, ok := excelEdbMap[chartEdbId]
		if !ok {
			err = fmt.Errorf("chartEdbId:%d not exist", chartEdbId)
			return
		}
		for _, v := range dataList {
			chartData := &ExcelChartData{
				ExcelInfoId:     chartEdb.ExcelInfoId,
				ExcelChartEdbId: chartEdb.ExcelChartEdbId,
				ChartInfoId:     chartEdb.ChartInfoId,
				DataTime:        v.DataTime,
				Value:           v.Value,
				DataTimestamp:   v.DataTimestamp,
				ModifyTime:      time.Now(),
				CreateTime:      time.Now(),
			}
			addList = append(addList, chartData)
			// data信息入库
			if len(addList) > 1000 {
				//_, err = o.InsertMulti(len(addList), addList)
				err = o.CreateInBatches(addList, len(addList)).Error
				if err != nil {
					return
				}
				addList = addList[:0]
			}
		}
	}

	// data信息入库
	if len(addList) > 0 {
		//_, err = o.InsertMulti(len(addList), addList)
		err = o.CreateInBatches(addList, len(addList)).Error
		if err != nil {
			return
		}
	}
	return
}

func GetExcelChartDataByChartInfoId(chartInfoId int) (list []*ExcelChartData, err error) {
	//o := orm.NewOrmUsingDB("data")
	sql := ` SELECT *
             FROM excel_chart_Data
			 WHERE chart_info_id=? 
             ORDER BY excel_chart_edb_id ASC `
	//_, err = o.Raw(sql, chartInfoId).QueryRows(&list)
	err = global.DbMap[utils.DbNameIndex].Raw(sql, chartInfoId).Find(&list).Error
	return
}