package pg

import (
	"context"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"log"
	"reflect"

	"github.com/go-pg/pg/v10"
	"github.com/go-pg/pg/v10/orm"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
	"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/infrastructure/pg/models"
)

var DB *pg.DB

func init() {
	DB = pg.Connect(&pg.Options{
		User:     constant.POSTGRESQL_USER,
		Password: constant.POSTGRESQL_PASSWORD,
		Database: constant.POSTGRESQL_DB_NAME,
		Addr:     fmt.Sprintf("%s:%s", constant.POSTGRESQL_HOST, constant.POSTGRESQL_PORT),
	})
	if !constant.DISABLE_SQL_GENERATE_PRINT {
		DB.AddQueryHook(SqlGeneratePrintHook{})
	}
	if !constant.DISABLE_CREATE_TABLE {
		for _, model := range []interface{}{
			(*models.Device)(nil),
			(*models.DeviceCollection)(nil),
			(*models.Product)(nil),
			(*models.ProductAttendanceRecord)(nil),
			(*models.ProductCalendar)(nil),
			(*models.ProductGroup)(nil),
			(*models.ProductJob)(nil),
			(*models.ProductPlan)(nil),
			(*models.ProductRecord)(nil),
			(*models.UnitConversion)(nil),
			(*models.Workshop)(nil),
			(*models.MaterialK3cloud)(nil),
			(*models.MaterialGroupK3cloud)(nil),
			(*models.PrdMoK3cloud)(nil),
			(*models.EmployeeProductRecord)(nil),
			(*models.WorkshopProductRecord)(nil),
			(*models.WorkshopWorkTimeRecord)(nil),
			(*models.ProductPlanDispatchRecord)(nil),
			(*models.DeviceDailyRunningRecord)(nil),
			(*models.DeviceRunningRecord)(nil),
			(*models.WorkshopPlanCompletionRecord)(nil),
			(*models.ProductMaterialGroup)(nil),
			(*models.ProductMaterial)(nil),
		} {
			err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
				Temp:          false,
				IfNotExists:   true,
				FKConstraints: true,
			})
			if err != nil {
				panic(err)
			}
			if !constant.DISABLE_SQL_GENERATE_COMMENT {
				AddComments(DB, model)
			}
		}
	}
}

type SqlGeneratePrintHook struct{}

func (hook SqlGeneratePrintHook) BeforeQuery(c context.Context, q *pg.QueryEvent) (context.Context, error) {
	return c, nil
}

func (hook SqlGeneratePrintHook) AfterQuery(c context.Context, q *pg.QueryEvent) error {
	sqlStr, err := q.FormattedQuery()
	if err != nil {
		return err
	}
	//log.Logger.Debug(string(sqlStr))
	log.Println(string(sqlStr))
	logs.Debug(string(sqlStr))
	return nil
}

func AddComments(db *pg.DB, model interface{}) {
	tableName := db.Model(model).TableModel().Table().SQLName
	columnsMap := make(map[string]*orm.Field)
	columns := db.Model(model).TableModel().Table().Fields
	for _, item := range columns {
		columnsMap[item.GoName] = item
	}
	valueOf := reflect.TypeOf(model)
	for i := 0; i < valueOf.Elem().NumField(); i++ {
		field := valueOf.Elem().Field(i)
		comment := field.Tag.Get("comment")
		if comment != "" {
			if field.Name == "tableName" {
				_, _ = db.Exec(fmt.Sprintf("COMMENT ON TABLE %s IS '%s';", tableName, comment))
			} else {
				if columnField, ok := columnsMap[field.Name]; ok {
					_, _ = db.Exec(fmt.Sprintf("COMMENT ON COLUMN %s.%s IS '%s';", tableName, columnField.SQLName, comment))
				}
			}
		}
	}
}