package szdz

import (
	"encoding/json"
	"fmt"
	"mtp2_if/db"
	"mtp2_if/global/app"
	"mtp2_if/global/e"
	"mtp2_if/logger"
	"mtp2_if/models"
	"mtp2_if/utils"
	"net/http"
	"sort"
	"strconv"
	"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 /SZDZ/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)
	}
}

// QueryGoodsPickupReq 商品提货单查询请求参数
type QueryGoodsPickupReq struct {
	AccountID       string `form:"accountID" binding:"required"`
	TakeOrderStatus int    `form:"takeOrderStatus"`
}

// QueryGoodsPickupRsp  商品提货单查询返回模型
type QueryGoodsPickupRsp struct {
	models.Szdz3goodspickup `xorm:"extends"`
	Goodscode               string `json:"goodscode"  xorm:"'GOODSCODE'"` // 商品代码
	Goodsname               string `json:"goodsname"  xorm:"'GOODSNAME'"` // 商品名称
}

// QueryGoodsPickup 商品提货单查询
// @Summary 商品提货单查询
// @Produce json
// @Security ApiKeyAuth
// @Param accountID query string true "资金账户 - 格式：1,2,3"
// @Param takeOrderStatus query int false "提货状态 - 1:待发货 2:已发货 3:已收货"
// @Success 200 {object} QueryGoodsPickupRsp
// @Failure 500 {object} app.Response
// @Router /SZDZ/QueryGoodsPickup [get]
// @Tags 定制【尚志大宗】
func QueryGoodsPickup(c *gin.Context) {
	appG := app.Gin{C: c}

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

	datas := make([]QueryGoodsPickupRsp, 0)
	engine := db.GetEngine()
	s := engine.Join("INNER", "GOODS", "GOODS.GOODSID = SZDZ3_GOODSPICKUP.GOODSID").
		Select("to_char(SZDZ3_GOODSPICKUP.TAKEORDERID) as TAKEORDERID, SZDZ3_GOODSPICKUP.*, GOODS.GOODSCODE, GOODS.GOODSNAME").
		Where(fmt.Sprintf(`SZDZ3_GOODSPICKUP.ACCOUNTID in (%s)`, req.AccountID)).
		Desc("SZDZ3_GOODSPICKUP.TAKEORDERID")
	if req.TakeOrderStatus > 0 {
		s = s.And("SZDZ3_GOODSPICKUP.TAKEORDERSTATUS = ?", req.TakeOrderStatus)
	}
	if err := s.Find(&datas); err != nil {
		// 查询失败
		logger.GetLogger().Errorf("QueryGoodsPickup failed: %s", err.Error())
		appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
		return
	}

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

// QueryConvertLogReq 交易系统转换流水查询请求参数
type QueryConvertLogReq struct {
	AccountID string `form:"accountID" binding:"required"`
	StartDate string `form:"startDate"`
	EndDate   string `form:"endDate"`
}

// QueryConvertLogRsp 交易系统转换流水查询返回模型
type QueryConvertLogRsp struct {
	models.Szdz3convertlog `xorm:"extends"`
	Goodscode              string `json:"goodscode"  xorm:"'GOODSCODE'"` // 商品代码
	Goodsname              string `json:"goodsname"  xorm:"'GOODSNAME'"` // 商品名称
	QTY                    string `json:"qty"`                           // 数量
}

// QueryConvertLog 交易系统转换流水查询
// @Summary 交易系统转换流水查询
// @Produce json
// @Security ApiKeyAuth
// @Param accountID query string true "资金账户 - 格式：1,2,3"
// @Param startDate query string false "开始时间 - 闭区间，格式：yyyy-MM-dd HH:mm:ss"
// @Param endDate query string false "结束时间 - 闭区间，格式：yyyy-MM-dd HH:mm:ss"
// @Success 200 {object} QueryConvertLogRsp
// @Failure 500 {object} app.Response
// @Router /SZDZ/QueryConvertLog [get]
// @Tags 定制【尚志大宗】
func QueryConvertLog(c *gin.Context) {
	appG := app.Gin{C: c}

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

	datas := make([]QueryConvertLogRsp, 0)
	engine := db.GetEngine()
	s := engine.Join("INNER", "GOODS", "GOODS.GOODSID = SZDZ3_CONVERTLOG.INNERGOODSID").
		Select("SZDZ3_CONVERTLOG.*, GOODS.GOODSCODE, GOODS.GOODSNAME").
		Where(fmt.Sprintf(`SZDZ3_CONVERTLOG.HandleStatus = 1 and SZDZ3_CONVERTLOG.ACCOUNTID in (%s)`, req.AccountID)).
		Desc("SZDZ3_CONVERTLOG.LOGID")
	if len(req.StartDate) > 0 {
		s = s.And(fmt.Sprintf(`SZDZ3_CONVERTLOG.CREATETIME >= to_date('%s','yyyy-MM-dd hh24:mi:ss')`, req.StartDate))
	}
	if len(req.EndDate) > 0 {
		s = s.And(fmt.Sprintf(`SZDZ3_CONVERTLOG.CREATETIME <= to_date('%s','yyyy-MM-dd hh24:mi:ss')`, req.EndDate))
	}
	if err := s.Find(&datas); err != nil {
		// 查询失败
		logger.GetLogger().Errorf("QueryConvertLog failed: %s", err.Error())
		appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
		return
	}

	// 计算数量
	for i, v := range datas {
		queryConvertLog := &datas[i]
		// 方向
		direction := "-"
		// 数量
		qty := v.Outvalue
		if v.Converttype == 1 || v.Converttype == 2 || v.Converttype == 5 {
			direction = "+"
			qty = v.Invalue
		}
		queryConvertLog.QTY = fmt.Sprintf("%s%v", direction, qty)
	}

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

// SearchWhiteReq 搜索白名单请求参数
type SearchWhiteReq struct {
	UserID int `form:"userID" binding:"required"`
}

// SearchWhite 搜索白名单
// @Summary 搜索白名单
// @Produce json
// @Security ApiKeyAuth
// @Param userID query int true "用户ID"
// @Success 200 {object} models.Szdz3searchwhitelist
// @Failure 500 {object} app.Response
// @Router /SZDZ/SearchWhite [get]
// @Tags 定制【尚志大宗】
func SearchWhite(c *gin.Context) {
	appG := app.Gin{C: c}

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

	datas := make([]models.Szdz3searchwhitelist, 0)
	engine := db.GetEngine()
	if err := engine.Where("USERID = ?", req.UserID).Find(&datas); err != nil {
		// 查询失败
		logger.GetLogger().Errorf("SearchWhite failed: %s", err.Error())
		appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
		return
	}

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

// QueryConvertConfigReq 查询交易系统转换设置请求参数
type QueryConvertConfigReq struct {
	ConvertType    int    `form:"convertType"`    // 转换类型 - 1:金点赞转交易 2:金点拍转交易 3:交易转金点赞(不设置) 4:交易转金点拍(不设置) 5:花生米转交易 6:交易转花生米(不设置)
	OuterGoodsCode string `form:"outerGoodsCode"` // 外部商品代码[JD\PD]
	InnerGoodsIDs  string `form:"innerGoodsIDs"`  // 内部商品ID列表[交易]
}

// QueryConvertConfig 查询交易系统转换设置
// @Summary 查询交易系统转换设置
// @Produce json
// @Security ApiKeyAuth
// @Param convertType query int false "转换类型 - 1:金点赞转交易 2:金点拍转交易 3:交易转金点赞(不设置) 4:交易转金点拍(不设置) 5:花生米转交易 6:交易转花生米(不设置)"
// @Param outerGoodsCode query string false "外部商品代码[JD\PD]"
// @Param innerGoodsIDs query string false "内部商品ID列表[交易]，格式：1,2,3"
// @Success 200 {object} models.Szdz3convertconfig
// @Failure 500 {object} app.Response
// @Router /SZDZ/QueryConvertConfig [get]
// @Tags 定制【尚志大宗】
func QueryConvertConfig(c *gin.Context) {
	appG := app.Gin{C: c}

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

	datas := make([]models.Szdz3convertconfig, 0)
	engine := db.GetEngine()
	s := engine.Table("SZDZ3_CONVERTCONFIG")
	if req.ConvertType > 0 {
		s = s.And("CONVERTTYPE = ?", req.ConvertType)
	}
	if len(req.OuterGoodsCode) > 0 {
		s = s.And("OUTERGOODSCODE = ?", req.OuterGoodsCode)
	}
	if len(req.InnerGoodsIDs) > 0 {
		s = s.And(fmt.Sprintf("INNERGOODSID in (%s)", req.InnerGoodsIDs))
	}
	if err := s.Find(&datas); err != nil {
		// 查询失败
		logger.GetLogger().Errorf("QueryConvertConfigReq failed: %s", err.Error())
		appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
		return
	}

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

// QuerySZDZTradePositionReq 持仓汇总查询请求参数（尚志大宗）
type QuerySZDZTradePositionReq struct {
	AccountID int `form:"accountID" binding:"required"`
}

// QuerySZDZTradePositionRsp 持仓汇总查询返回模型（尚志大宗）
type QuerySZDZTradePositionRsp struct {
	Accountid       int64   `json:"accountid"  xorm:"'ACCOUNTID'"`             // 账号Id
	Goodsid         int64   `json:"goodsid"  xorm:"'GOODSID'"`                 // 商品Id
	Positionqty     int64   `json:"positionqty"  xorm:"'POSITIONQTY'"`         // 期初持仓数量
	Holderamount    float64 `json:"holderamount"  xorm:"'HOLDERAMOUNT'"`       // 期初持仓总金额
	Curpositionqty  int64   `json:"curpositionqty"  xorm:"'CURPOSITIONQTY'"`   // 当前持仓总数量
	Curholderamount float64 `json:"curholderamount"  xorm:"'CURHOLDERAMOUNT'"` // 当前持仓总金额
	Frozenqty       int64   `json:"frozenqty"  xorm:"'FROZENQTY'"`             // 持仓冻结数量
	Otherfrozenqty  int64   `json:"otherfrozenqty"  xorm:"'OTHERFROZENQTY'"`   // 持仓其他冻结数量(交割冻结)
	Openreqqty      int64   `json:"openreqqty"  xorm:"'OPENREQQTY'"`           // 开仓申请数量
	Opentotalqty    int64   `json:"opentotalqty"  xorm:"'OPENTOTALQTY'"`       // 开仓总数量
	Closetotalqty   int64   `json:"closetotalqty"  xorm:"'CLOSETOTALQTY'"`     // 平仓总数量
	Tnqty           int64   `json:"tnqty"  xorm:"'TNQTY'"`                     // T+N冻结总量
	Tnusedqty       int64   `json:"tnusedqty"  xorm:"'TNUSEDQTY'"`             // T+N使用量
	Usedmargin      float64 `json:"usedmargin"  xorm:"'USEDMARGIN'"`           // 占用保证金
	Curtdposition   int64   `json:"curtdposition"  xorm:"'CURTDPOSITION'"`     // 期末今日头寸
	Fretdposition   int64   `json:"fretdposition"  xorm:"'FRETDPOSITION'"`     // 冻结今日头寸
	Goodscode       string  `json:"goodscode"  xorm:"'GOODSCODE'"`             // 商品代码(内部)
	Goodsname       string  `json:"goodsname"  xorm:"'GOODSNAME'"`             // 商品名称
	Currencyid      int64   `json:"currencyid"  xorm:"'CURRENCYID'"`           // 报价货币ID
	Goodunitid      int64   `json:"goodunitid"  xorm:"'GOODUNITID'"`           // 报价单位ID
	Goodunit        string  `json:"goodunit" xorm:"'GOODUNIT'"`                // 报价单位
	Agreeunit       float64 `json:"agreeunit"  xorm:"'AGREEUNIT'"`             // 合约单位
	Decimalplace    int64   `json:"decimalplace"  xorm:"'DECIMALPLACE'"`       // 报价小数位
	Marketid        int32   `json:"marketid"  xorm:"'MARKETID'"`               // 市场ID
	Trademode       int32   `json:"trademode"  xorm:"'TRADEMODE'"`             // 交易模式
	SZDZ3FreezQTY   int64   `json:"szdz3freezqty" xorm:"'SZDZ3FREEZQTY'"`      // 尚志大宗转换冻结总数量

	BuyOrSell    int64   `json:"buyorsell"  xorm:"'BUYORSELL'" `   // 方向 - 0:买 1:卖
	EnableQTY    int64   `json:"enableqty"  xorm:"'ENABLEQTY'"`    // 可用量
	AveragePrice float64 `json:"averageprice" xorm:"AVERAGEPRICE"` // 持仓均价
}

// QuerySZDZTradePosition 持仓汇总查询（尚志大宗）
// @Summary 持仓汇总查询（尚志大宗）
// @Produce json
// @Security ApiKeyAuth
// @Param accountID query int true "资金账户"
// @Success 200 {object} QuerySZDZTradePositionRsp
// @Failure 500 {object} app.Response
// @Router /SZDZ/QuerySZDZTradePosition [get]
// @Tags 定制【尚志大宗】
func QuerySZDZTradePosition(c *gin.Context) {
	appG := app.Gin{C: c}

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

	// 查询数据
	datas, err := models.GetSZDZBuyTradePosition(req.AccountID)
	if err != nil {
		// 查询失败
		logger.GetLogger().Errorf("QueryConvertConfigReq failed: %s", err.Error())
		appG.Response(http.StatusBadRequest, e.ERROR_QUERY_FAIL, nil)
		return
	}
	// 构建返回数据
	rst := make([]QuerySZDZTradePositionRsp, 0)
	for _, v := range datas {
		var tradePosition QuerySZDZTradePositionRsp
		// 反射数据
		// struct -> json
		if jsonBytes, err := json.Marshal(v); err == nil {
			// json -> struct
			json.Unmarshal(jsonBytes, &tradePosition)

			tradePosition.Accountid = v.Accountid
			tradePosition.Goodsid = v.Goodsid
			tradePosition.Positionqty = v.Positionqty
			tradePosition.Holderamount = v.Holderamount
			tradePosition.Curholderamount = v.Curholderamount
			tradePosition.Otherfrozenqty = v.Otherfrozenqty
			tradePosition.Openreqqty = v.Openreqqty
			tradePosition.Opentotalqty = v.Opentotalqty
			tradePosition.Closetotalqty = v.Closetotalqty
			tradePosition.Tnqty = v.Tnqty
			tradePosition.Tnusedqty = v.Tnusedqty
			tradePosition.Usedmargin = v.Usedmargin
			tradePosition.Curtdposition = v.Curtdposition
			tradePosition.Fretdposition = v.Fretdposition
			tradePosition.Goodscode = v.Goodscode
			tradePosition.Goodsname = v.Goodsname
			tradePosition.Currencyid = v.Currencyid
			tradePosition.Goodunitid = v.Goodunitid
			tradePosition.Goodunit = v.Goodunit
			tradePosition.Agreeunit = v.Agreeunit
			tradePosition.Decimalplace = v.Decimalplace
			tradePosition.Marketid = v.Marketid
			tradePosition.Trademode = v.Trademode
			tradePosition.SZDZ3FreezQTY = v.SZDZ3FreezQTY

			// 计算相关
			tradePosition.Frozenqty = v.Frozenqty + v.SZDZ3FreezQTY // 需要加上
			tradePosition.Curpositionqty = v.Curpositionqty + v.SZDZ3FreezQTY
			tradePosition.EnableQTY = v.Curpositionqty - v.Frozenqty - v.Otherfrozenqty
			averagePrice := tradePosition.Curholderamount / float64(tradePosition.Curpositionqty) / tradePosition.Agreeunit
			tradePosition.AveragePrice, _ = strconv.ParseFloat(utils.FormatFloat(averagePrice, int(v.Decimalplace)), 64)
			tradePosition.BuyOrSell = 0

			rst = append(rst, tradePosition)
		}
	}

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