<?php
namespace common\lib;

use backend\helpers\MailHelper;
use backend\models\Mt4DepositLog;
use common\lib\Mt4ManagerApi;

/**
 * Class Mt4Deposit
 * @package common\helps
 */
class Mt4Deposit
{
    const TYPE_DEPOSIT = 1; // 入金
    const TYPE_WITHDRAW = 2; // 出金

    /**
     * soap服务url
     * @var string
     */
    public $url = 'http://43.239.176.170:10001/';
    /**
     * @var array
     */
    public $options = [
        'cache_wsdl' => WSDL_CACHE_NONE,
    ];
    /**
     * @var array
     */
    public $emails = [];
    /**
     * 错误码
     * @var array
     */
    public $errorCodes = [
        0 => 'RET_OK|正确',
        1 => 'RET_OK_NONE|正确，但是不做操作',
        2 => 'RET_ERROR|一般性错误',
        3 => 'RET_INVALID_DATA|无效数据',
        4 => 'RET_TECH_PROBLEM|服务器技术问题',
        5 => 'RET_OLD_VERSION|客户端版本过低',
        6 => 'RET_NO_CONNECT|无连接',
        7 => 'RET_NOT_ENOUGH_RIGHTS|权限不足',
        8 => 'RET_TOO_FREQUENT|请求太频繁',
        9 => 'RET_MALFUNCTION|交易操作故障',
        64 => 'RET_ACCOUNT_DISABLED|被禁用账号',
        65 => 'RET_BAD_ACCOUNT_INFO|无效账户',
        -1 => 'MT4ManWSEC_COMM|一般性错误',
        -2 => 'MT4ManWSEC_CONN|连接和登录 MT4 服务器错误',
        -3 => 'MT4ManWSEC_UNKN|未知错误',
        -17 => 'MT4ManWSEC_FREEAPI|API 释放错误',
        -18 => 'MT4ManWSEC_APIERR|API 错误',
        -33 => 'MT4ManWSEC_INVLDPRM|输入参数不允许',
        // 自定义错误信息
        1000 => '参数非法',
        1100 => '入金失败',
        1101 => '入金异常',
        1200 => '查询失败',
        1201 => '查询异常',
        1300 => '出金失败',
        1301 => '出金异常',
    ];

    /**
     * 入金
     * @param int $mt4Id mt4id
     * @param float $usdMoney 美元
     * @param string $comment 注释
     * @return array
     */
    public function deposit($mt4Id, $usdMoney, $comment = null)
    {
        if (empty($mt4Id) || empty($usdMoney)) {
            // 参数非法
            return $this->retResult(1000, $this->errorCodes[1000], func_get_args());
        }
		/*
        $params = [
            'login' => $mt4Id,
            'money' => $usdMoney,
        ];
        if ($comment) {
            $params['comment'] = $comment;
        } 
        $client = new \SoapClient($this->url, $this->options);
        $result = $client->deposit($params);
		*/
		$comment = ($comment) ? $comment : 'Deposit';
		$api = new Mt4ManagerApi();
        $result = $api->balance('deposit', $mt4Id, $usdMoney, $comment);
		$result = json_decode($result, true);	
        if ($result) {
            $errMsg = isset($this->errorCodes[$result['ret']]) ? trim($this->errorCodes[$result['ret']]) : '未知错误';
            if ($result['ret'] == 0) {
                // 入金成功
                $this->log(self::TYPE_DEPOSIT, $mt4Id, $usdMoney, $comment, $result['ret'], $errMsg, $result['order']);
                return $this->retResult(0, $errMsg, $result);
            } else {
                // 入金失败
                $this->log(self::TYPE_DEPOSIT, $mt4Id, $usdMoney, $comment, $result['ret'], $errMsg);
                $this->sendMail('入金失败报警', [
                    'mt4Id' => $mt4Id,
                    'usdMoney' => $usdMoney,
                    'comment' => $comment,
                    'errCode' => $result['ret'],
                    'errMsg' => $errMsg,
                ]);
                return $this->retResult(1100, $errMsg, $result);
            }
        } else {
            // 入金异常
            $this->log(self::TYPE_DEPOSIT, $mt4Id, $usdMoney, $comment, 1101, $this->errorCodes[1101]);
            $this->sendMail('入金异常报警', [
                'mt4Id' => $mt4Id,
                'usdMoney' => $usdMoney,
                'orderNo' => $comment,
                'errCode' => 1101,
                'errMsg' => $this->errorCodes[1101],
            ]);
            return $this->retResult(1101, $this->errorCodes[1101], $result);
        }
    }

    /**
     * 入金
     * @param int $mt4Id mt4id
     * @param float $cnyMoney 人民币(元)
     * @param float $usdRate 美元汇率
     * @param int $orderNo 订单号
     * @return array
     */
    public function depositByCNY($mt4Id, $cnyMoney, $usdRate, $orderNo = null)
    {
        if (empty($mt4Id) || empty($cnyMoney) || empty($usdRate)) {
            // 参数非法
            return $this->retResult(1000, $this->errorCodes[1000], func_get_args());
        }
        $usdMoney = $cnyMoney / $usdRate;
        return $this->deposit($mt4Id, $usdMoney, $orderNo);
    }

