<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 16/6/4
 * Time: 上午11:12
 */

require_once (BASE_ROOT_PATH . "/helper/session_helper.php");
require_once (BASE_ROOT_PATH . '/helper/bonus_helper.php');
require_once (BASE_ROOT_PATH . '/helper/account_helper.php');

require_once (BASE_ROOT_PATH . '/helper/pay/IPay.php');
require_once (BASE_ROOT_PATH . '/helper/pay/alipay.php');
require_once (BASE_ROOT_PATH . '/helper/pay/wxpay.php');
require_once (BASE_ROOT_PATH . '/helper/pay/cmbpay.php');
require_once (BASE_ROOT_PATH . '/helper/pay/jspay.php');

class pay_helper
{
    const WX_PAYMENT = "wxpay";
    const ALI_PAYMENT = "alipay";
    const CMB_PAYMENT = "cmbpay";
    const PUBWX_PAYMENT = "jspay";

    public function __construct() {
    }

    static public function pay_types()
    {
        //支付宝,微信,招商银行,各自的描述语
        $types = [];
        $types[] = array("payment" => "wxpay","desc" => "");
        $types[] = array("payment" => "alipay","desc" => "");
        $types[] = array("payment" => "cmbpay","desc" => "");
        return $types;
    }

    static public function pay_bonus($pay_sn)
    {
        $member_info = array('member_id' => $_SESSION['member_id'], 'member_name'  => $_SESSION['member_name']);
        $logic_payment = Logic('payment');
        $logic_payment->payPredepositEx($pay_sn,$member_info);
    }

    static public function pay($pay_sn, $payment,$usebonus,&$err)
    {
        if($usebonus) {
            self::pay_bonus($pay_sn);
        }

        $logic_payment = Logic('payment');
        $payinfo = $logic_payment->getRealOrderInfo($pay_sn, $_SESSION['member_id'],true);
        if (intval($payinfo['data']['api_pay_state']) != 0) {
            $err = array('code' => errcode::ErrPayment, 'msg' => $payinfo['msg']);
            return false;
        }

        $left_cents = intval(doubleval($payinfo['data']['api_pay_amount']) * 100 + 0.5);
        if($left_cents == 0)
        {
            $output['need_pay'] = false;
            $output['tips'] = "已经用红包支付完成";

            $payinfo = self::update_order($pay_sn, $pay_sn, 'bonus');  // 更新订单
            if (isset($payinfo) && $payinfo['state'])
            {
                if(is_pushoms())
                {
                    $logic_delivery = Logic('delivery');
                    $ret = $logic_delivery->putOrder($pay_sn, $pay_sn);
                    if(empty($ret)) { //todo must add to 定时任务
                        Log::record("Put order to oms error: pay_sn={$pay_sn},bonus pay.",Log::ERR);
                    }
                }
                $pay_helper = new pay_helper();
                $pay_helper->OnSuccess($pay_sn);
            }
            return $output;
        }
        else
        {
            $pay = null;
            if($payment == "wxpay") {
                $pay = new Pay\wxpay();
            }
            else if($payment == "jspay")
            {
                $openid = session_helper::pub_openid();
                Log::record("openid = {$openid}",Log::DEBUG);
                if(empty($openid)) {
                    $err = array('code' => errcode::ErrPayment, 'msg' => '微信未授权，不可以进行网页支付.');
                    return false;
                }
                else {
                    $pay = new Pay\jspay($openid);
                }
            }
            else if($payment == "alipay") {
                $pay = new Pay\alipay();
            }
            else if($payment == "cmbpay") {
                $pay = new Pay\cmbpay();
            }
            else {
                $err = array('code' => errcode::ErrPayment, 'msg' => $payinfo['msg']);
                return false;
            }

            $subject = $payinfo['data']['subject'];
            $pay_sn  = $payinfo['data']['pay_sn'];
            $order_sn = $payinfo['data']['order_list'][0]['order_sn'];

            $output['need_pay'] = true;
            $output['tips'] = "";

            $third_param = $pay->gen_pay($pay_sn,$left_cents,$order_sn,$subject);
            $output['param'] = $third_param;

            return $output;
        }
    }

    public static function confirm($pay_sn,&$err,&$amount,&$fcode_state)
    {
        $logic_payment = Logic('payment');
        $result = $logic_payment->getRealOrderInfo($pay_sn,null,true);
        if(empty($result)) {
            $err = ['code'=> errcode::ErrOrder,'msg' => '无此订单.'];
            return false;
        }
        $amount = $result['data']['api_pay_amount'];
        $fcode_state = intval($result['data']['fcode_state']);

        if (intval($result['data']['api_pay_state']) == 0) {
            $err = ['code'=> errcode::ErrOrder,'msg' => '此订单未完成支付.'];
            return false;
        }
        else {
            return true;
        }
    }

