package line_feature

import (
	"eta_gn/eta_api/global"
	"eta_gn/eta_api/models/data_manage"
	"eta_gn/eta_api/utils"
	"fmt"
	"strconv"
	"strings"
	"time"
)

type BatchAddChart struct {
	ChartInfo                       *data_manage.ChartInfo
	EdbMappingList                  []*data_manage.ChartEdbMapping
	MultipleGraphConfigChartMapping *data_manage.MultipleGraphConfigChartMapping
}

func CreateLineFeatureChartAndEdb(chartInfo *data_manage.ChartInfo, edbMappingList []*data_manage.ChartEdbMapping) (chartInfoId int, err error) {
	tx := global.DmSQL["data"].Begin()
	defer func() {
		if err != nil {
			_ = tx.Rollback()
		} else {
			_ = tx.Commit()
		}
	}()

	// 新增图表信息
	err = tx.Create(chartInfo).Error
	if err != nil {
		return
	}
	chartInfoId = chartInfo.ChartInfoId

	// 指标mapping
	if len(edbMappingList) > 0 {
		for i := range edbMappingList {
			edbMappingList[i].ChartInfoId = chartInfoId
		}
		err = tx.CreateInBatches(edbMappingList, utils.MultiAddNum).Error
		if err != nil {
			return
		}
	}

	return
}

// EditLineFeatureChartAndMapping 批量新增/编辑拟合方程图表
func EditLineFeatureChartAndMapping(req *data_manage.EditChartInfoReq, edbInfoIdStr string, calendar string, dateType, disabled int, extraConfig string) (err error) {
	to := global.DmSQL["data"].Begin()
	defer func() {
		if err != nil {
			_ = to.Rollback()
		} else {
			_ = to.Commit()
		}
	}()
	var pars []interface{}
	pars = append(pars, req.ChartName)
	pars = append(pars, req.ChartNameEn)
	pars = append(pars, edbInfoIdStr)
	pars = append(pars, req.ChartClassifyId)
	pars = append(pars, disabled)
	pars = append(pars, extraConfig)

	sql := ` UPDATE  chart_info
			SET
			  chart_name =?,
			  chart_name_en =?,
              edb_info_ids=?,
			  chart_classify_id = ?,
			  modify_time = NOW(),
              disabled = ?,
              extra_config = ?
			`
	if calendar != "" {
		sql += `,calendar = ? `
		pars = append(pars, calendar)
	}
	if dateType > 0 {
		sql += `,date_type = ? `
		pars = append(pars, dateType)
	}

	sql += `,start_date = ? `
	pars = append(pars, req.StartDate)

	sql += `,end_date = ? `
	pars = append(pars, req.EndDate)

	sql += `,season_start_date = ? `
	pars = append(pars, req.StartDate)

	sql += `,season_end_date = ? `
	pars = append(pars, req.EndDate)

	sql += `,left_min = ? `
	pars = append(pars, req.LeftMin)

	sql += `,left_max = ? `
	pars = append(pars, req.LeftMax)

	sql += `,right_min = ? `
	pars = append(pars, req.RightMin)

	sql += `,right_max = ? `
	pars = append(pars, req.RightMax)

	sql += `WHERE chart_info_id = ?`

	pars = append(pars, req.ChartInfoId)
	err = to.Exec(sql, pars).Error
	if err != nil {
		fmt.Println("UPDATE  chart_info Err:", err.Error())
		return err
	}
	chartEdbMappingIdList := make([]string, 0)
	for _, v := range req.CorrelationChartInfo.EdbInfoIdList {
		// 查询该指标是否存在,如果存在的话,那么就去修改,否则新增
		var tmpChartEdbMapping *data_manage.ChartEdbMapping
		csql := `SELECT *  FROM chart_edb_mapping WHERE chart_info_id=? AND edb_info_id=? AND source = ? `
		err = to.Raw(csql, req.ChartInfoId, v.EdbInfoId, utils.CHART_SOURCE_CORRELATION).First(&tmpChartEdbMapping).Error
		if err != nil && !utils.IsErrNoRow(err) {
			fmt.Println("QueryRow Err:", err.Error())
			return err
		}
		if tmpChartEdbMapping != nil {
			chartEdbMappingIdList = append(chartEdbMappingIdList, strconv.Itoa(tmpChartEdbMapping.ChartEdbMappingId))
			//tmpChartEdbMapping.ModifyTime = time.Now()
			//tmpChartEdbMapping.MaxData = v.MaxData
			//tmpChartEdbMapping.MinData = v.MinData
			//tmpChartEdbMapping.IsOrder = v.IsOrder
			//tmpChartEdbMapping.IsAxis = v.IsAxis
			//tmpChartEdbMapping.EdbInfoType = v.EdbInfoType
			//tmpChartEdbMapping.LeadValue = v.LeadValue
			//tmpChartEdbMapping.LeadUnit = v.LeadUnit
			//tmpChartEdbMapping.ChartStyle = v.ChartStyle
			//tmpChartEdbMapping.ChartColor = v.ChartColor
			//tmpChartEdbMapping.PredictChartColor = v.PredictChartColor
			//tmpChartEdbMapping.ChartWidth = v.ChartWidth
			//_, err = to.Update(tmpChartEdbMapping, "ModifyTime", "MaxData", "MinData", "IsOrder", "IsAxis", "EdbInfoType", "LeadValue", "LeadUnit", "ChartStyle", "ChartColor", "PredictChartColor", "ChartWidth")
			//if err != nil {
			//	fmt.Println("chart_edb_mapping Err:" + err.Error())
			//	return err
			//}
		} else {
			mapItem := new(data_manage.ChartEdbMapping)
			mapItem.ChartInfoId = req.ChartInfoId
			mapItem.EdbInfoId = v.EdbInfoId
			mapItem.CreateTime = time.Now()
			mapItem.ModifyTime = time.Now()
			timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
			mapItem.UniqueCode = utils.MD5(utils.CHART_PREFIX + "_" + timestamp + "_" + strconv.Itoa(v.EdbInfoId))
			//mapItem.MaxData = v.MaxData
			//mapItem.MinData = v.MinData
			mapItem.IsOrder = true
			mapItem.IsAxis = 1
			mapItem.EdbInfoType = 1
			//mapItem.LeadValue = v.LeadValue
			//mapItem.LeadUnit = v.LeadUnit
			//mapItem.ChartStyle = v.ChartStyle
			//mapItem.ChartColor = v.ChartColor
			//mapItem.PredictChartColor = v.PredictChartColor
			//mapItem.ChartWidth = v.ChartWidth
			mapItem.Source = utils.CHART_SOURCE_CORRELATION
			err = to.Create(mapItem).Error
			if err != nil {
				fmt.Println("AddChartEdbMapping Err:" + err.Error())
				return err
			}
			chartEdbMappingIdList = append(chartEdbMappingIdList, strconv.Itoa(mapItem.ChartEdbMappingId))
		}
	}
	if len(chartEdbMappingIdList) > 0 {
		chartEdbMappingIdStr := strings.Join(chartEdbMappingIdList, ",")
		dsql := `DELETE FROM chart_edb_mapping WHERE chart_info_id=? AND chart_edb_mapping_id NOT IN(` + chartEdbMappingIdStr + `)`
		err = to.Exec(dsql, req.ChartInfoId).Error
		if err != nil {
			fmt.Println("delete err:" + err.Error())
			return err
		}
	}

	return
}