<?php

namespace app\home\service;


use app\model\StockBlockListModel;
use app\model\UserStockBlockOrderModel;

class BlockStockService extends BaseHomeService
{

    // 列表
    public function index($param)
    {
        try {
            if (empty($param['page']) || !is_numeric($param['page']) || empty($param['limit']) || !is_numeric($param['limit'])) {
                $param['page'] = 1;
                $param['limit'] = 10;
            }

            // stock_type 3 美股 4 印尼 5 马股 6 泰股 9 新加坡股票
            if (empty($param['type']) || !in_array($param['type'], ['3', '4', '5', '6', '7', '9', '12','14','15','16','17','18'])) {
                return $this->toData('1', 'Params error');
            }

            $list = StockBlockListModel::where('type', $param['type'])->page($param['page'], $param['limit'])->select();
            $total = StockBlockListModel::where('type', $param['type'])->count();

            $redisKeyArr = [3 => 'US', 4 => 'Indonesia', 5 => 'Malaysia', 6 => 'Thailand', 7 => 'India', 9 => 'Singapore', 12 => 'HongKong',14=>'UK',15=>'France',16=>'Germany',17=>'Brazil',18=>'Japan'];
            $redis = $this->getRedis();

            foreach ($list as $key=>&$v) {
                unset($list[$key]['buy_pwd']);
                $key = "Stock:" . $redisKeyArr[$v->type];
                $v->current_price = $redis->hget($key . ":ClosePrice", $v->stock_code) ?? $redis->hget($key . ":CloseNewPrice", $v->stock_code);
            }
            return $this->toData('0', 'SUCCESS', ['list' => $list, 'total' => $total,]);
        } catch (\Exception $exception) {
            return $this->toData('0', 'The system is busy. Please try again later.', [$exception->getMessage()]);
        }
    }

    // 订单列表
    public function list($param, $userId)
    {
        try {

            if (empty($param['page']) || !is_numeric($param['page']) || empty($param['limit']) || !is_numeric($param['limit'])) {
                $param['page'] = 1;
                $param['limit'] = 10;
            }

            $where[] = ['user_id', '=', $userId];
            // stock_type 3 美股 4 印尼 5 马股 6 泰股 9 新加坡股票
            if (!empty($param['type']) && ($param['type'] >2 && $param['type']< 19)) {
                $where[] = [
                    'type', '=', $param['type']
                ];
            }

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

            return $this->toData('0', 'SUCCESS', ['list' => $list, 'total' => $total,]);
        } catch (\Exception $exception) {
            return $this->toData('0', 'The system is busy. Please try again later.', [$exception->getMessage()]);
        }
    }


}