package trade

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

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

// QueryRecieptOrderReq 点选挂牌委托单据查询参数
type QueryRecieptOrderReq struct {
	app.PageInfo
	GoodsID     int    `form:"goodsID" binding:"required"` // 商品ID，必填
	BuyOrSell   int    `form:"buyorsell"`                  // 方向
	AccountName string `form:"accountName"`                // 所属账户名称
	MarketID    int    `form:"marketID"`                   // 市场ID
}

// QueryRecieptOrderRsp 点选挂牌委托单据查询返回模型
type QueryRecieptOrderRsp struct {
	Goodsid     int64     `json:"goodsid"  xorm:"'GOODSID'"`                        // 商品ID
	Goodscode   string    `json:"goodscode"  xorm:"'GOODSCODE'"`                    // 商品代码
	Goodsname   string    `json:"goodsname"  xorm:"'GOODSNAME'"`                    // 商品名称
	Buyorsell   uint32    `json:"buyorsell"  xorm:"'BUYORSELL'"`                    // 方向 - 0:买 1:卖
	Orderid     string    `json:"orderid"  xorm:"'ORDERID'"`                        // 委托单号
	Tradedate   string    `json:"tradedate"  xorm:"'TRADEDATE'"`                    // 交易日(yyyyMMdd)
	Orderprice  float64   `json:"orderprice"  xorm:"'ORDERPRICE'"`                  // 委托价格
	EnableQty   int64     `json:"enableqty" xorm:"ENABLEQTY"`                       // 可摘数量
	AccountName string    `json:"accountName" xorm:"ACCOUNTNAME"`                   // 所属账号名称（已脱敏）
	AccountID   int64     `json:"accountid" xorm:"ACCOUNTID"`                       // 资金账号
	Ordertime   time.Time `json:"ordertime"  xorm:"'ORDERTIME'" binding:"required"` // 委托时间
}

