package apis

import (
	"errors"
	"fmt"
	"go-admin/common/global"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"

	"go-admin/app/admin/models"
	"go-admin/app/admin/service"
	"go-admin/app/admin/service/dto"
	"go-admin/common/actions"
)

type LinePreOrder struct {
	api.Api
}

// GetPage 获取委托管理列表
// @Summary 获取委托管理列表
// @Description 获取委托管理列表
// @Tags 委托管理
// @Param apiId query string false "api用户"
// @Param symbol query string false "交易对"
// @Param quoteSymbol query string false "计较货币"
// @Param signPriceType query string false "对标价类型: new=最新价格;tall=24小时最高;low=24小时最低;mixture=标记价;entrust=委托实价;add=补仓"
// @Param rate query string false "下单百分比"
// @Param site query string false "购买方向:BUY=买;SELL=卖"
// @Param orderSn query string false "订单号"
// @Param orderType query string false "订单类型:1=现货;2=合约;3=合约止盈;4=合约止损;5=现货止盈;6=现货止损;7=止损补仓;8=现货加仓；9=现货平仓;10 = 合约止损补仓,11=合约加仓；12=合约平仓"
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {object} response.Response{data=response.Page{list=[]models.LinePreOrder}} "{"code": 200, "data": [...]}"
// @Router /api/v1/line-pre-order [get]
// @Security Bearer
func (e LinePreOrder) GetPage(c *gin.Context) {
	req := dto.LinePreOrderGetPageReq{}
	s := service.LinePreOrder{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	p := actions.GetPermissionFromContext(c)
	list := make([]models.LinePreOrder, 0)
	var count int64

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取委托管理失败，\r\n失败信息 %s", err.Error()))
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// GetOrderPage 获取LinePreOrder列表
func (e LinePreOrder) GetOrderPage(c *gin.Context) {
	req := dto.LinePreOrderGetPageReq{}
	s := service.LinePreOrder{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	p := actions.GetPermissionFromContext(c)
	list := make([]models.LinePreOrder, 0)
	var count int64

	err = s.GetOrderPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取委托管理失败，\r\n失败信息 %s", err.Error()))
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

func (e LinePreOrder) GetChildOrderList(c *gin.Context) {
	s := service.LinePreOrder{}
	req := dto.GetChildOrderReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	if req.Id <= 0 {
		e.Error(500, err, "参数错误")
		return
	}
	p := actions.GetPermissionFromContext(c)
	list := make([]models.LinePreOrder, 0)

	err = s.GetChildList(&req, p, &list)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取子订单信息失败，\r\n失败信息 %s", err.Error()))
		return
	}
	e.OK(list, "操作成功")
}

// Get 获取委托管理
// @Summary 获取委托管理
// @Description 获取委托管理
// @Tags 委托管理
// @Param id path int false "id"
// @Success 200 {object} response.Response{data=models.LinePreOrder} "{"code": 200, "data": [...]}"
// @Router /api/v1/line-pre-order/{id} [get]
// @Security Bearer
func (e LinePreOrder) Get(c *gin.Context) {
	req := dto.LinePreOrderGetReq{}
	s := service.LinePreOrder{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var object models.LinePreOrder

	p := actions.GetPermissionFromContext(c)
	err = s.Get(&req, p, &object)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取委托管理失败，\r\n失败信息 %s", err.Error()))
		return
	}

	e.OK(object, "查询成功")
}

// Insert 创建委托管理
// @Summary 创建委托管理
// @Description 创建委托管理
// @Tags 委托管理
// @Accept application/json
// @Product application/json
// @Param data body dto.LinePreOrderInsertReq true "data"
// @Success 200 {object} response.Response	"{"code": 200, "message": "添加成功"}"
// @Router /api/v1/line-pre-order [post]
// @Security Bearer
func (e LinePreOrder) Insert(c *gin.Context) {
	req := dto.LinePreOrderInsertReq{}
	s := service.LinePreOrder{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	// 设置创建人
	req.SetCreateBy(user.GetUserId(c))

	err = s.Insert(&req)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("创建委托管理失败，\r\n失败信息 %s", err.Error()))
		return
	}

	e.OK(req.GetId(), "创建成功")
}

// Update 修改委托管理
// @Summary 修改委托管理
// @Description 修改委托管理
// @Tags 委托管理
// @Accept application/json
// @Product application/json
// @Param id path int true "id"
// @Param data body dto.LinePreOrderUpdateReq true "body"
// @Success 200 {object} response.Response	"{"code": 200, "message": "修改成功"}"
// @Router /api/v1/line-pre-order/{id} [put]
// @Security Bearer
func (e LinePreOrder) Update(c *gin.Context) {
	req := dto.LinePreOrderUpdateReq{}
	s := service.LinePreOrder{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	req.SetUpdateBy(user.GetUserId(c))
	p := actions.GetPermissionFromContext(c)

	err = s.Update(&req, p)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("修改委托管理失败，\r\n失败信息 %s", err.Error()))
		return
	}
	e.OK(req.GetId(), "修改成功")
}

// Delete 删除委托管理
// @Summary 删除委托管理
// @Description 删除委托管理
// @Tags 委托管理
// @Param data body dto.LinePreOrderDeleteReq true "body"
// @Success 200 {object} response.Response	"{"code": 200, "message": "删除成功"}"
// @Router /api/v1/line-pre-order [delete]
// @Security Bearer
func (e LinePreOrder) Delete(c *gin.Context) {
	s := service.LinePreOrder{}
	req := dto.LinePreOrderDeleteReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	// req.SetUpdateBy(user.GetUserId(c))
	p := actions.GetPermissionFromContext(c)

	err = s.Remove(&req, p)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("删除委托管理失败，\r\n失败信息 %s", err.Error()))
		return
	}
	e.OK(req.GetId(), "删除成功")
}