    public static function check_fee($pay_sn,$total_fee,&$need_pay)
    {
        $logic_payment = Logic('payment');
        $result = $logic_payment->getRealOrderInfo($pay_sn,null,true);

        if (intval($result['data']['api_pay_state']) != 0) {
            return false;
        }

        $need_pay = intval($result['data']['api_pay_amount'] * 100 + 0.5);
        $total_fee = intval($total_fee * 100 + 0.5);

        return ($need_pay === $total_fee);
    }

    static public function paied($pay_sn)
    {
        $logic_payment = Logic('payment');
        $result = $logic_payment->getRealOrderInfo($pay_sn,null,true);
        if (intval($result['data']['api_pay_state']) != 0) {
            return true;
        }

        return false;
    }

    public function OnOmsNotify($order_sn, $express_id, $logistics_no,$logistics_company)
    {
        $model_order = Model('order');
        $order_info = $model_order->getOrderInfo(array('order_sn' => $order_sn),array('order_common','order_goods'));

        $data['reciver_name'] = $order_info['extend_order_common']['reciver_name'];
        $data['reciver_info'] = $order_info['extend_order_common']['reciver_info'];
        $data['deliver_explain'] = $order_info['extend_order_common']['deliver_explain'];
        $data['daddress_id'] = intval($order_info['extend_order_common']['daddress_id']);
        $data['shipping_express_id'] =intval($express_id);
        $data['shipping_code']  = $logistics_no;
        $data['store_id']  = 6;

        $logic_order = Logic('order');
        $result = $logic_order->changeOrderSend($order_info, 'system', $order_info['buyer_name'], $data);

        QueueClient::push('onAsyncOrderSended',
            ['pay_sn' => $order_info['pay_sn'],
             'logistics_company' => $logistics_company,
             'logistics_no' => $logistics_no]);

        return $result['state'];
    }

    public function OnNotify($param,$payment)
    {
        $pay = $this->gen_payment($payment);
        if($pay == null) {
            return false;
        }

        $result = $pay->on_notify($param);
        if($result != false)
        {
            $pay_sn   = $result['pay_sn'];
            $trade_no = $result['trade_no'];

            $cb_info = self::update_order($pay_sn,$trade_no,$payment);
            if ($cb_info['state'] == false) {
                Log::record("update_order fail: pay_sn={$pay_sn},trade_no={$trade_no}", Log::DEBUG);
                return false;
            }
            else
            {
                if(is_pushoms()) {
                    $logic_delivery = Logic('delivery');
                    $logic_delivery->putOrder($pay_sn, $trade_no);
                    Log::record("update_order success: pay_sn={$pay_sn}", Log::DEBUG);
                }
                $this->OnSuccess($pay_sn);

                return true;
            }
        } else {
            return false;
        }
    }

    private function gen_payment($payment)
    {
        if($payment == "wxpay") {
            return new Pay\wxpay();
        }
        else if($payment == "jspay")
        {
            return new Pay\jspay("");
        }
        else if($payment == "alipay") {
            return new Pay\alipay();
        }
        else if($payment == "cmbpay") {
            return new Pay\cmbpay();
        }
        else {
            return null;
        }
    }

    public function OnSuccess($pay_sn)
    {
        $logic_payment = Logic('payment');
        $result = $logic_payment->getRealOrderInfo($pay_sn,null,true);

        if($result['state'] != true) {
            return false;
        } else {
            QueueClient::push('onAsyncOrderPaied',['pay_sn' => $pay_sn]);
            return true;
        }
    }

    public static function update_order($paysn, $trade_no, $payment)
    {
        $logic_payment = Logic('payment');
        $tmp = explode('|', $paysn);
        $paysn = $tmp[0];
        if (!empty($tmp[1])) {
            $order_type = $tmp[1];
        } else {
            $order_pay_info = Model('order')->getOrderPayInfo(array('pay_sn' => $paysn),true);
            if (empty($order_pay_info)) {
                $order_type = 'v';
            } else {
                $order_type = 'r';
            }
        }

        if ($order_type == 'r')
        {
            $result = $logic_payment->getRealOrderInfo($paysn,null,true);
            if (intval($result['data']['api_pay_state'])) {
                return array('state' => true);
            }
            $order_list = $result['data']['order_list'];
            $result = $logic_payment->updateRealOrder($paysn, $payment, $order_list, $trade_no);
        }
        elseif ($order_type == 'v')
        {
            $result = $logic_payment->getVrOrderInfo($paysn);
            if ($result['data']['order_state'] != ORDER_STATE_NEW) {
                return array('state' => true);
            }
            $result = $logic_payment->updateVrOrder($paysn, $payment, $result['data'], $trade_no);
        }

        return $result;
    }
}