<?php

namespace app\admin\service\setting;

use app\admin\service\AdminBaseService;
use app\admin\validate\setting\StockValidate;
use app\model\StockOptionInrListModel;
use think\exception\ValidateException;
use PHPMailer\PHPMailer\Exception;

// 印度期权
class OptionInService extends AdminBaseService
{

    public function index($param)
    {
        try {
            validate(StockValidate::class)->scene('in_option_index')->check($param);

            $stockCode = $param['stock_code'] ?? '';
            $where = [];
            if ($stockCode) {
                $where[] = ['stock_code', '=', $stockCode];
            }
            $list = StockOptionInrListModel::where($where)->page($param['page'], $param['limit'])->append(['tape_text', 'status_text'])->order('id', 'desc')->select();
            $total = StockOptionInrListModel::order('id', 'desc')->where($where)->count();
            $rows = [];
            if (!$list->isEmpty()) {
                $rows = $list->toArray();
            }
            return $this->toData('0', 'SUCCESS', ['list' => $rows, 'total' => $total, 'extend' => [
                'tape_list' => StockOptionInrListModel::$tapeListText,
                'status_list' => StockOptionInrListModel::$statusList
            ]]);
        } catch (ValidateException $validateException) {
            // 参数校验失败
            $message = $validateException->getError();
            return $this->toData('1', $message);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统繁忙', []);
        }
    }

    public function add($param)
    {
        try {
            validate(StockValidate::class)->scene('in_option_add')->check($param);
            $info = '';
            if (isset($param['info']) && is_string($param['info'])) {
                $info = $param['info'];
            }

            // 判断股票交易所
            $tape = '0';
            if (isset($param['tape']) && in_array($param['tape'], array_keys(StockOptionInrListModel::$tapeList))) {
                $tape = $param['tape'];
            }

            // 判断股票代码是否已经存在
            $count = StockOptionInrListModel::where('stock_code', $param['stock_code'])->count();
            if ($count > 0) {
                return $this->toData('1', '股票代码已经存在');
            }

            // 新增数据
            $stockList = new StockOptionInrListModel;
            $stockList->stock_name = $param['stock_name'];
            $stockList->stock_code = $param['stock_code'];
            $stockList->status = $param['status'];
            $stockList->rate = $param['rate'] ?? 0;
            $stockList->keep_decimal = $param['keep_decimal'] ?? 4;
            $stockList->forced_closure = $param['forced_closure'] ?? 30;
            $stockList->up_limit = $param['up_limit'] ?? 30;
            $stockList->down_limit = $param['down_limit'] ?? 30;
            $stockList->info = $info;
            $stockList->tape = $tape;
            $stockList->create_time = date('Y-m-d H:i:s');
            $stockList->update_time = date('Y-m-d H:i:s');
            $stockList->save();

            // 新增缓存
            $list_key = "IN:OPTION:LIST:" . $param['stock_code'];
            $redis = $this->getRedis();
            $redis->del($list_key);
            $redis->hMset($list_key, [
                'stock_name' => $param['stock_name'],
                'stock_code' => $param['stock_code'],
                'status' => $param['status'],
                'keep_decimal' => $param['keep_decimal'] ?? 4,
                'forced_closure' => $param['forced_closure'] ?? 30,
                'up_limit' => $param['up_limit'] ?? 30,
                'down_limit' => $param['down_limit'] ?? 30,
                'rate' => $param['rate'] ?? 0,
                'info' => $info,
                'tape' => $tape,
            ]);

            // 给行情推送
//            $bool = $this->sendDecimalToGo('Indonesia', $stockList->stock_code, $stockList->keep_decimal);
//            $bool = $this->sendNewStockToGo('India', $stockList->stock_code, $stockList->stock_name, StockOptionInrListModel::$tapeList[$tape]);

//            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', '系统繁忙', []);
        }
    }


    public function edit($param)
    {
        try {
            validate(StockValidate::class)->scene('in_option_edit')->check($param);

            $stockList = StockOptionInrListModel::where('id', $param['id'])->find();
            if (empty($stockList)) {
                return $this->toData('1', '目标不存在', []);
            }

            $info = '';
            if (isset($param['info']) && is_string($param['info'])) {
                $info = $param['info'];
            }

            // 判断股票交易所
            $tape = '0';
            if (isset($param['tape']) && in_array($param['tape'], array_keys(StockOptionInrListModel::$tapeList))) {
                $tape = $param['tape'];
            }

            // 判断股票代码是否已经存在
            $count = StockOptionInrListModel::where('stock_code', $param['stock_code'])->where('id', '<>', $param['id'])->count();
            if ($count > 0) {
                return $this->toData('1', '股票代码已经存在');
            }

            // 修改数据
            $stockList->stock_name = $param['stock_name'];
            $stockList->stock_code = $param['stock_code'];
            $stockList->status = $param['status'];
            $stockList->rate = $param['rate'] ?? 0;
            $stockList->keep_decimal = $param['keep_decimal'] ?? 4;
            $stockList->forced_closure = $param['forced_closure'] ?? 30;
            $stockList->up_limit = $param['up_limit'] ?? 30;
            $stockList->down_limit = $param['down_limit'] ?? 30;
            $stockList->info = $info;
            $stockList->tape = $tape;
            $stockList->update_time = date('Y-m-d H:i:s');
            $stockList->save();

            // 新增缓存
            $list_key = "IN:OPTION:LIST:" . $param['stock_code'];
            $redis = $this->getRedis();
            $redis->del($list_key);
            $redis->hMset($list_key, [
                'stock_name' => $param['stock_name'],
                'stock_code' => $param['stock_code'],
                'status' => $param['status'],
                'keep_decimal' => $param['keep_decimal'] ?? 4,
                'forced_closure' => $param['forced_closure'] ?? 30,
                'up_limit' => $param['up_limit'] ?? 30,
                'down_limit' => $param['down_limit'] ?? 30,
                'rate' => $param['rate'] ?? 0,
                'info' => $info,
                'tape' => $tape,
            ]);

            // 给行情推送
//            $bool = $this->sendNewStockToGo('India', $stockList->stock_code, $stockList->stock_name, StockOptionInrListModel::$tapeList[$tape]);
//
//            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', '系统繁忙', []);
        }
    }