// AddPreOrder 单个添加
func (e LinePreOrder) AddPreOrder(c *gin.Context) {
	s := service.LinePreOrder{}
	req := dto.LineAddPreOrderReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	err = req.CheckParams()
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	if err := req.Valid(); err != nil {
		e.Error(500, err, err.Error())
		return
	}

	userId := user.GetUserId(c)

	if userId <= 0 {
		e.Error(500, errors.New("用户不存在"), "用户不存在")
		return
	}

	p := actions.GetPermissionFromContext(c)
	req.SetCreateBy(userId)
	errs := make([]error, 0)
	errStr := make([]string, 0)
	var msg string

	if err := s.AddPreOrderCheck(&req, p, &errs); err != nil {
		e.Error(500, err, err.Error())
		return
	}

	if len(errs) > 0 {
		for _, err2 := range errs {
			errStr = append(errStr, err2.Error())
		}

		msg = strings.Join(errStr, ",")
	}

	e.OK(msg, "操作成功")
}

// // 手动加仓
// func (e LinePreOrder) AddPosition(c *gin.Context) {
// 	s := service.LinePreOrder{}
// 	req := dto.LinePreOrderAddPositionReq{}
// 	err := e.MakeContext(c).
// 		MakeOrm().
// 		Bind(&req).
// 		MakeService(&s.Service).
// 		Errors
// 	if err != nil {
// 		e.Logger.Error(err)
// 		e.Error(500, err, err.Error())
// 		return
// 	}

// 	if err := req.Valid(); err != nil {
// 		e.Error(500, err, err.Error())
// 		return
// 	}

// 	err = s.AddPosition(&req)

// 	if err != nil {
// 		e.Error(500, nil, err.Error())
// 		return
// 	}
// 	e.OK(nil, "操作成功")
// }

// BatchAddOrder 批量添加
func (e LinePreOrder) BatchAddOrder(c *gin.Context) {
	s := service.LinePreOrder{}
	req := dto.LineBatchAddPreOrderReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	err = req.CheckParams()
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	p := actions.GetPermissionFromContext(c)
	errs := make([]error, 0)
	errStr := make([]string, 0)
	userId := user.GetUserId(c)
	var msg string
	if userId <= 0 {
		e.Error(500, nil, "用户不存在")
		return
	}
	req.SetCreateBy(userId)
	if err := s.AddBatchPreOrder(&req, p, &errs); err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	if len(errs) > 0 {
		//e.Logger.Error(err)
		for _, err2 := range errs {
			errStr = append(errStr, err2.Error())
		}
		msg = strings.Join(errStr, ",")
	}
	e.OK(msg, "操作成功")
}

// QuickAddPreOrder 模板快速下单
func (e LinePreOrder) QuickAddPreOrder(c *gin.Context) {
	s := service.LinePreOrder{}
	req := dto.QuickAddPreOrderReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	if req.Ids == "" {
		e.Error(500, err, "参数错误")
		return
	}
	p := actions.GetPermissionFromContext(c)
	errs := make([]error, 0)
	errStr := make([]string, 0)
	userId := user.GetUserId(c)
	var msg string

	if userId <= 0 {
		e.Error(500, nil, "用户不存在")
		return
	}

	if err := s.QuickAddPreOrder(&req, p, userId, &errs); err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	if len(errs) > 0 {
		//e.Logger.Error(err)
		for _, err2 := range errs {
			errStr = append(errStr, err2.Error())
		}

		msg = strings.Join(errStr, ",")
	}
	e.OK(msg, "操作成功")

}

