<?php

namespace api\third\controller;

use cmf\controller\RestBaseController;
use think\Db;
use think\Validate;

class AccountController extends RestBaseController
{
    public function _initialize()
    {
        //因为操作时间会很长，设置php操作超时时间600秒
        set_time_limit(600);
        date_default_timezone_set("Etc/GMT");
    }

    public function validateAccount($exchange_class, $apiKey, $secret, $password)
    {


        $vendor_name = "ccxt.ccxt";
        Vendor($vendor_name);

        $className = "\ccxt\\" . $exchange_class;

        $exchange  = new $className(array(
            'apiKey' => $apiKey,
            'secret' => $secret,
            'password' => $password,
        ));

        //$this->market
        try {
            $result = $exchange->fetch_balance();
        } catch (\Exception $e) {
            //$this->error($e->getMessage());
            return array(0, $e->getMessage());
        }
        return array(1, $result);
    }

    /*
     * 绑定api
     */
    public function addAccount()
    {

        $userId = $this->getUserId();
        $platforms = implode(',', Db::name("third_platform")->column('platform'));
        $validate = new Validate([
            'platform'     => 'require|in:' . $platforms,
            'api_key'     => 'require',
            'secret_key' => 'require',
            'passphrase' => 'require',
        ]);

        $validate->message([
            'platform.require'  => '平台不能为空!',
            'api_key.require'  => 'API Key不能为空!',
            'secret_key.require'  => 'Secret Key不能为空',
            'passphrase.require'  => 'Passphrase不能为空!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $platform = $data['platform'];
        $apiKey = $data['api_key'];
        $secretKey = $data['secret_key'];
        $passphrase = $data['passphrase'];
        $platforms = Db::name("third_platform")->select()->toArray();
        $exchange_class = array_column($platforms, 'class', 'platform');
        //$exchange_class = array('okex' => 'okex3', 'binance' => 'binance', 'huobi' => 'hbdm', 'gateio' => 'gateio');
        if (!isset($exchange_class[$platform])) {
            $this->error('无法验证该平台API有效性:', $platform);
        }
        //测试api信息是否正确
        $ret = $this->validateAccount($exchange_class[$platform], $data['api_key'], $data['secret_key'], $data['passphrase']);
        if ($ret[0] != 1) {
            $this->error('API信息校验错误:' . $ret[1]);
        }

        $where = array();
        $where['platform'] = $platform;
        $where['uid'] = $userId;

        $findApi = Db::name("third_api")->where($where)->find();
        if ($findApi) {
            if ($findApi['status'] == 1) {
                $this->error("您已经添加过该平台API了:" . $platform);
            } else {
                //更新到数据库
                $api_info = [
                    'api_key' => $apiKey,
                    'secret_key' => $secretKey,
                    'passphrase' => $passphrase,
                    'update_time' => time(),
                    'status' => 1,
                ];
                $ret = Db::name("third_api")->where('id', $findApi['id'])->update($api_info);
            }
        } else {
            //添加到数据库
            $api_info = [
                'platform' => $platform,
                'uid' => $userId,
                'api_key' => $apiKey,
                'secret_key' => $secretKey,
                'passphrase' => $passphrase,
                'create_time' => time(),
                'update_time' => time(),
                'status' => 1,
            ];
            $ret = Db::name("third_api")->insert($api_info);
        }
        if ($ret) {
            $this->success('绑定API成功');
        } else {
            $this->error('绑定API失败');
        }
    }

    /*
     * 删除api
     */
    public function removeAccount()
    {

        $userId = $this->getUserId();
        $platforms = implode(',', Db::name("third_platform")->column('platform'));
        $validate = new Validate([
            'platform'     => 'require|in:' . $platforms,
        ]);

        $validate->message([
            'platform.require'  => '平台不能为空!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }

        $platform = $data['platform'];

        $where = array();
        $where['platform'] = $platform;
        $where['uid'] = $userId;
        $findApi = Db::name("third_api")->where($where)->find();
        if ($findApi) {
            $ret = Db::name("third_api")->where('id', $findApi['id'])->update(array('status' => 0));
            if ($ret) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('您没有设置该平台的API:' . $platform);
        }
    }



    public function accountInfo()
    {
        $userId = $this->getUserId();
        $platforms = implode(',', Db::name("third_platform")->column('platform'));
        $validate = new Validate([
            'platform'     => 'require|in:' . $platforms,
        ]);

        $validate->message([
            'platform.require'  => '平台不能为空!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $platform = $data['platform'];
        $where = array();
        $where['platform'] = $platform;
        $where['uid'] = $userId;
        $findApi = Db::name("third_api")->where($where)->find();
        if ($findApi) {
            if ($findApi['status'] == 0) { //已经删除
                $this->error('您还未添加该平台的API:' . $platform);
            } else {
                $this->success('success', $findApi);
            }
        } else {
            $this->error('您还未添加该平台的API:' . $platform);
        }
    }

    public function accountBalance()
    {
        $userId = $this->getUserId();
        $platforms = implode(',', Db::name("third_platform")->column('platform'));
        $validate = new Validate([
            'platform'     => 'require|in:' . $platforms,
        ]);

        $validate->message([
            'platform.require'  => '平台不能为空!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error($validate->getError());
        }
        $platform = $data['platform'];
        $where = array();
        $where['platform'] = $platform;
        $where['uid'] = $userId;
        $findApi = Db::name("third_api")->where($where)->find();
        if ($findApi) {
            if ($findApi['status'] == 0) { //已经删除
                $this->error('您还未添加该平台的API:' . $platform);
            } else {
                $platform = $findApi['platform'];
                $apiKey = $findApi['api_key'];
                $secretKey = $findApi['secret_key'];
                $passphrase = $findApi['passphrase'];
                $platforms = Db::name("third_platform")->select()->toArray();
                $exchange_class = array_column($platforms, 'class', 'platform');
                if (!isset($exchange_class[$platform])) {
                    $this->error('无法验证该平台API有效性:', $platform);
                }        
                //测试api信息是否正确
                $ret = $this->validateAccount($exchange_class[$platform], $apiKey, $secretKey, $passphrase);
                if ($ret[0] != 1) {
                    $this->error('API信息校验错误:' . $ret[1]);
                }
                $this->success('success', $ret[1]);
            }
        } else {
            $this->error('您还未添加该平台的API:' . $platform);
        }
    }
}