    /**
     * 获取账户余额
     * @param int $mt4Id mt4id
     * @return array
     */
    public function getbalance($mt4Id)
    {
        if (empty($mt4Id)) {
            // 参数非法
            return $this->retResult(1000, $this->errorCodes[1000], func_get_args());
        }
        $params = [
            'login' => $mt4Id,
        ];
        $client = new \SoapClient($this->url, $this->options);
        $result = $client->getbalance($params);
        if ($result) {
            if ($result->result == 0) {
                // 查询成功
                return $this->retResult(0, $this->errorCodes[$result->result], $result);
            } else {
                // 查询失败
                return $this->retResult(1200, $this->errorCodes[$result->result], $result);
            }
        } else {
            // 查询异常
            return $this->retResult(1201, $this->errorCodes[1201], $result);
        }
    }

    /**
     * 出金
     * @param int $mt4Id mt4id
     * @param float $usdMoney 美元
     * @param string $comment 注释
     * @return array
     */
    public function withdraw($mt4Id, $usdMoney, $comment = null)
    {
        if (empty($mt4Id) || empty($usdMoney)) {
            // 参数非法
            return $this->retResult(1000, $this->errorCodes[1000], func_get_args());
        }
		/*
        $params = [
            'login' => $mt4Id,
            'money' => $usdMoney,
        ];
        if ($comment) {
            $params['comment'] = $comment;
        }
		
        $client = new \SoapClient($this->url, $this->options);
        $result = $client->withdraw($params);
		*/
		
		$comment = ($comment) ? $comment : 'Withdraw';
		$api = new Mt4ManagerApi();
        $result = $api->balance('withdraw', $mt4Id, $usdMoney, $comment);
		$result = json_decode($result, true);	
        if ($result) {
            $errMsg = isset($this->errorCodes[$result['ret']]) ? trim($this->errorCodes[$result['ret']]) : '未知错误';
            if ($result['ret'] == 0) {
                // 出金成功
                $this->log(self::TYPE_WITHDRAW, $mt4Id, $usdMoney, $comment, $result['ret'], $errMsg, $result['order']);
                return $this->retResult(0, $errMsg, $result);
            } else {
                // 出金失败
                $this->log(self::TYPE_WITHDRAW, $mt4Id, $usdMoney, $comment, $result['ret'], $errMsg);
                $this->sendMail('出金失败报警', [
                    'mt4Id' => $mt4Id,
                    'usdMoney' => $usdMoney,
                    'comment' => $comment,
                    'errCode' => $result['ret'],
                    'errMsg' => $errMsg,
                ]);
                return $this->retResult(1300, $errMsg, $result);
            }
        } else {
            // 出金异常
            $this->log(self::TYPE_WITHDRAW, $mt4Id, $usdMoney, $comment, 1301, $this->errorCodes[1301]);
            $this->sendMail('出金异常报警', [
                'mt4Id' => $mt4Id,
                'usdMoney' => $usdMoney,
                'orderNo' => $comment,
                'errCode' => 1301,
                'errMsg' => $this->errorCodes[1301],
            ]);
            return $this->retResult(1301, $this->errorCodes[1301], $result);
        }
    }

    /**
     * 出金
     * @param int $mt4Id mt4id
     * @param float $cnyMoney 人民币
     * @param float $usdRate 美元汇率
     * @param null|int $orderNo 订单号
     * @return array
     */
    public function withdrawByCNY($mt4Id, $cnyMoney, $usdRate, $orderNo = null)
    {
        if (empty($mt4Id) || empty($cnyMoney) || empty($usdRate)) {
            // 参数非法
            return $this->retResult(1000, $this->errorCodes[1000], func_get_args());
        }
        $usdMoney = $cnyMoney / $usdRate;
        return $this->withdraw($mt4Id, $usdMoney, $orderNo);
    }

    /**
     * 返回结果
     * @param int $errCode 错误码
     * @param string $errMsg 错误信息
     * @param array $data 返回数据
     * @return array
     */
    public function retResult($errCode, $errMsg = '', $data = [])
    {
        return ['errCode' => $errCode, 'errMsg' => $errMsg, 'data' => (array)$data];
    }

    /**
     * 记录日志
     * @param int $type
     * @param int $mt4Id
     * @param float $usdMoney
     * @param string $orderId
     * @param string $errCode
     * @param string $errMsg 
     * @param string $mt4Order
     * @return bool
     */
    private function log($type, $mt4Id, $usdMoney, $orderId, $errCode, $errMsg, $mt4Order = '')
    {
        $data = [
            'type' => intval($type),
            'mt4_id' => trim($mt4Id),
            'order_id' => trim($orderId),
            'mt4_order_id' => trim($mt4Order),
            'usd_money' => trim($usdMoney),
            'err_code' => trim($errCode),
            'err_msg' => trim($errMsg),
            'create_time' => time(),
        ];
        $model = new Mt4DepositLog();
        $model->setAttributes($data);
        return $model->save();
    }

    /**
     * 发送邮件
     * @param string $subject
     * @param string|array $body
     */
    private function sendMail($subject, $body)
    {
        $html = '';
        if (is_array($body)) {
            $html .= '<table>';
            foreach ($body as $key => $value) {
                $html .= "<tr><td>{$key} : </td><td>{$value}</td></tr>";
            }
            $html .= '</table>';
        } else {
            $html = trim($body);
        }
        MailHelper::sendMail($subject, $this->emails, [], 'do.not.reply', $html);
    }
}
