package controllers_join

import (
	"encoding/json"
	"errors"
	"kkscrap-go/locals"
	models_join "kkscrap-go/models/join"
	models_table "kkscrap-go/models/table"
	"net/http"
	"strconv"

	"github.com/dabory/abango-rest"
	"github.com/labstack/echo"
)

type BalanceIdPageBase struct {
	Page []locals.IdBase
}

type ListFormBalancePageReq struct {
	QueryVars           locals.QueryVars
	ListFormBalanceVars locals.ListFormBalanceVars
	PageVars            locals.PageVars
}

func ListFormBalancePage(c echo.Context) error {

	v := c.Get("receiver").(ListFormBalancePageReq)
	y := c.Get("abango").(abango.Controller)

	vRet := &struct {
		models_join.ListFormBalancePageRet
	}{}

	vRet.QueryVars = v.QueryVars
	vRet.ListFormBalanceVars = v.ListFormBalanceVars
	vRet.PageVars = v.PageVars

	if err := vRet.GetListFormBalancePage(&y); err != nil {
		return c.String(607, err.Error())
	}

	ret, _ := json.Marshal(vRet)
	return c.JSONBlob(http.StatusOK, ret)
}

type ListFormBalanceMactReq struct {
	QueryVars           locals.QueryVars
	ListFormBalanceVars locals.ListFormBalanceVars
	Page                []models_join.ListFormBalance
}

func ListFormBalanceMact(c echo.Context) error {

	v := c.Get("receiver").(ListFormBalanceMactReq)
	y := c.Get("abango").(abango.Controller)

	vRet := &struct {
		BalanceIdPageBase
	}{}

	if v.QueryVars.QueryName == "item" {
		if status, err := vRet.ListFormBalanceMactItem(y, v); err != nil {
			return c.String(status, err.Error())
		}
	} else if v.QueryVars.QueryName == "supplier" {
		if status, err := vRet.ListFormBalanceMactSupplier(y, v); err != nil {
			return c.String(status, err.Error())
		}
	} else if v.QueryVars.QueryName == "buyer" {
		if status, err := vRet.ListFormBalanceMactBuyer(y, v); err != nil {
			return c.String(status, err.Error())
		}
	}

	ret, _ := json.Marshal(vRet)
	return c.JSONBlob(http.StatusOK, ret)
}

func (vRet *BalanceIdPageBase) ListFormBalanceMactBuyer(y abango.Controller, v ListFormBalanceMactReq) (int, error) {

	vIdRet := &locals.IdBase{}

	t := &struct {
		models_table.DbrBalBuyer
	}{}

	sess := y.Db.NewSession()
	defer sess.Close()
	if err := sess.Begin(); err == nil {
		for _, row := range v.Page {

			if !(row.Id < 0) {
				t.BranchId = y.Gtb.BranchId
			}

			t.YyyyMm = v.ListFormBalanceVars.YyyyMm

			t.Id = row.Id
			t.BuyerId = row.CodeId
			t.BalAmt = row.Balance2 //맨마지막 밸렌스 이용

			skipRow := false // Do NOT write row if Balaces are ZERO
			if bal, err := strconv.ParseFloat(row.Balance2, 32); err == nil {
				if bal == 0 {
					skipRow = true
				}
			}
			if t.Id == 0 && !skipRow {
				if err := t.AddaRow(&y); err != nil {
					sess.Rollback()
					return 603, err
				}
			} else if t.Id > 0 {
				if err := t.EditaRow(&y); err != nil {
					sess.Rollback()
					return 605, err
				}
			}
			vIdRet.Id = t.Id
			vRet.Page = append(vRet.Page, *vIdRet)
		}
	} else {
		return 608, errors.New("Transaction Action Failed")
	}

	if err := sess.Commit(); err != nil {
		return 608, errors.New("Transaction Commit Failed")
	}
	return 200, nil
}

func (vRet *BalanceIdPageBase) ListFormBalanceMactSupplier(y abango.Controller, v ListFormBalanceMactReq) (int, error) {

	vIdRet := &locals.IdBase{}

	t := &struct {
		models_table.DbrBalSupplier
	}{}

	sess := y.Db.NewSession()
	defer sess.Close()
	if err := sess.Begin(); err == nil {
		for _, row := range v.Page {

			if !(row.Id < 0) {
				t.BranchId = y.Gtb.BranchId
			}

			t.YyyyMm = v.ListFormBalanceVars.YyyyMm

			t.Id = row.Id
			t.SupplierId = row.CodeId
			t.BalAmt = row.Balance2 //맨마지막 밸렌스 이용

			skipRow := false // Do NOT write row if Balaces are ZERO
			if bal, err := strconv.ParseFloat(row.Balance2, 32); err == nil {
				if bal == 0 {
					skipRow = true
				}
			}
			if t.Id == 0 && !skipRow {
				if err := t.AddaRow(&y); err != nil {
					sess.Rollback()
					return 603, err
				}
			} else if t.Id > 0 {
				if err := t.EditaRow(&y); err != nil {
					sess.Rollback()
					return 605, err
				}
			}
			vIdRet.Id = t.Id
			vRet.Page = append(vRet.Page, *vIdRet)
		}
	} else {
		return 608, errors.New("Transaction Action Failed")
	}

	if err := sess.Commit(); err != nil {
		return 608, errors.New("Transaction Commit Failed")
	}
	return 200, nil
}

func (vRet *BalanceIdPageBase) ListFormBalanceMactItem(y abango.Controller, v ListFormBalanceMactReq) (int, error) {

	vIdRet := &locals.IdBase{}

	t := &struct {
		models_table.DbrBalItem
	}{}

	sess := y.Db.NewSession()
	defer sess.Close()
	if err := sess.Begin(); err == nil {
		for _, row := range v.Page {

			t.YyyyMm = v.ListFormBalanceVars.YyyyMm
			t.StorageId = v.ListFormBalanceVars.SelectedId

			t.Id = row.Id
			t.ItemId = row.CodeId
			t.BalQty = row.Balance
			t.BadBalQty = row.Balance2

			skipRow := false // Do NOT write row if Balaces are ZERO
			if bal, err := strconv.ParseFloat(row.Balance, 32); err == nil {
				if bal2, err := strconv.ParseFloat(row.Balance2, 32); err == nil {
					if bal == 0 && bal2 == 0 {
						skipRow = true
					}
				}
			}
			if t.Id == 0 && !skipRow {
				if err := t.AddaRow(&y); err != nil {
					sess.Rollback()
					return 603, err
				}
			} else if t.Id > 0 {
				if err := t.EditaRow(&y); err != nil {
					sess.Rollback()
					return 605, err
				}
			}
			vIdRet.Id = t.Id
			vRet.Page = append(vRet.Page, *vIdRet)
		}
	} else {
		return 608, errors.New("Transaction Action Failed")
	}

	if err := sess.Commit(); err != nil {
		return 608, errors.New("Transaction Commit Failed")
	}
	return 200, nil
}
