<?php

namespace common\pay\wangtong;

use backend\models\Config;
use backend\models\Deposit;
use backend\models\SyncDesposit;
use common\pay\BasePayHandler;
use Yii;
use yii\helpers\VarDumper;

class PayHandler extends BasePayHandler
{
    public $payUrl;
    public $merId;
    public $comkey;

    /**
     * @inheritdoc  
     */
    public function init()
    {
        parent::init();
        if ($this->payUrl == null) {
            $this->payUrl = Yii::$app->params['wangtong.payUrl'];
        }
        if ($this->merId == null) {
            $this->merId = Yii::$app->params['wangtong.merId'];
        }
        if ($this->comkey == null) {
            $this->comkey = Yii::$app->params['wangtong.comkey'];
        }
    }

    /**
     * @param array $deposit 
     * @param array $params
     * @return string
     */
    public function outPay($deposit, $params = [])
    {
        $data = [];
        $data['pay_memberid'] = $this->merId; // 商户号
        $data['pay_orderid'] = $deposit['order_sn']; // 订单号
        $data['pay_bankcode'] = '907'; // 服务类型
        $data['pay_amount'] = $deposit['rmb']; // 金额
        $data['pay_applydate'] = date("Y-m-d H:i:s");
        $data['pay_callbackurl'] = $this->returnUrl; // 支付完成返回地址
        $data['pay_notifyurl'] = $this->notifyUrl; // 回调地址
        $data['pay_attach'] = "123";
        $data['pay_productname'] = 'RJ' . $deposit['order_sn'];

        // 1. 加密所需参数
        $signData = [];
        foreach (['pay_memberid', 'pay_orderid', 'pay_amount', 'pay_applydate', 'pay_bankcode', 'pay_notifyurl', 'pay_callbackurl'] as $field) {
            $signData[$field] = isset($data[$field]) ? $data[$field] : null;
        }
        $data['pay_md5sign'] = PayUtils::createLinkString($signData, $this->comkey);
        Yii::warning('支付请求参数，' . VarDumper::dumpAsString($data), __METHOD__);
        $result = static::createHtml($data, $this->payUrl);
        Yii::warning('支付请求结果，' . VarDumper::dumpAsString($result), __METHOD__);
        return $result;
    }

    /**
     * @param array $data
     * @return bool
     */
    public function handleNotify($data)
    {
        Yii::warning('支付异步通知参数，' . VarDumper::dumpAsString($data), __METHOD__);
        if (isset($data['sign']) && trim($data['sign']) !== '') {
            // 1. 加密所需参数
            $signData = [];
            foreach (['memberid', 'orderid', 'amount', 'datetime', 'transaction_id', 'returncode'] as $field) {
                $signData[$field] = isset($data[$field]) ? $data[$field] : null;
            }
            // 2. 根据createLinkString方法进行参数排序处理
            $sign = PayUtils::createLinkString($signData, $this->comkey);
            if ($sign == $data['sign']) {
                if ($data['returncode'] == '00') {
                    $merOrderId = trim($data['orderid']);
                    $reuslt = Deposit::find()->where(['order_sn' => $merOrderId])->asArray()->limit(1)->one();
                    if ($reuslt['type'] != 1) {
                        $res = Deposit::updateAll(['type' => 1], "order_sn = $merOrderId");
                        $configData = Config::find()->asArray()->one();
                        if ($configData['auto_deposit'] == 1 && $res) {
                            $syncDespositModel = new SyncDesposit();
                            $syncDespositModel->login = $reuslt['login'];
                            $syncDespositModel->amount = $reuslt['amount'];
                            $syncDespositModel->comment = 'Deposit';
                            $syncDespositModel->memo = $merOrderId;
                            $syncDespositModel->type = 2;
                            $syncDespositModel->in_time = time();
                            $syncDespositModel->save();
                        }
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public function outNotify($success)
    {
        if ($success == true) {
            return "OK";
        } else {
            return "FAIL";
        }
    }

    /**
     * @param array $data
     * @return bool
     */
    public function handleReturn($data)
    {
        Yii::warning('支付异步通知参数，' . VarDumper::dumpAsString($data), __METHOD__);
        if (isset($data['sign']) && trim($data['sign']) !== '') {
            // 1. 加密所需参数
            $signData = [];
            foreach (['memberid', 'orderid', 'amount', 'datetime', 'transaction_id', 'returncode'] as $field) {
                $signData[$field] = isset($data[$field]) ? $data[$field] : null;
            }
            // 2. 根据createLinkString方法进行参数排序处理
            $sign = PayUtils::createLinkString($signData, $this->comkey);
            if ($sign == $data['sign']) {
                if ($data['returncode'] == '00') {
                    $merOrderId = trim($data['orderid']);
                    $merOrderId = str_ireplace("SN", "", $merOrderId);
                    /** @var Deposit $model */
                    $model = Deposit::find()->where(['id' => $merOrderId])->asArray()->limit(1)->one();
                    if ($model) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public function outReturn($success)
    {
    }
}