// QueryRecieptOrder 点选挂牌委托单据查询（保证金摘牌大厅）
// @Summary 点选挂牌委托单据查询（保证金摘牌大厅）
// @Description 说明：pagesize参数赋值不为0时表示需要分页；page参数从0开始计算
// @Produce json
// @Security ApiKeyAuth
// @Param page query int false "页码"
// @Param pagesize query int false "每页条数"
// @Param goodsID query int true "商品ID"
// @Param accountName query string false "所属账户名称"
// @Param marketID query int false "市场ID"
// @Param buyorsell query int true "方向 - 0:买 1:卖"
// @Success 200 {object} QueryRecieptOrderRsp
// @Failure 500 {object} app.Response
// @Router /Trade/QueryRecieptOrder [get]
// @Tags 通用交易
// 参考通用查询：Client_SZDZ3_SearchRecieptOrder
func QueryRecieptOrder(c *gin.Context) {
	appG := app.Gin{C: c}

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

	datas := make([]QueryRecieptOrderRsp, 0)
	engine := db.GetEngine()

	// 投资者挂牌委托单
	s := engine.Table("TRADE_ORDERDETAIL").
		Join("INNER", "GOODS", "TRADE_ORDERDETAIL.GOODSID = GOODS.GOODSID").
		Join("LEFT", "TAACCOUNT", "TAACCOUNT.ACCOUNTID = TRADE_ORDERDETAIL.ACCOUNTID").
		Join("LEFT", "USERACCOUNT", "USERACCOUNT.USERID = TAACCOUNT.RELATEDUSERID").
		Select(`GOODS.GOODSID, GOODS.GOODSCODE, GOODS.GOODSNAME, 
				TRADE_ORDERDETAIL.BUYORSELL, to_char(TRADE_ORDERDETAIL.ORDERID) as ORDERID, TRADE_ORDERDETAIL.TRADEDATE, TRADE_ORDERDETAIL.ORDERPRICE, 
				TRADE_ORDERDETAIL.ORDERQTY - TRADE_ORDERDETAIL.TRADEQTY - TRADE_ORDERDETAIL.CANCELQTY as ENABLEQTY, 
				(case when USERACCOUNT.ISANONYMOUS = 0 then to_char(USERACCOUNT.ACCOUNTNAME) else '*****' end) ACCOUNTNAME`).
		Where("TRADE_ORDERDETAIL.ORDERSTATUS in (3,7,12) and GOODS.GOODSID = ?", req.GoodsID)
	if len(req.AccountName) > 0 {
		s = s.And("USERACCOUNT.ACCOUNTNAME = ?", req.AccountName)
	}
	if req.MarketID > 0 {
		s = s.And("TRADE_ORDERDETAIL.MARKETID = ?", req.MarketID)
	}
	if req.BuyOrSell > -1 {
		s = s.And("TRADE_ORDERDETAIL.BUYORSELL = ?", req.BuyOrSell)
	}
	// 判断是否要分页
	// 这样分页会报错
	// if req.Size > 0 {
	// 	s = s.Limit(req.Size, req.Page*req.Size)
	// }
	d1 := make([]QueryRecieptOrderRsp, 0)
	if err := s.Find(&d1); err != nil {
		// 查询失败
		logger.GetLogger().Errorf("QueryRecieptOrder failed: %s", err.Error())
		appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
		return
	}
	datas = append(datas, d1...)

	// 报价商挂牌委托
	s = engine.Table("TRADE_QUOTEDETAILNEW").
		Join("INNER", "GOODS", "TRADE_QUOTEDETAILNEW.GOODSID = GOODS.GOODSID").
		Join("INNER", "QUOTER", "QUOTER.QUOTERID = TRADE_QUOTEDETAILNEW.QUOTERID").
		Join("INNER", "AREAROLE", "AREAROLE.USERID = QUOTER.DEFAULTMAKERID and AREAROLE.ROLETYPE = 8").
		Select(`GOODS.GOODSID, GOODS.GOODSCODE, GOODS.GOODSNAME, 
				TRADE_QUOTEDETAILNEW.BUYORSELL, to_char(TRADE_QUOTEDETAILNEW.ORDERID) as ORDERID, TRADE_QUOTEDETAILNEW.TRADEDATE, TRADE_QUOTEDETAILNEW.PRICE as ORDERPRICE, 
				TRADE_QUOTEDETAILNEW.CURQTY as ENABLEQTY, 
				substr(QUOTER.QUOTERNAME,0,1)||'****' as ACCOUNTNAME`).
		Where("(TRADE_QUOTEDETAILNEW.CURQTY > 0 or TRADE_QUOTEDETAILNEW.PRICE > 0) and TRADE_QUOTEDETAILNEW.ISVALID != 1 and TRADE_QUOTEDETAILNEW.FREEZESTATUS != 3")
	d2 := make([]QueryRecieptOrderRsp, 0)
	if err := s.Find(&d2); err != nil {
		// 查询失败
		logger.GetLogger().Errorf("QueryRecieptOrder failed: %s", err.Error())
		appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
		return
	}
	datas = append(datas, d2...)

	// 过滤相关账号下非买一卖一的单据（如买一卖一有多张单则都要显示）
	if req.BuyOrSell == 0 {
		// 买，先按价格倒序排列
		sort.Slice(datas, func(i int, j int) bool {
			if datas[i].Orderprice == datas[j].Orderprice {
				return datas[i].Ordertime.Before(datas[j].Ordertime)
			}
			return datas[i].Orderprice > datas[j].Orderprice
		})
	} else {
		// 卖，先按价格顺序排列
		sort.Slice(datas, func(i int, j int) bool {
			if datas[i].Orderprice == datas[j].Orderprice {
				return datas[i].Ordertime.Before(datas[j].Ordertime)
			}
			return datas[i].Orderprice < datas[j].Orderprice
		})
	}

	// tmpDatas := make([]QueryRecieptOrderRsp, 0)
	// for _, v := range datas {
	// 	needAdd := true
	// 	for _, t := range tmpDatas {
	// 		if req.BuyOrSell == 0 {
	// 			// 买
	// 			if t.AccountID == v.AccountID && t.Buyorsell == v.Buyorsell && t.Orderprice > v.Orderprice {
	// 				needAdd = false
	// 			}
	// 		} else {
	// 			// 卖
	// 			if t.AccountID == v.AccountID && t.Buyorsell == v.Buyorsell && t.Orderprice < v.Orderprice {
	// 				needAdd = false
	// 			}
	// 		}
	// 	}
	// 	if needAdd {
	// 		tmpDatas = append(tmpDatas, v)
	// 	}
	// }
	// datas = tmpDatas

	total := len(datas)
	// FIXME: - 排序 & 分页
	// 排序
	sort.Slice(datas, func(i int, j int) bool {
		return datas[i].Tradedate > datas[j].Tradedate
	})
	// 分页
	if req.PageSize > 0 {
		// 开始上标
		start := req.Page * req.PageSize
		// 结束下标
		// a := []int{1,2,3,4,5}
		// a[2:4] -> [3 4]
		end := start + req.PageSize

		if start <= len(datas) {
			// 判断结束下标是否越界
			if end > len(datas) {
				end = len(datas)
			}
			datas = datas[start:end]
		} else {
			datas = make([]QueryRecieptOrderRsp, 0)
		}
	}

	// 查询成功返回
	logger.GetLogger().Debugln("QueryRecieptOrder successed: %v", datas)
	if req.PageSize > 0 {
		// 分页
		appG.ResponseByPage(http.StatusOK, e.SUCCESS, datas, app.PageInfo{Page: req.Page, PageSize: req.PageSize, Total: total})
	} else {
		// 不分页
		appG.Response(http.StatusOK, e.SUCCESS, datas)
	}
}
