// Package wrtrade 仓单贸易
package wrtrade

import (
	"mtp2_if/db"
	"mtp2_if/global/app"
	"mtp2_if/global/e"
	"mtp2_if/logger"
	"mtp2_if/models"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// GetAllDeliveryGoods 获取带仓单分类的种类信息
// @Summary 获取带仓单分类的种类信息
// @Produce json
// @Security ApiKeyAuth
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /WRTrade/GetAllDeliveryGoods [get]
// @Tags 仓单贸易
// @Summary 获取带仓单分类的种类信息
// @Produce json
// @Security ApiKeyAuth
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /WRTrade/GetAllDeliveryGoods [get]
// @Tags 仓单贸易
func GetAllDeliveryGoods(c *gin.Context) {
	appG := app.Gin{C: c}

	engine := db.GetEngine()

	// 获取品种（交割商品）信息
	deliveryGoodses := make([]models.Deliverygoods, 0)
	if err := engine.Where("IsValid=1").And("categoryid<>0").Find(&deliveryGoodses); err != nil {
		// 查询失败
		logger.GetLogger().Errorf("GetAllDeliveryGoods failed: %s", err.Error())
		appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
		return
	}

	// 获取与品种相关的所有仓单分类信息
	// 当前种品所相关的分类ID
	ids := ""
	for _, deliveryGoods := range deliveryGoodses {
		if ids == "" {
			ids = strconv.FormatInt(int64(deliveryGoods.Categoryid), 10)
		} else {
			ids += "," + strconv.FormatInt(int64(deliveryGoods.Categoryid), 10)
		}
	}

	// SELECT w.categoryid,w.categoryname,w.parentcategoryid,w.categorydesc,w.iconurl FROM WRCategory w START WITH Categoryid in (2,2,4) CONNECT BY PRIOR ParentCategoryID = Categoryid;
	// 查询当前所有品种信息
	var wrcategorys []models.Wrcategory
	if err := engine.SQL("SELECT w.categoryid,w.categoryname,w.parentcategoryid,w.categorydesc,w.iconurl FROM WRCategory w START WITH Categoryid in (?) CONNECT BY PRIOR ParentCategoryID = Categoryid", ids).Find(&wrcategorys); err != nil {
		// 查询失败
		logger.GetLogger().Errorf("GetAllDeliveryGoods failed: %s", err.Error())
		appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
		return
	}

	// 构建分类与品种的从属关系

	appG.Response(http.StatusOK, e.SUCCESS, deliveryGoodses)
}
