<?php

namespace app\admin\service;

use app\admin\service\setting\IPOService;
use app\admin\validate\OrderValidate;
use app\model\ContractSecTradeModel;
use app\model\ContractTradeModel;
use app\model\DigitalTradeModel;
use app\model\ForexTradeModel;
use app\model\PreBrlStockModel;
use app\model\PreEurStockModel;
use app\model\PreFundStockModel;
use app\model\PreFurStockModel;
use app\model\PreGBXStockModel;
use app\model\PreHkdStockModel;
use app\model\PreIdnStockModel;
use app\model\PreInStockModel;
use app\model\PreMysStockModel;
use app\model\PreThaStockModel;
use app\model\PreUsStockModel;
use app\model\StockHkdListModel;
use app\model\StockHkdTradeModel;
use app\model\StockIdnListModel;
use app\model\StockIdnTradeModel;
use app\model\StockInListModel;
use app\model\StockInTradeModel;
use app\model\StockListModel;
use app\model\StockMysListModel;
use app\model\StockMysTradeModel;
use app\model\StockOptionInrTradeModel;
use app\model\StockSgdTradeModel;
use app\model\StockThaListModel;
use app\model\StockThaTradeModel;
use app\model\StockTradeModel;
use app\model\UserArrearsModel;
use app\model\UserBrlPreStockOrderModel;
use app\model\UserEurPreStockOrderModel;
use app\model\UserFundPreStockOrderModel;
use app\model\UserFurPreStockOrderModel;
use app\model\UserGBXPreStockOrderModel;
use app\model\UserHkdPreStockOrderModel;
use app\model\UserIdnPreStockOrderModel;
use app\model\UserInPreStockOrderModel;
use app\model\UserModel;
use app\model\UserMysPreStockOrderModel;
use app\model\UserStockBlockOrderModel;
use app\model\UserStockEurLogModel;
use app\model\UserStockFundInterestReceiptModel;
use app\model\UserThaPreStockOrderModel;
use app\model\UserUsPreStockOrderModel;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Log;

class OrderService extends AdminBaseService
{

    ######################################## 现货交易 #######################################