    // 列表
    public function getTradeNameList()
    {
        try {
            $list = StockOptionInrListModel::where('status', 1)->order('id', 'desc')->column('stock_name', 'id');
            return $this->toData('0', 'SUCCESS', ['list' => $list]);
        } catch (\Exception $exception) {
            return $this->toData('1', '系统繁忙', []);
        }
    }

    public function refresh()
    {
        try {

            $ch = curl_init();

            $url = env('OPTION_REFRESH.OPTION_REFRESH_IN_URL');

            curl_setopt($ch, CURLOPT_URL, $url); // Set the URL
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the response as a string
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow any redirects
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // This should be set to true in production, disables SSL certificate verification (only for testing)

            $response = curl_exec($ch);
            if (curl_errno($ch)) {
                echo 'Curl error: ' . curl_error($ch);
            }

            curl_close($ch);

            $data = json_decode($response, true);
            if (empty($data) || empty($data['data']) || empty($data['code']) || (!empty($data['code']) && $data['code'] != 200)) {
                return;
            }

            $now = date('Y-m-d H:i:s'); // 订单时间
            $insertArr = [];
            $responseCodeArr = array_column($data['data'], 'Code');
            $dataCodeArr = StockOptionInrListModel::column('stock_code');
            $result = array_diff($responseCodeArr, $dataCodeArr);
            foreach ($data['data'] as $v) {
                if (in_array($v['Code'], $result)) {
                    $insertArr[] = [
                        'stock_name' => $v['Code'],
                        'stock_code' => $v['Code'],
                        'status' => 1,
                        'tape' => StockOptionInrListModel::$tapeList[$v['Exchange']] ?? 1,
                        'keep_decimal' => 4,
                        'create_time' => $now,
                        'update_time' => $now,
                        'rate' => 30,
                        'forced_closure' => 30,
                        'up_limit' => 30,
                        'down_limit' => 30
                    ];
                }
            }
            $StockOptionInrListModel = new StockOptionInrListModel();
            $StockOptionInrListModel::insertAll($insertArr);

            $redis = $this->getRedis();
            foreach ($insertArr as $cacheV) {
                $list_key = "IN:OPTION:LIST:" . $cacheV['stock_code'];
                $redis->del($list_key);
                $redis->hMset($list_key, [
                    'stock_name' => $cacheV['stock_name'],
                    'stock_code' => $cacheV['stock_code'],
                    'status' => $cacheV['status'],
                    'keep_decimal' => $cacheV['keep_decimal'],
                    'forced_closure' => $cacheV['forced_closure'],
                    'up_limit' => $cacheV['up_limit'],
                    'down_limit' => $cacheV['down_limit'],
                    'rate' => $cacheV['rate'],
                    'info' => '',
                    'tape' => $cacheV['tape'],
                ]);
            }


        } catch (\Exception $exception) {
        }
    }

    public function batchEdit($param)
    {
        try {
            $rate = $param['rate'];
            $keep_decimal = $param['keep_decimal'];
            $forced_closure = $param['forced_closure'];
            $status = $param['status'];
            $updateArr = ['rate' => $rate, 'keep_decimal' => $keep_decimal, 'forced_closure' => $forced_closure, 'status' => $status, 'update_time' => date('Y-m-d H:i:s')];
            StockOptionInrListModel::where(1, '=', 1)->update($updateArr);

            $dataCodeArr = StockOptionInrListModel::select()->toArray();
            $redis = $this->getRedis();
            foreach ($dataCodeArr as $cacheV) {
                $list_key = "IN:OPTION:LIST:" . $cacheV['stock_code'];
                $redis->del($list_key);
                $redis->hMset($list_key, [
                    'stock_name' => $cacheV['stock_name'],
                    'stock_code' => $cacheV['stock_code'],
                    'status' => $cacheV['status'],
                    'keep_decimal' => $cacheV['keep_decimal'],
                    'forced_closure' => $cacheV['forced_closure'],
                    'up_limit' => $cacheV['up_limit'],
                    'down_limit' => $cacheV['down_limit'],
                    'rate' => $cacheV['rate'],
                    'info' => $cacheV['info'],
                    'tape' => $cacheV['tape'],
                ]);
            }

            return $this->toData('0', 'SUCCESS');
        } catch (\Exception $exception) {
            return $this->toData('1', '系统繁忙', []);
        }
    }

    public function onOff($param)
    {
        try {
            $id = $param['id'];
            $stockList = StockOptionInrListModel::where('id', $param['id'])->find();
            if (empty($stockList)) {
                return $this->toData('1', '目标不存在', []);
            }
            $status = $stockList->status == 0 ? 1 : 0;
            $updateArr = ['status' => $status, 'update_time' => date('Y-m-d H:i:s')];
            StockOptionInrListModel::where('id', $id)->update($updateArr);
            return $this->toData('0', 'SUCCESS');
        } catch (\Exception $exception) {
            return $this->toData('1', '系统繁忙', []);
        }
    }
}