// Lever 设置杠杆
func (e LinePreOrder) Lever(c *gin.Context) {
	s := service.LinePreOrder{}
	req := dto.LeverReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	err = req.CheckParams()
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	errs := make([]error, 0)
	errStr := make([]string, 0)
	p := actions.GetPermissionFromContext(c)

	s.Lever(&req, p, &errs)
	if len(errs) > 0 {
		for _, err2 := range errs {
			errStr = append(errStr, err2.Error())
		}
		e.Error(500, nil, strings.Join(errStr, ","))
		return
	}
	e.OK(nil, "操作成功")
}

// MarginType 设置仓位模式
func (e LinePreOrder) MarginType(c *gin.Context) {
	s := service.LinePreOrder{}
	req := dto.MarginTypeReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	err = req.CheckParams()
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	errs := make([]error, 0)
	errStr := make([]string, 0)
	p := actions.GetPermissionFromContext(c)

	s.MarginType(&req, p, &errs)
	if len(errs) > 0 {
		for _, err2 := range errs {
			errStr = append(errStr, err2.Error())
		}
		e.Error(500, nil, strings.Join(errStr, ","))
		return
	}
	e.OK(nil, "操作成功")
}

// CancelOpenOrder 取消指定交易对的委托
func (e LinePreOrder) CancelOpenOrder(c *gin.Context) {
	s := service.LinePreOrder{}
	req := dto.CancelOpenOrderReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	if req.ApiId <= 0 {
		e.Error(500, err, "参数错误")
		return
	}
	errs := make([]error, 0)
	errStr := make([]string, 0)
	if req.ExchangeType == global.EXCHANGE_BINANCE {
		s.CancelOpenOrder(&req, &errs)
	}
	if len(errs) > 0 {
		for _, err2 := range errs {
			errStr = append(errStr, err2.Error())
		}
		e.Error(500, nil, strings.Join(errStr, ","))
		return
	}
	e.OK(nil, "操作成功")
}

// ClearAll 一键清除数据
func (e LinePreOrder) ClearAll(c *gin.Context) {
	s := service.LinePreOrder{}
	req := dto.MarginTypeReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	err = s.ClearAll()
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	e.OK(nil, "操作成功")
}

// ClosePosition 平仓
func (e LinePreOrder) ClosePosition(c *gin.Context) {
	s := service.LinePreOrder{}
	req := dto.ClosePosition{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	err = req.CheckParams()
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	errs := make([]error, 0)
	errStr := make([]string, 0)

	if req.ExchangeType == global.EXCHANGE_BINANCE {
		if req.CloseType == 1 {
			s.SpotClosePosition(&req, &errs)
		} else {
			s.FutClosePosition(&req, &errs)
		}
	}
	if len(errs) > 0 {
		for _, err2 := range errs {
			errStr = append(errStr, err2.Error())
		}
		e.Error(500, nil, strings.Join(errStr, ","))
		return
	}
	e.OK(nil, "操作成功")
}

// ClearUnTriggered 清除待触发的交易对
func (e LinePreOrder) ClearUnTriggered(c *gin.Context) {
	s := service.LinePreOrder{}
	err := e.MakeContext(c).
		MakeOrm().
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	err = s.ClearUnTriggered()
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.OK(nil, "操作成功")
}

func (e LinePreOrder) QueryOrder(c *gin.Context) {
	s := service.LinePreOrder{}
	req := dto.QueryOrderReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	res, err := s.QueryOrder(&req)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.OK(res, "操作成功")
}

func (e LinePreOrder) QueryAiCoinPrice(c *gin.Context) {
	s := service.LinePreOrder{}
	req := dto.QueryAiCoinPriceReq{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	res, err := s.QueryAiCoinPrice(&req)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}
	e.OK(res, "操作成功")
}

// 计算回本盈利比例
func (e LinePreOrder) CalculateBreakEevenRatio(c *gin.Context) {
	s := service.LinePreOrder{}
	req := dto.LineAddPreOrderReq{}

	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	if req.Symbol == "" {
		return
	}

	err = s.GenerateOrder(&req)
	if err != nil {
		e.Error(500, err, err.Error())
		return
	}

	e.OK(req, "操作成功")
}
