package delivery

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

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

// QueryDeliveryRelationReq 查询商品交割关系表请求参数
type QueryDeliveryRelationReq struct {
	GoodsID         int `form:"goodsid"`
	DeliveryGoodsID int `form:"deliverygoodsid"`
	MarketID        int `form:"marketid"`
}

// QueryDeliveryRelationRsp 商品交割关系表
type QueryDeliveryRelationRsp struct {
	Goodsid           int64   `json:"goodsid"  xorm:"'GOODSID'" binding:"required"`               // 交易合约ID
	Deliverymode      int64   `json:"deliverymode"  xorm:"'DELIVERYMODE'"`                        // 交割方式 - 1:点选式 2:申报式
	Wrstandardid      int64   `json:"wrstandardid"  xorm:"'WRSTANDARDID'"`                        // 仓单标准ID
	Deliverygoodsid   int64   `json:"deliverygoodsid"  xorm:"'DELIVERYGOODSID'"`                  // 交割商品
	Mindeliveryqty    int64   `json:"mindeliveryqty"  xorm:"'MINDELIVERYQTY'" binding:"required"` // 最小交割系数(K)
	Rratio1           int64   `json:"rratio1"  xorm:"'RRATIO1'"`                                  // 兑换系数(交易合约)(R1)
	Rratio2           int64   `json:"rratio2"  xorm:"'RRATIO2'"`                                  // 兑换系数(仓单标准)(R2)
	Deliverypricerule int64   `json:"deliverypricerule"  xorm:"'DELIVERYPRICERULE'"`              // 交割价规则- 1:行情价 2:建仓价
	Begindate         string  `json:"begindate"  xorm:"'BEGINDATE'" binding:"required"`           // 起始日期(yyyyMMdd)
	Enddate           string  `json:"enddate"  xorm:"'ENDDATE'" binding:"required"`               // 结束日期(yyyyMMdd)
	Buytemplateid     int64   `json:"buytemplateid"  xorm:"'BUYTEMPLATEID'"`                      // 买履约计划模板ID
	Selltemplateid    int64   `json:"selltemplateid"  xorm:"'SELLTEMPLATEID'"`                    // 卖履约计划模板ID
	Deliverytype      int64   `json:"deliverytype"  xorm:"'DELIVERYTYPE'"`                        // 交割模式 - 1:X交割 2:X+P交割 3:X+C交割 4:X+P+C交割
	Xdeliveryratio    int64   `json:"xdeliveryratio"  xorm:"'XDELIVERYRATIO'" binding:"required"` // 交易合约系数(m)
	Ppricemode        int64   `json:"ppricemode"  xorm:"'PPRICEMODE'"`                            // P合约价格方式 - 1:商品价  2:固定值
	Pdeliveryprice    float64 `json:"pdeliveryprice"  xorm:"'PDELIVERYPRICE'"`                    // P合约价格(商品价时填写0，固定值时填写固定值)
	Pdeliveryratio    int64   `json:"pdeliveryratio"  xorm:"'PDELIVERYRATIO'"`                    // P合约系数(n)
	Pgoodsid          int64   `json:"pgoodsid"  xorm:"'PGOODSID'"`                                // P合约ID
	P2pricemode       int64   `json:"p2pricemode"  xorm:"'P2PRICEMODE'"`                          // P2合约价格方式 - 1:商品价  2:固定值
	P2deliveryprice   float64 `json:"p2deliveryprice"  xorm:"'P2DELIVERYPRICE'"`                  // P2合约价格(商品价时填写0，固定值时填写固定值)
	P2deliveryratio   int64   `json:"p2deliveryratio"  xorm:"'P2DELIVERYRATIO'"`                  // P2合约系数(p)
	P2goodsid         int64   `json:"p2goodsid"  xorm:"'P2GOODSID'"`                              // P2合约ID
	Rratio            int64   `json:"rratio"  xorm:"'RRATIO'"`                                    // 兑换系数(R)

	Goodscode         string `json:"goodscode"  xorm:"'GOODSCODE'"`                 // 商品代码
	Goodsname         string `json:"goodsname"  xorm:"'GOODSNAME'"`                 // 商品名称
	Marketid          int64  `json:"marketid"  xorm:"'MARKETID'"`                   // 市场ID
	Deliverygoodscode string `json:"deliverygoodscode"  xorm:"'DELIVERYGOODSCODE'"` // 品种代码
	Deliverygoodsname string `json:"deliverygoodsname"  xorm:"'DELIVERYGOODSNAME'"` // 品种名称
}

// QueryDeliveryRelation 查询商品交割关系表
// @Summary 查询商品交割关系表
// @Produce json
// @Security ApiKeyAuth
// @Param goodsid query int false "商品ID"
// @Param deliverygoodsid query int false "品种ID"
// @Param marketid query int false "市场ID"
// @Success 200 {object} QueryDeliveryRelationRsp
// @Failure 500 {object} app.Response
// @Router /Delivery/QueryDeliveryRelation [get]
// @Tags 交割服务
func QueryDeliveryRelation(c *gin.Context) {
	appG := app.Gin{C: c}

	// 获取请求参数
	var req QueryDeliveryRelationReq
	if err := appG.C.ShouldBindQuery(&req); err != nil {
		logger.GetLogger().Errorf("QueryDeliveryRelation failed: %s", err.Error())
		appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
		return
	}

	// 查询数据
	engine := db.GetEngine()
	datas := make([]QueryDeliveryRelationRsp, 0)
	sql := `select
				t.GOODSID,
				t.DELIVERYMODE,
				t.WRSTANDARDID,
				t.DELIVERYGOODSID,
				t.MINDELIVERYQTY,
				t.RRATIO1,
				t.RRATIO2,
				t.DELIVERYPRICERULE,
				t.BEGINDATE,
				t.ENDDATE,
				t.BUYTEMPLATEID,
				t.SELLTEMPLATEID,
				t.DELIVERYTYPE,
				t.XDELIVERYRATIO,
				t.PPRICEMODE,
				t.PDELIVERYPRICE,
				t.PDELIVERYRATIO,
				t.PGOODSID,
				t.P2PRICEMODE,
				t.P2DELIVERYPRICE,
				t.P2DELIVERYRATIO,
				t.P2GOODSID,
				t.RRATIO,
				g.goodscode,
				g.goodsname,
				g.marketid,
				dg.deliverygoodscode,
				dg.deliverygoodsname
			from DELIVERYRELATION t
			left join goods g on t.goodsid = g.goodsid
			left join deliverygoods dg on t.deliverygoodsid = dg.deliverygoodsid 
			where 1=1`
	if req.GoodsID > 0 {
		sql += fmt.Sprintf(` and t.GoodsID = %d`, req.GoodsID)
	}
	if req.DeliveryGoodsID > 0 {
		sql += fmt.Sprintf(` and t.DeliveryGoodsID = %d`, req.DeliveryGoodsID)
	}
	// FIXME: 之前写成了 and t.MarketID = %d ，但返回时err == nil ，需要判断原因
	if req.MarketID > 0 {
		sql += fmt.Sprintf(` and g.MarketID = %d`, req.MarketID)
	}
	if err := engine.SQL(sql).Find(&datas); err != nil {
		// 查询失败
		logger.GetLogger().Errorf("QueryDeliveryRelation failed: %s", err.Error())
		appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
		return
	}

	// 查询成功
	logger.GetLogger().Debugln("QueryDeliveryRelation successed: %v", datas)
	appG.Response(http.StatusOK, e.SUCCESS, datas)
}
