package controllers_join

import (
	"encoding/json"
	controllers_func "kkscrap-go/controllers/func"
	"kkscrap-go/locals"
	models_join "kkscrap-go/models/join"
	"net/http"

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

type BodyCopyPageReq struct {
	QueryVars        locals.QueryVars
	BodyCopyPageVars locals.BodyCopyPageVars
	PageVars         locals.PageVars
}

func BodyCopyPage(c echo.Context) error {

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

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

	vRet.QueryVars = v.QueryVars
	vRet.BodyCopyPageVars = v.BodyCopyPageVars
	vRet.PageVars = v.PageVars
	if err := vRet.GetBodyCopyPage(&y); err != nil {
		return c.String(607, err.Error())
	}

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

type BodyCopyMactReq struct {
	QueryVars     locals.QueryVars
	LastSeqNoVars controllers_func.LastSeqNoGetReq
	Page          []locals.BodyCopyBase
}

func BodyCopyMact(c echo.Context) error {

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

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

	// var msg string
	// var accErr error

	q := &v.QueryVars
	sn := &v.LastSeqNoVars

	// if if v.q{
	// 	return c.String(608, "Transaction Commit Failed")
	// }

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

			seqNo := 0
			if serial, err := controllers_func.LastSerial(&y, sn.TableName+sn.SlipNo); err == nil {
				seqNo = serial
			} else {
				return c.String(605, err.Error())
			}

			if addId, err := models_join.BodyCopyAdd(&y, q.QueryName, sn.TableName, sn.SlipNo, seqNo, row.BdId, row.Qty); err == nil {
				vIdRet.Id = addId
				vRet.Page = append(vRet.Page, *vIdRet)
			} else {
				sess.Rollback()
				return c.String(603, err.Error())
			}

			// if addId, err := models_join.BodyCopyAdd(&y, q.QueryName, v.SlipId, seqNo, row.BdId, row.Qty); err == nil {
			// 	vIdRet.Id = addId
			// 	vRet.Page = append(vRet.Page, *vIdRet)
			// } else {
			// 	sess.Rollback()
			// 	return c.String(603, err.Error())
			// }

		}
	} else {
		return c.String(608, "Transaction Action Failed")
	}

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

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

}