    // 现货持仓
    public function digitalPlace($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('digitalPlace')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $where = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($where)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }
            if (!empty($where['user_id']) && is_numeric($where['user_id']) && $where['user_id'] == 0) {
                return $this->toData('1', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0,
                ]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['digital_id'])) {
                $where['digital_id'] = $param['digital_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['create_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = DigitalTradeModel::where('status', DigitalTradeModel::STATUS_PLACE)->where($where)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = DigitalTradeModel::where('status', DigitalTradeModel::STATUS_PLACE)
                ->where($where)
                ->count();
            // 持仓总金额
            $totalModel = DigitalTradeModel::where('status', DigitalTradeModel::STATUS_PLACE)
                ->field('SUM(order_money) as total')
                ->where($where)->find();

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    $rows[] = [
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'order_id' => $item['order_id'], // 用户号
                        'trade_id' => $item['trade_id'], //
                        'trade_type' => $item['trade_type'], //
                        'trade_type_name' => $item['trade_type'] == DigitalTradeModel::TRADE_TYPE_BUY ? '买入' : '卖出', //交易类型
                        'create_time' => $item['create_time'], // 挂单时间
                        'order_money' => $item['order_money'], // 订单金额
                        'digital_id' => $item['digital_id'], // 股票代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'deal_price' => $item['deal_price'], // 开仓价
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4),
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }

    }

    // 现货撤单
    public function digitalBack($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('digitalBack')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['digital_id'])) {
                $where['digital_id'] = $param['digital_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['create_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = DigitalTradeModel::where('status', DigitalTradeModel::STATUS_BACk)
                ->where($where)->where($whereU)
                ->order('trade_id', 'desc')
                ->page($param['page'], $param['limit'])->select();
            // 总数
            $total = DigitalTradeModel::where('status', DigitalTradeModel::STATUS_BACk)
                ->where($where)->where($whereU)
                ->count();
            // 持仓总金额
            $totalModel = DigitalTradeModel::where('status', DigitalTradeModel::STATUS_BACk)
                ->field('SUM(order_money) as total')
                ->where($where)->where($whereU)->find();

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'order_id' => $item['order_id'], // 用户号
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'trade_type' => $item['trade_type'], //
                        'trade_type_name' => $item['trade_type'] == DigitalTradeModel::TRADE_TYPE_BUY ? '买入' : '卖出', //交易类型
                        'create_time' => $item['create_time'], // 挂单时间
                        'update_time' => $item['update_time'], // 撤单时间
                        'order_money' => $item['order_money'], // 订单金额
                        'digital_id' => $item['digital_id'], // 股票代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'deal_price' => $item['deal_price'], // 开仓价
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4),
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }

    }

    // 现货订单
    public function digitalDeal($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('digitalDeal')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['digital_id'])) {
                $where['digital_id'] = $param['digital_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['create_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = DigitalTradeModel::where('status', DigitalTradeModel::STATUS_SUCCESS)
                ->where($where)->where($whereU)
                ->order('trade_id', 'desc')
                ->page($param['page'], $param['limit'])->select();
            // 总数
            $total = DigitalTradeModel::where('status', DigitalTradeModel::STATUS_SUCCESS)
                ->where($where)->where($whereU)
                ->count();
            // 持仓总金额
            $totalModel = DigitalTradeModel::where('status', DigitalTradeModel::STATUS_SUCCESS)
                ->field('SUM(order_money) as total')
                ->where($where)->where($whereU)->find();

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'order_id' => $item['order_id'], // 用户号
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'trade_type' => $item['trade_type'], //
                        'trade_type_name' => $item['trade_type'] == DigitalTradeModel::TRADE_TYPE_BUY ? '买入' : '卖出', //交易类型
                        'create_time' => $item['create_time'], // 挂单时间
                        'closing_time' => $item['closing_time'], // 完成时间
                        'order_money' => $item['order_money'], // 订单金额
                        'digital_id' => $item['digital_id'], // 股票代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['closing_cost'], // 服务费
                        'deal_price' => $item['closing_price'], // 平仓价
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4),
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }

    }


    ######################################## 外汇交易 #######################################

    // 合约持仓
    public function forexHold($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('forexHold')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['contract_id'])) {
                $where['contract_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['open_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = ForexTradeModel::where('status', ForexTradeModel::STATUS_HOLD)->where($where)->where($whereU)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = ForexTradeModel::where('status', ForexTradeModel::STATUS_HOLD)
                ->where($where)->where($whereU)
                ->count();
            // 持仓总金额
            $totalModel = ForexTradeModel::where('status', ForexTradeModel::STATUS_HOLD)
                ->field('SUM(order_money) as total')
                ->where($where)->where($whereU)->find();

            // 持仓总手续费
            $totalServiceCost = ForexTradeModel::where('status', ForexTradeModel::STATUS_HOLD)
                ->where($where)->where($whereU)
                ->sum('service_cost');

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'order_id' => $item['order_id'], // 用户号
                        'open_time' => $item['open_time'], // 挂单时间
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'order_money' => $item['order_money'], // 订单金额
                        'contract_id' => $item['contract_id'], // 合约代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'float' => '-', // 浮动盈亏
                        'face_value' => $item['face_value'], // 浮动盈亏
                        'deal_price' => $item['deal_price'], // 开仓价
                        'now_price' => '-', // 当前价
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4), 'totalServiceCost' => $totalServiceCost,
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 合约持仓
    public function forexPlace($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('forexPlace')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['contract_id'])) {
                $where['contract_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['create_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = ForexTradeModel::where('status', ForexTradeModel::STATUS_PLACE)->where($where)->where($whereU)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = ForexTradeModel::where('status', ForexTradeModel::STATUS_PLACE)
                ->where($where)->where($whereU)
                ->count();
            // 持仓总金额
            $totalModel = ForexTradeModel::where('status', ForexTradeModel::STATUS_PLACE)
                ->field('SUM(order_money) as total')->where($whereU)
                ->where($where)->find();

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'order_id' => $item['order_id'], // 订单号
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'create_time' => $item['create_time'], // 挂单时间
                        'order_money' => $item['order_money'], // 订单金额
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'contract_id' => $item['contract_id'], // 合约代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'deal_price' => $item['deal_price'], // 开仓价
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'face_value' => $item['face_value'], // 面值
                        'pry_num' => $item['pry_num'], // 杠杆
                        'limit_price' => $item['limit_price'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4),
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 合约撤单
    public function forexBack($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('forexBack')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['contract_id'])) {
                $where['contract_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['update_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = ForexTradeModel::where('status', ForexTradeModel::STATUS_BACK)->where($whereU)->where($where)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = ForexTradeModel::where('status', ForexTradeModel::STATUS_BACK)
                ->where($where)->where($whereU)
                ->count();
            // 持仓总金额
            $totalModel = ForexTradeModel::where('status', ForexTradeModel::STATUS_BACK)
                ->field('SUM(order_money) as total')->where($whereU)
                ->where($where)->find();


            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'order_id' => $item['order_id'], // 用户号
                        'create_time' => $item['create_time'], // 挂单时间
                        'update_time' => $item['update_time'], // 挂单时间
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'order_money' => $item['order_money'], // 订单金额
                        'contract_id' => $item['contract_id'], // 合约代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'face_value' => $item['face_value'], // 浮动盈亏
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'price' => $item['deal_type'] == 1 ? $item['limit_price'] : $item['market_price'], // 价格
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4),
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 合约持仓
    public function forexClear($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('forexClear')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['contract_id'])) {
                $where['contract_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['open_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = ForexTradeModel::where('status', ForexTradeModel::STATUS_CLEAR)->where($whereU)->where($where)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = ForexTradeModel::where('status', ForexTradeModel::STATUS_CLEAR)->where($whereU)
                ->where($where)
                ->count();

            // 持仓总手续费
            $totalClosingCost = ForexTradeModel::where('status', ForexTradeModel::STATUS_CLEAR)
                ->where($whereU)
                ->where($where)
                ->sum('closing_cost');

            $totalFloat = ForexTradeModel::where('status', ForexTradeModel::STATUS_CLEAR)
                ->where($whereU)
                ->where($where)
                ->field("SUM( CASE WHEN trade_type = 1 THEN ( closing_price - deal_price )* order_number ELSE ( deal_price - closing_price )* order_number END ) AS total")->find();

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    // 计算浮动盈亏
                    if ($item['trade_type'] == 1) {
                        $float = $item['closing_price'] - $item['deal_price'];
                    } else {
                        $float = $item['deal_price'] - $item['closing_price'];
                    }

                    // * 仓位
                    $float = @bcmul($float, $item['order_number'], 10);
                    // * 面值
                    $float = @bcmul($float, $item['face_value'], 6);

                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'order_id' => $item['order_id'], // 用户号
                        'closing_time' => $item['closing_time'], // 平仓时间
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'order_money' => $item['order_money'], // 订单金额
                        'contract_id' => $item['contract_id'], // 合约代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'closing_cost' => $item['closing_cost'], // 平仓服务费
                        'face_value' => $item['face_value'], //
                        'deal_price' => $item['deal_price'], // 开仓价
                        'closing_price' => $item['closing_price'], // 平仓价格
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'float' => $float, // 平仓盈亏
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => [
                    'totalClosingCost' => $totalClosingCost,
                    'totalFloat' => $totalFloat['total'],
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }


    ######################################## 合约交易 #######################################

    // 合约持仓
    public function contractHold($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('contractHold')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['contract_id'])) {
                $where['contract_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['open_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = ContractTradeModel::where('status', ContractTradeModel::STATUS_HOLD)->where($where)->where($whereU)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = ContractTradeModel::where('status', ContractTradeModel::STATUS_HOLD)
                ->where($where)->where($whereU)
                ->count();
            // 持仓总金额
            $totalModel = ContractTradeModel::where('status', ContractTradeModel::STATUS_HOLD)
                ->field('SUM(order_money) as total')
                ->where($where)->where($whereU)->find();

            // 持仓总手续费
            $totalServiceCost = ContractTradeModel::where('status', ContractTradeModel::STATUS_HOLD)
                ->where($where)->where($whereU)
                ->sum('service_cost');

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'order_id' => $item['order_id'], // 用户号
                        'open_time' => $item['open_time'], // 挂单时间
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'order_money' => $item['order_money'], // 订单金额
                        'contract_id' => $item['contract_id'], // 合约代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'float' => '-', // 浮动盈亏
                        'face_value' => $item['face_value'], // 浮动盈亏
                        'deal_price' => $item['deal_price'], // 开仓价
                        'now_price' => '-', // 当前价
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4), 'totalServiceCost' => $totalServiceCost,
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 合约持仓
    public function contractPlace($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('contractPlace')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['contract_id'])) {
                $where['contract_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['create_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = ContractTradeModel::where('status', ContractTradeModel::STATUS_PLACE)->where($where)->where($whereU)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = ContractTradeModel::where('status', ContractTradeModel::STATUS_PLACE)
                ->where($where)->where($whereU)
                ->count();
            // 持仓总金额
            $totalModel = ContractTradeModel::where('status', ContractTradeModel::STATUS_PLACE)
                ->field('SUM(order_money) as total')->where($whereU)
                ->where($where)->find();

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'order_id' => $item['order_id'], // 订单号
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'create_time' => $item['create_time'], // 挂单时间
                        'order_money' => $item['order_money'], // 订单金额
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'contract_id' => $item['contract_id'], // 合约代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'deal_price' => $item['deal_price'], // 开仓价
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'face_value' => $item['face_value'], // 面值
                        'pry_num' => $item['pry_num'], // 杠杆
                        'limit_price' => $item['limit_price'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4),
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 合约撤单
    public function contractBack($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('contractBack')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['contract_id'])) {
                $where['contract_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['update_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = ContractTradeModel::where('status', ContractTradeModel::STATUS_BACK)->where($whereU)->where($where)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = ContractTradeModel::where('status', ContractTradeModel::STATUS_BACK)
                ->where($where)->where($whereU)
                ->count();
            // 持仓总金额
            $totalModel = ContractTradeModel::where('status', ContractTradeModel::STATUS_BACK)
                ->field('SUM(order_money) as total')->where($whereU)
                ->where($where)->find();


            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'order_id' => $item['order_id'], // 用户号
                        'create_time' => $item['create_time'], // 挂单时间
                        'update_time' => $item['update_time'], // 挂单时间
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'order_money' => $item['order_money'], // 订单金额
                        'contract_id' => $item['contract_id'], // 合约代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'face_value' => $item['face_value'], // 浮动盈亏
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'price' => $item['deal_type'] == 1 ? $item['limit_price'] : $item['market_price'], // 价格
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4),
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 合约持仓
    public function contractClear($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('contractClear')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['contract_id'])) {
                $where['contract_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['open_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = ContractTradeModel::where('status', ContractTradeModel::STATUS_CLEAR)->where($whereU)->where($where)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = ContractTradeModel::where('status', ContractTradeModel::STATUS_CLEAR)->where($whereU)
                ->where($where)
                ->count();

            // 持仓总手续费
            $totalClosingCost = ContractTradeModel::where('status', ContractTradeModel::STATUS_CLEAR)
                ->where($whereU)
                ->where($where)
                ->sum('closing_cost');

            $totalFloat = ContractTradeModel::where('status', ContractTradeModel::STATUS_CLEAR)
                ->where($whereU)
                ->where($where)
                ->field("SUM( CASE WHEN trade_type = 1 THEN ( closing_price - deal_price )* order_number ELSE ( deal_price - closing_price )* order_number END ) AS total")->find();

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    // 计算浮动盈亏
                    if ($item['trade_type'] == 1) {
                        $float = $item['closing_price'] - $item['deal_price'];
                    } else {
                        $float = $item['deal_price'] - $item['closing_price'];
                    }

                    // * 仓位
                    $float = @bcmul($float, $item['order_number'], 10);
                    // * 面值
                    $float = @bcmul($float, $item['face_value'], 6);

                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'order_id' => $item['order_id'], // 用户号
                        'closing_time' => $item['closing_time'], // 平仓时间
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'order_money' => $item['order_money'], // 订单金额
                        'contract_id' => $item['contract_id'], // 合约代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'closing_cost' => $item['closing_cost'], // 平仓服务费
                        'face_value' => $item['face_value'], //
                        'deal_price' => $item['deal_price'], // 开仓价
                        'closing_price' => $item['closing_price'], // 平仓价格
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'float' => $float, // 平仓盈亏
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => [
                    'totalClosingCost' => $totalClosingCost,
                    'totalFloat' => $totalFloat['total'],
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }


    ######################################## 秒合约交易 #######################################

    // 合约持仓
    public function contractSecHold($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('contractHold')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['contract_id'])) {
                $where['contract_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['open_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = ContractSecTradeModel::where('status', ContractSecTradeModel::STATUS_HOLD)->where($where)->where($whereU)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = ContractSecTradeModel::where('status', ContractSecTradeModel::STATUS_HOLD)
                ->where($where)->where($whereU)
                ->count();
            // 持仓总金额
            $totalModel = ContractSecTradeModel::where('status', ContractSecTradeModel::STATUS_HOLD)
                ->field('SUM(order_money) as total')
                ->where($where)->where($whereU)->find();

            // 持仓总手续费
            $totalServiceCost = ContractSecTradeModel::where('status', ContractSecTradeModel::STATUS_HOLD)
                ->where($where)->where($whereU)
                ->sum('service_cost');

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'order_id' => $item['order_id'], // 用户号
                        'open_time' => $item['open_time'], // 挂单时间
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'order_money' => $item['order_money'], // 订单金额
                        'contract_id' => $item['contract_id'], // 合约代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'float' => '-', // 浮动盈亏
                        'face_value' => $item['face_value'], // 浮动盈亏
                        'deal_price' => $item['deal_price'], // 开仓价
                        'now_price' => '-', // 当前价
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4), 'totalServiceCost' => $totalServiceCost,
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 合约持仓
    public function contractSecPlace($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('contractPlace')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['contract_id'])) {
                $where['contract_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['create_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = ContractSecTradeModel::where('status', ContractSecTradeModel::STATUS_PLACE)->where($where)->where($whereU)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = ContractSecTradeModel::where('status', ContractSecTradeModel::STATUS_PLACE)
                ->where($where)->where($whereU)
                ->count();
            // 持仓总金额
            $totalModel = ContractSecTradeModel::where('status', ContractSecTradeModel::STATUS_PLACE)
                ->field('SUM(order_money) as total')->where($whereU)
                ->where($where)->find();

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'order_id' => $item['order_id'], // 订单号
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'create_time' => $item['create_time'], // 挂单时间
                        'order_money' => $item['order_money'], // 订单金额
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'contract_id' => $item['contract_id'], // 合约代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'deal_price' => $item['deal_price'], // 开仓价
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'face_value' => $item['face_value'], // 面值
                        'pry_num' => $item['pry_num'], // 杠杆
                        'limit_price' => $item['limit_price'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4),
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 合约撤单
    public function contractSecBack($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('contractBack')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['contract_id'])) {
                $where['contract_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['update_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = ContractSecTradeModel::where('status', ContractSecTradeModel::STATUS_BACK)->where($whereU)->where($where)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = ContractSecTradeModel::where('status', ContractSecTradeModel::STATUS_BACK)
                ->where($where)->where($whereU)
                ->count();
            // 持仓总金额
            $totalModel = ContractSecTradeModel::where('status', ContractSecTradeModel::STATUS_BACK)
                ->field('SUM(order_money) as total')->where($whereU)
                ->where($where)->find();


            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'order_id' => $item['order_id'], // 用户号
                        'create_time' => $item['create_time'], // 挂单时间
                        'update_time' => $item['update_time'], // 挂单时间
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'order_money' => $item['order_money'], // 订单金额
                        'contract_id' => $item['contract_id'], // 合约代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'face_value' => $item['face_value'], // 浮动盈亏
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'price' => $item['deal_type'] == 1 ? $item['limit_price'] : $item['market_price'], // 价格
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4),
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 合约持仓
    public function contractSecClear($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('contractClear')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['contract_id'])) {
                $where['contract_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['open_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = ContractSecTradeModel::where('status', ContractSecTradeModel::STATUS_CLEAR)->where($whereU)->where($where)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = ContractSecTradeModel::where('status', ContractSecTradeModel::STATUS_CLEAR)->where($whereU)
                ->where($where)
                ->count();

            // 持仓总手续费
            $totalClosingCost = ContractSecTradeModel::where('status', ContractSecTradeModel::STATUS_CLEAR)
                ->where($whereU)
                ->where($where)
                ->sum('closing_cost');

            $totalFloat = ContractSecTradeModel::where('status', ContractSecTradeModel::STATUS_CLEAR)
                ->where($whereU)
                ->where($where)
                ->field("SUM( CASE WHEN trade_type = 1 THEN ( closing_price - deal_price )* order_number ELSE ( deal_price - closing_price )* order_number END ) AS total")->find();

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    // 计算浮动盈亏
                    if ($item['trade_type'] == 1) {
                        $float = $item['closing_price'] - $item['deal_price'];
                    } else {
                        $float = $item['deal_price'] - $item['closing_price'];
                    }

                    // * 仓位
                    $float = @bcmul($float, $item['order_number'], 10);
                    // * 面值
                    $float = @bcmul($float, $item['face_value'], 6);

                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'order_id' => $item['order_id'], // 用户号
                        'closing_time' => $item['closing_time'], // 平仓时间
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'order_money' => $item['order_money'], // 订单金额
                        'contract_id' => $item['contract_id'], // 合约代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'closing_cost' => $item['closing_cost'], // 平仓服务费
                        'face_value' => $item['face_value'], //
                        'deal_price' => $item['deal_price'], // 开仓价
                        'closing_price' => $item['closing_price'], // 平仓价格
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'float' => $float, // 平仓盈亏
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => [
                    'totalClosingCost' => $totalClosingCost,
                    'totalFloat' => $totalFloat['total'],
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }


    ##########################################  股票交易  ###########################################
    // 股票持仓
    public function StockHold($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('stockHold')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }
            $market_type = intval($param['market_type']);
            $table_obj = (new IPOService())->getStockModel($market_type);
            if (empty($table_obj)) {
                return $this->toData('1', '数据异常');
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['stock_id'])) {
                $where['stock_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['open_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = Db::table($table_obj['trade_table'])->where('status', 1)->where($whereU)->where($where)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = Db::table($table_obj['trade_table'])->where('status', 1)
                ->where($whereU)
                ->where($where)
                ->count();
            // 持仓总金额
            $totalModel = Db::table($table_obj['trade_table'])->where('status', 1)
                ->field('SUM(order_money) as total')
                ->where($whereU)
                ->where($where)->find();

            // 持仓总手续费
            $totalServiceCost = Db::table($table_obj['trade_table'])->where('status', 1)
                ->where($whereU)
                ->where($where)
                ->sum('service_cost');

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    $orderNumber = number_format($item['order_number'], '18', '.', '');
                    $orderPrice = number_format($item['deal_price'], '18', '.', '');
                    $orderAmount = bcmul($orderNumber, $orderPrice, 18);
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'order_id' => $item['order_id'], // 用户号
                        'open_time' => $item['open_time'] ?? '-', // 挂单时间
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'order_money' => $orderAmount, // 订单金额
                        'stock_id' => $item['stock_id'], // 股票代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'float' => '-', // 浮动盈亏
                        'deal_price' => $item['deal_price'], // 开仓价
                        'now_price' => '-', // 当前价
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4), 'totalServiceCost' => $totalServiceCost,
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 股票挂单
    public function StockPlace($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('stockPlace')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['stock_id'])) {
                $where['stock_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['create_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }
            $market_type = intval($param['market_type']);
            $table_obj = (new IPOService())->getStockModel($market_type);
            if (empty($table_obj)) {
                return $this->toData('1', '数据异常');
            }

            // 列表
            $list = Db::table($table_obj['trade_table'])->where('status', 0)->where($whereU)->where($where)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = Db::table($table_obj['trade_table'])->where('status', 0)
                ->where($where)->where($whereU)
                ->count();
            // 持仓总金额
            $totalModel = Db::table($table_obj['trade_table'])->where('status', 0)
                ->field('SUM(order_money) as total')
                ->where($where)->where($whereU)->find();

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    // 挂单价
                    $price = $item['limit_price'];
                    if ($item['deal_type'] == 2) {
                        $price = $item['market_price'];
                    }

                    $orderNumber = number_format($item['order_number'], '18', '.', '');
                    $orderPrice = number_format($price, '18', '.', '');
                    $orderAmount = bcmul($orderNumber, $orderPrice, 18);
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'order_id' => $item['order_id'], // 订单号
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'create_time' => $item['create_time'], // 挂单时间
                        'order_money' => $orderAmount, // 订单金额
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'stock_id' => $item['stock_id'], // 合约代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'deal_price' => $price, // 委托价
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'limit_price' => $item['limit_price'], // 限价
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4),
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 股票撤单
    public function StockBack($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('stockBack')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }
            $market_type = intval($param['market_type']);
            $table_obj = (new IPOService())->getStockModel($market_type);
            if (empty($table_obj)) {
                return $this->toData('1', '数据异常');
            }
            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['stock_id'])) {
                $where['stock_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['update_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = Db::table($table_obj['trade_table'])->where('status', 2)->where($where)->where($whereU)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = Db::table($table_obj['trade_table'])->where('status', 2)
                ->where($where)->where($whereU)
                ->count();
            // 持仓总金额
            $totalModel = Db::table($table_obj['trade_table'])->where('status', 2)
                ->field('SUM(order_money) as total')->where($whereU)
                ->where($where)->find();


            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    // 挂单价
                    $price = $item['limit_price'];
                    if ($item['deal_type'] == 2) {
                        $price = $item['market_price'];
                    }
                    $orderNumber = number_format($item['order_number'], '18', '.', '');
                    $orderPrice = number_format($price, '18', '.', '');
                    $orderAmount = bcmul($orderNumber, $orderPrice, 18);
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'order_id' => $item['order_id'], // 用户号
                        'create_time' => $item['create_time'], // 挂单时间
                        'update_time' => $item['update_time'], // 挂单时间
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'order_money' => $orderAmount, // 订单金额
                        'stock_id' => $item['stock_id'], // 合约代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'deal_price' => $price, // 委托价
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4),
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 股票平仓
    public function StockClear($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('us_stockClear')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['contract_id'])) {
                $where['contract_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['open_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }
            $market_type = intval($param['market_type']);
            $table_obj = (new IPOService())->getStockModel($market_type);
            if (empty($table_obj)) {
                return $this->toData('1', '数据异常');
            }

            // 列表
            $list = Db::table($table_obj['trade_table'])->where('status', 3)->where($whereU)->where($where)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = Db::table($table_obj['trade_table'])->where('status', 3)
                ->where($where)->where($whereU)
                ->count();

            // 持仓总手续费
            $totalClosingCost = Db::table($table_obj['trade_table'])->where('status', 3)
                ->where($whereU)
                ->where($where)
                ->sum('closing_cost');

            $totalFloat = Db::table($table_obj['trade_table'])->where('status', 3)
                ->where($whereU)
                ->where($where)
                ->field("SUM( CASE WHEN trade_type = 1 THEN ( closing_price - deal_price )* order_number ELSE ( deal_price - closing_price )* order_number END ) AS total")->find();


            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    // 计算浮动盈亏
                    if ($item['trade_type'] == 1) {
                        $float = $item['closing_price'] - $item['deal_price'];
                    } else {
                        $float = $item['deal_price'] - $item['closing_price'];
                    }

                    $orderNumber = number_format($item['order_number'], '18', '.', '');
                    $orderPrice = number_format($item['deal_price'], '18', '.', '');
                    $float = number_format($float, '18', '.', '');

                    $float = bcmul($float, $item['order_number'], 18);
                    $orderAmount = bcmul($orderNumber, $orderPrice, 18);

                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'order_id' => $item['order_id'], // 用户号
                        'closing_time' => $item['closing_time'], // 平仓时间
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'order_money' => $orderAmount, // 订单金额
                        'stock_id' => $item['stock_id'], // 股票代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'closing_cost' => $item['closing_cost'], // 平仓服务费
                        'deal_price' => $item['deal_price'], // 开仓价
                        'closing_price' => $item['closing_price'], // 平仓价格
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'float' => $float, // 平仓盈亏
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => [
                    'totalClosingCost' => $totalClosingCost,
                    'totalFloat' => $totalFloat['total'],
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }


    ################################################# 申购订单

    // 申购订单
    public function preStock($marketType, $param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('pre_stock')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_no'])) {
                $where['order_no'] = $param['order_no'];
            }

            $tableObj = (new IPOService)->getStockModel($marketType);

            if (!empty($param['stock_code'])) {
                $stockArr = Db::table($tableObj['stock_table'])->where('stock_code', 'like', '%' . $param['stock_code'])->column('id');
                if (!empty($stockArr)) {
                    $where[] = ['pre_stock_id', 'in', $stockArr];
                }
            }
            $list = Db::table($tableObj['order_table'])->where($where)->where($whereU)->order('id', 'desc')->page($param['page'], $param['limit'])->select();
            $total = Db::table($tableObj['order_table'])->where($where)->where($whereU)->count();


            $stockTape=(new IPOService)->getStockTape($marketType);
            $tapeList = $stockTape['tape'];
            $stockTypeList = $stockTape['type'];
            $statusList = UserUsPreStockOrderModel::$statusList;

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                // stock
                $preStockId = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                    $preStockId[] = $idItem['pre_stock_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                $stockArr = Db::table($tableObj['stock_table'])->where('id', 'in', $preStockId)->column('*', 'id');

                $rows = $list->toArray();
                foreach ($rows as $key => $item) {
                    $stock = $stockArr[$item['pre_stock_id']] ?? [];
                    $rows[$key]['user_no'] = $userNoArr[$item['user_id']] ?? '-'; // 用户号
                    $rows[$key]['stock_code'] = $stock['stock_code'] ?? '-';
                    $rows[$key]['stock_name'] = $stock['stock_name'] ?? '-';
                    $rows[$key]['stock_type'] = $stock['stock_type'] ?? '-';
                    $rows[$key]['tape'] = $stock['stock_type'] ?? '-';
                    $rows[$key]['rate'] = $stock['rate'] ?? '-';
                    $rows[$key]['open_time'] = $stock['open_time'] ?? '-';
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows, 'extend' => [
                'tape_list' => $tapeList,
                'stock_type_list' => $stockTypeList,
                'status_list' => $statusList
            ]]);

        } catch
        (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 申购订单 - 修改中签数
    public function updateGetNum($marketType, $param)
    {
        try {
            if (empty($param['id']) || !is_numeric($param['id'])) {
                return $this->toData('1', 'id参数错误');
            }

            if (!is_numeric($param['get_num'])) {
                return $this->toData('1', 'get_num参数错误');
            }

            $tableObj = (new IPOService)->getStockModel($marketType);
            $order = Db::table($tableObj['order_table'])->where('id', $param['id'])->find();
            if (empty($order)) return $this->toData('1', 'id参数错误');

            if (in_array($order['status'], [7, 8])) return $this->toData('1', '订单已退款,不可操作');

            if ($param['get_num'] > $order['num']) {
                return $this->toData('1', '修改中签数不能大于订单申购数');
            }

            $getTime = Db::table($tableObj['stock_table'])->where('id', $order['pre_stock_id'])->value('get_time');
            if (env('USER_ARREARS.HAS_USER_ARREARS') == 1 && $order['pay_type'] == 2 && in_array($order['status'], [5, 6])) {
            } else {
                if (strtotime($getTime) < time()) return $this->toData('1', 'IPO已中签,无法修改');
            }

            $bool = Db::table($tableObj['order_table'])->where('id', $param['id'])->update([
                'get_num' => $param['get_num'],
                'get_amount' => $param['get_num'] * $order['price'],
                'get_fee' => $order['get_amount'] * $order['fee_rate'],
                'update_time' => date('Y-m-d H:i:s')
            ]);
            if (!$bool) return $this->toData('1', '修改失败');

            return $this->toData('0', 'SUCCESS', []);
        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 申购订单退款
    public function preRefund($marketType, $param)
    {
        try {
            if (empty($param['id']) || !is_numeric($param['id'])) {
                return $this->toData('1', 'id参数错误');
            }
            $tableObj = (new IPOService)->getStockModel($marketType);

            $order = Db::table($tableObj['order_table'])->where('id', $param['id'])->whereIn('status',[1,2,5,6])->find();
            if (empty($order)) return $this->toData('1', 'id参数错误');


            $preStock = Db::table($tableObj['stock_table'])->where('id', $param['id'])->where('is_delete', 1)
                ->where('status', 1)
                ->where('id', $param['pre_id'])
                // 签名状态
                ->where('sign_status', 1)
                ->where('open_status', 1) ->find();
            if(empty($preStock)){
                return $this->toData('1', 'IPO未签名或已上市不可退款');
            }

            $now = date('Y-m-d H:i:s');
            $total_num=$order['amount']+$order['fee'];
            //查询订单有没有欠款
            $user_arrears=UserArrearsModel::where('order_no', $order['order_no'])->where('status',0)->where('user_id', $order['user_id'])->find();

            Db::startTrans();
            if($user_arrears){
                $user_arrears=$user_arrears->toArray();
                if($user_arrears['is_add']==1){
                    //扣除冻结,不加可用
                    $updateNum = Db::table($tableObj['user_table'])->where('stock_id', $tableObj['stock_id'])->where('user_id', $order['user_id'])
                        ->where('frozen_num', '>=', $total_num)
                        ->dec('frozen_num',$total_num)
                        ->update(['update_time' => $now]);
                    if(!$updateNum){
                        Db::rollback();
                        trace('IPO订单退款01-给用户ID:' . $order['user_id'] . "解冻资金异常" . $order['order_no'], 'error');
                        return $this->toData('1', '解冻资金异常');
                    }
                }
                $update_bool=UserArrearsModel::where('order_no', $order['order_no'])->where('user_id', $order['user_id'])
                    ->update([
                        'update_time'=>$now,
                        'status'=>1
                    ]);
                if(!$update_bool){
                    Db::rollback();
                    trace('IPO订单退款02-给用户ID:' . $order['user_id'] . "更新贷款订单异常" . $order['order_no'], 'error');
                    return $this->toData('1', '更新贷款订单异常');
                }

                $status=8;
            }else{
                //扣除冻结  加可用
                $updateNum = Db::table($tableObj['user_table'])->where('stock_id', $tableObj['stock_id'])->where('user_id', $order['user_id'])
                    ->where('frozen_num', '>=', $total_num)
                    ->inc('usable_num', $total_num)
                    ->dec('frozen_num',$total_num)
                    ->update(['update_time' => $now]);
                if(!$updateNum){
                    Db::rollback();
                    trace('IPO订单退款03-给用户ID:' . $order['user_id'] . "解冻资金异常" . $order['order_no'], 'error');
                    return $this->toData('1', '解冻资金异常');
                }
                $status=7;
            }

            //更新状态
            $bool_status = Db::table($tableObj['order_table'])->where('id', $order['id'])->update([
                'status' => $status,
                'update_time' => $now
            ]);
            if (!$bool_status) {
                Db::rollback();
                trace('IPO订单退款04-更新订单状态异常' . $order['order_no'], 'error');
                return $this->toData('1', '更新订单状态异常');
            }
            //删除缓存订单
            $redis = $this->getRedis();
            $key = "USER:ARREAR:ORDER:" . $order['order_no'];
            $redis->del($key);
            Db::commit();

            return $this->toData('0', 'SUCCESS', []);
        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }


    ################################################# 基金订单
    //基金订单
    public function fundStock($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('fund_stock')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_no'])) $where[] = ['order_no', '=', $param['order_no']];

            // 状态
            if (!empty($param['open_status']) && in_array($param['open_status'], array_keys(PreFundStockModel::$stockTypeList))) $where[] = ['status', '=', $param['status']];

            if (!empty($param['stock_code'])) {
                $stockId = PreFundStockModel::where('stock_code', $param['stock_code'])->value('id');
                $stockId = $stockId ?? 0;
                $where[] = ['pre_stock_id', '=', $stockId];
            }

            $list = UserFundPreStockOrderModel::where($whereU)->where($where)->order('id', 'desc')->page($param['page'], $param['limit'])->select();
            $total = UserFundPreStockOrderModel::where($whereU)->where($where)->count();

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                // stock
                $preStockId = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                    $preStockId[] = $idItem['pre_stock_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                $stockArr = PreFundStockModel::where('id', 'in', $preStockId)->column('*', 'id');

                $rows = $list->toArray();
                foreach ($rows as $key => $item) {
                    $stock = $stockArr[$item['pre_stock_id']] ?? [];
                    if (empty($stock)) continue;
                    $rows[$key]['user_no'] = $userNoArr[$item['user_id']] ?? '-'; // 用户号
                    $rows[$key]['stock_code'] = $stock['stock_code'] ?? '-';
                    $rows[$key]['stock_name'] = $stock['stock_name'] ?? '-';
                    $rows[$key]['stock_type'] = PreFundStockModel::$stockTypeList[$stock['stock_type']] ?? '-';
                    $rows[$key]['rate'] = $item['stock_rate'] . "%" ?? '-';
                    $rows[$key]['cycle'] = $item['stock_cycle'] . PreFundStockModel::$cycleTypeList[$item['stock_cycle_type']] ?? '-';
                    $rows[$key]['open_time'] = $stock['open_time'] ?? '-';
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows, 'extend' => [
                'tape_list' => [],
                'stock_type_list' => PreFundStockModel::$stockTypeList,
                'cycle_type_list' => PreFundStockModel::$cycleTypeList
            ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    //基金订单info
    public function fundStockInfo($param)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('fund_stock_info')->check($param);
            $list = UserStockFundInterestReceiptModel::where('order_id', $param['id'])->append(['status_text'])->select();
            return $this->toData('0', 'SUCCESS', ['list' => $list]);
        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    //基金返息单列表
    public function fundInterestList($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('fund_interest_list')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 状态
            if (!empty($param['status']) && in_array($param['status'], ['1', '2'])) $where[] = ['status', '=', $param['status']];

            if (!empty($param['stock_code'])) {
                $stockId = PreFundStockModel::where('stock_code', $param['stock_code'])->value('id');
                $stockId = $stockId ?? 0;
                $where[] = ['pre_stock_id', '=', $stockId];
            }

            $list = UserStockFundInterestReceiptModel::where($whereU)->where($where)->append(['status_text'])->order('status', 'asc')->order('return_date', 'asc')->page($param['page'], $param['limit'])->select();
            $total = UserStockFundInterestReceiptModel::where($whereU)->where($where)->count();

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                // stock
                $preStockId = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                    $orderIdArr[] = $idItem['order_id'];
                    $preStockId[] = $idItem['pre_stock_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                $orderArr = UserFundPreStockOrderModel::where('id', 'in', $orderIdArr)->column('*', 'id');
                $stockArr = PreFundStockModel::where('id', 'in', $preStockId)->column('*', 'id');

                $rows = $list->toArray();
                foreach ($rows as $key => $item) {
                    $order = $orderArr[$item['order_id']] ?? [];
                    $stock = $stockArr[$item['pre_stock_id']] ?? [];
                    if (empty($stock) || empty($order)) continue;
                    $rows[$key]['user_no'] = $userNoArr[$item['user_id']] ?? '-'; // 用户号
                    $rows[$key]['stock_code'] = $stock['stock_code'] ?? '-';
                    $rows[$key]['stock_name'] = $stock['stock_name'] ?? '-';
                    $rows[$key]['stock_type'] = PreFundStockModel::$stockTypeList[$order['interest_type']] ?? '-';
                    $rows[$key]['order_no'] = $order['order_no'] ?? '-';
                    $rows[$key]['rate'] = $order['stock_rate'] . "%" ?? '-';
                    $rows[$key]['cycle'] = $order['stock_cycle'] . PreFundStockModel::$cycleTypeList[$order['stock_cycle_type']] ?? '-';
                    $rows[$key]['open_time'] = $stock['open_time'] ?? '-';
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows, 'extend' => [
                'tape_list' => [],
                'stock_type_list' => PreFundStockModel::$stockTypeList,
                'cycle_type_list' => PreFundStockModel::$cycleTypeList
            ]]);
        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }



    ########################################## 印度期权交易  ###########################################
    // 印度期权持仓
    public function inOptionHold($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('hk_stockHold')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['stock_id'])) {
                $where['stock_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['open_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = StockOptionInrTradeModel::where('status', StockOptionInrTradeModel::STATUS_HOLD)->where($whereU)->where($where)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = StockOptionInrTradeModel::where('status', StockOptionInrTradeModel::STATUS_HOLD)
                ->where($where)->where($whereU)
                ->count();
            // 持仓总金额
            $totalModel = StockOptionInrTradeModel::where('status', StockOptionInrTradeModel::STATUS_HOLD)
                ->field('SUM(order_money) as total')->where($whereU)
                ->where($where)->find();

            // 持仓总手续费
            $totalServiceCost = StockOptionInrTradeModel::where('status', StockOptionInrTradeModel::STATUS_HOLD)
                ->where($whereU)
                ->where($where)
                ->sum('service_cost');

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    $orderNumber = number_format($item['order_number'], '18', '.', '');
                    $orderPrice = number_format($item['deal_price'], '18', '.', '');
                    $orderAmount = bcmul($orderNumber, $orderPrice, 18);
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'order_id' => $item['order_id'], // 用户号
                        'open_time' => $item['open_time'] ?? '-', // 挂单时间
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'order_money' => $orderAmount, // 订单金额
                        'stock_id' => $item['stock_id'], // 股票代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'float' => '-', // 浮动盈亏
                        'deal_price' => $item['deal_price'], // 开仓价
                        'now_price' => '-', // 当前价
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4), 'totalServiceCost' => $totalServiceCost,
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 印度期权挂单
    public function inOptionPlace($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('hk_stockPlace')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['stock_id'])) {
                $where['stock_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['create_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = StockOptionInrTradeModel::where('status', StockOptionInrTradeModel::STATUS_PLACE)->where($whereU)->where($where)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = StockOptionInrTradeModel::where('status', StockOptionInrTradeModel::STATUS_PLACE)
                ->where($where)->where($whereU)
                ->count();
            // 持仓总金额
            $totalModel = StockOptionInrTradeModel::where('status', StockOptionInrTradeModel::STATUS_PLACE)
                ->field('SUM(order_money) as total')->where($whereU)
                ->where($where)->find();

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    // 挂单价
                    $price = $item['limit_price'];
                    if ($item['deal_type'] == 2) {
                        $price = $item['market_price'];
                    }

                    $orderNumber = number_format($item['order_number'], '18', '.', '');
                    $orderPrice = number_format($price, '18', '.', '');
                    $orderAmount = bcmul($orderNumber, $orderPrice, 18);
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'order_id' => $item['order_id'], // 订单号
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'create_time' => $item['create_time'], // 挂单时间
                        'order_money' => $orderAmount, // 订单金额
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'stock_id' => $item['stock_id'], // 合约代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'deal_price' => $price, // 委托价
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'limit_price' => $item['limit_price'], // 限价
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4),
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 印度期权撤单
    public function inOptionBack($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('hk_stockBack')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['stock_id'])) {
                $where['stock_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['update_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = StockOptionInrTradeModel::where('status', StockOptionInrTradeModel::STATUS_BACK)->where($whereU)->where($where)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = StockOptionInrTradeModel::where('status', StockOptionInrTradeModel::STATUS_BACK)
                ->where($where)->where($whereU)
                ->count();
            // 持仓总金额
            $totalModel = StockOptionInrTradeModel::where('status', StockOptionInrTradeModel::STATUS_BACK)
                ->field('SUM(order_money) as total')->where($whereU)
                ->where($where)->find();


            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    // 挂单价
                    $price = $item['limit_price'];
                    if ($item['deal_type'] == 2) {
                        $price = $item['market_price'];
                    }

                    $orderNumber = number_format($item['order_number'], '18', '.', '');
                    $orderPrice = number_format($price, '18', '.', '');
                    $orderAmount = bcmul($orderNumber, $orderPrice, 18);
                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'order_id' => $item['order_id'], // 用户号
                        'create_time' => $item['create_time'], // 挂单时间
                        'update_time' => $item['update_time'], // 挂单时间
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'order_money' => $orderAmount, // 订单金额
                        'stock_id' => $item['stock_id'], // 合约代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'deal_price' => $price, // 委托价
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => ['totalMoney' => round($totalModel['total'], 4),
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    // 印度期权平仓
    public function inOptionClear($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('hk_stockClear')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            // 订单号
            if (!empty($param['order_id'])) {
                $where['order_id'] = $param['order_id'];
            }

            // 交易对
            if (!empty($param['contract_id'])) {
                $where['contract_id'] = $param['contract_id'];
            }

            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where['open_time'] = ['between time', [$param['start_time'], $param['end_time']]];
            }

            // 列表
            $list = StockOptionInrTradeModel::where('status', StockOptionInrTradeModel::STATUS_CLEAR)->where($whereU)->where($where)->order('trade_id', 'desc')->page($param['page'], $param['limit'])->select();
            // 总数
            $total = StockOptionInrTradeModel::where('status', StockOptionInrTradeModel::STATUS_CLEAR)
                ->where($where)->where($whereU)
                ->count();

            // 持仓总手续费
            $totalClosingCost = StockOptionInrTradeModel::where('status', StockOptionInrTradeModel::STATUS_CLEAR)
                ->where($whereU)
                ->where($where)
                ->sum('closing_cost');

            $totalFloat = StockOptionInrTradeModel::where('status', StockOptionInrTradeModel::STATUS_CLEAR)
                ->where($whereU)
                ->where($where)
                ->field("SUM( CASE WHEN trade_type = 1 THEN ( closing_price - deal_price )* order_number ELSE ( deal_price - closing_price )* order_number END ) AS total")->find();


            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
                foreach ($list as $item) {
                    // 计算浮动盈亏
                    if ($item['trade_type'] == 1) {
                        $float = $item['closing_price'] - $item['deal_price'];
                    } else {
                        $float = $item['deal_price'] - $item['closing_price'];
                    }
                    $float = bcmul($float, $item['order_number'], 18);

                    $orderNumber = number_format($item['order_number'], '18', '.', '');
                    $orderPrice = number_format($item['deal_price'], '18', '.', '');
                    $orderAmount = bcmul($orderNumber, $orderPrice, 18);

                    $rows[] = [
                        'trade_id' => $item['trade_id'], //
                        'user_no' => $userNoArr[$item['user_id']] ?? '-', // 用户号
                        'order_id' => $item['order_id'], // 用户号
                        'closing_time' => $item['closing_time'], // 平仓时间
                        'trade_type' => $item['trade_type'] == 1 ? '买涨' : '买跌',
                        'order_money' => $orderAmount, // 订单金额
                        'stock_id' => $item['stock_id'], // 股票代码
                        'order_number' => $item['order_number'], // 数量
                        'service_cost' => $item['service_cost'], // 服务费
                        'closing_cost' => $item['closing_cost'], // 平仓服务费
                        'deal_price' => $item['deal_price'], // 开仓价
                        'closing_price' => $item['closing_price'], // 平仓价格
                        'stop_loss_price' => $item['stop_loss_price'], // 止损价
                        'stop_win_price' => $item['stop_win_price'], // 止盈价
                        'float' => $float, // 平仓盈亏
                        'pry_num' => $item['pry_num'], // 杠杆
                    ];
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows,
                'extent' => [
                    'totalClosingCost' => $totalClosingCost,
                    'totalFloat' => $totalFloat['total'],
                ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }

    ################################################# 大宗交易
    //大宗交易订单
    public function blockStock($param, $adminId)
    {
        try {
            // 参数校验
            validate(OrderValidate::class)->scene('fund_stock')->check($param);

            $where = [];
            $userId = 0;
            // 用户号精确搜索
            if (!empty($param['user_no'])) {
                $user = UserModel::where('user_no', $param['user_no'])->find();
                if (empty($user)) {
                    return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
                }
                $userId = $user['user_id'];
            }

            // 判断是否是代理 如果是代理 只能看他自己管理的用户
            $whereU = $this->getWhereByIsAgentAndUserId($adminId, $where, $userId);
            if (!is_array($whereU)) {
                return $this->toData('0', 'SUCCESS', ['total' => 0, 'list' => [], 'extent' => ['totalMoney' => 0]]);
            }

            if (!empty($param['type']) && is_numeric($param['type'])) {
                $where['type'] = $param['type'];
            }

            $list = UserStockBlockOrderModel::where($whereU)->where($where)->order('id', 'desc')->page($param['page'], $param['limit'])->select();
            $total = UserStockBlockOrderModel::where($whereU)->where($where)->count();

            $rows = [];
            if (!$list->isEmpty()) {
                // 获取用户号
                $userIdArr = [];
                // stock
                $preStockId = [];
                foreach ($list as $idItem) {
                    $userIdArr[] = $idItem['user_id'];
//                    $preStockId[] = $idItem['pre_stock_id'];
                }

                $userNoArr = UserModel::where('user_id', 'in', $userIdArr)->column('user_no', 'user_id');
//                $stockArr = PreFundStockModel::where('id', 'in', $preStockId)->column('*', 'id');

                $rows = $list->toArray();
                foreach ($rows as $key => $item) {
//                    $stock = $stockArr[$item['pre_stock_id']] ?? [];
//                    if (empty($stock)) continue;
                    $rows[$key]['user_no'] = $userNoArr[$item['user_id']] ?? '-'; // 用户号
                    $rows[$key]['stock_name'] = $item['stock_name'] ?? '-';
                    $rows[$key]['market_price'] = $item['market_price'] ?? '-';
                    $rows[$key]['deal_price'] = $item['deal_price'] ?? '-';
                    $rows[$key]['order_number'] = $item['order_number'] ?? '-';
                    $rows[$key]['market_money'] = $item['market_money'] ?? '-';
                    $rows[$key]['order_money'] = $item['order_money'] ?? '-';
                    $rows[$key]['status'] = UserStockBlockOrderModel::$statusList[$item['status']];
                    $rows[$key]['type'] = UserStockBlockOrderModel::$typeList[$item['type']];
                    $rows[$key]['create_time'] = $item['create_time'] ?? '-';
                }
            }

            return $this->toData('0', 'SUCCESS', ['total' => $total, 'list' => $rows, 'extend' => [
                'status_list' => UserStockBlockOrderModel::$statusList,
                'type_list' => UserStockBlockOrderModel::$typeList
            ]]);

        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统异常 请稍后重试', [$exception->getMessage(), $exception->getTrace()]);
        }
    }
}