<?php
/**
 * Created by PhpStorm.
 * User: zhengmingwei
 * Date: 2020/1/7
 * Time: 10:01 下午
 */


namespace addons\unishop\controller;

use addons\epay\library\Service;
use addons\unishop\extend\Ali;
use addons\unishop\extend\Hashids;
use addons\unishop\extend\Wechat;
use addons\unishop\model\Config;
use think\Db;
use think\Exception;
use think\Hook;
use think\Log;

class Pay extends Base
{
    protected $noNeedLogin = ['getPayType', 'notify', 'authRedirect', 'alipay', 'alinotify'];

    /**
     * 获取支付类型
     */
    public function getPayType()
    {
        $platfrom = $this->request->header('platform');
        $type = [];
        $offline = Config::getByName('offline_pay')['value'] == 1 ? true : false;
        switch ($platfrom) {
            case 'APP-PLUS';
                $type = ['alipay' => true, 'wxpay' => true, 'offline' => $offline];
                break;
            case 'H5':
                $type = ['alipay' => true, 'wxpay' => true, 'offline' => $offline];
                // 如果是微信内访问 公众号等
                if (Wechat::h5InWechat()) {
                    $type['alipay'] = false;
                }
                break;
            case 'MP-WEIXIN':
                $type = ['alipay' => false, 'wxpay' => true, 'offline' => $offline];
                break;
            case 'MP-ALIPAY':
                $type = ['alipay' => true, 'wxpay' => false, 'offline' => $offline];
                break;
            case 'MP-BAIDU':
                $type = ['alipay' => false, 'wxpay' => false, 'offline' => $offline];
                break;
            case 'MP-TOUTIAO':
                $type = ['alipay' => false, 'wxpay' => false, 'offline' => $offline];
                break;
        }
        $this->success('', $type);
    }

    /**
     * 微信统一下单接口
     */
    public function unify()
    {

        $orderId = $this->request->request('order_id', 0);
        $orderId = Hashids::decodeHex($orderId);

        $orderModel = new \addons\unishop\model\Order();
        $order = $orderModel->where(['id' => $orderId])->find();

        try {
            if (!$order) {
                $this->error(__('Order does not exist'));
            }

            $products = $order->products()->select();

            $body = Config::getByName('name')['value'];
            foreach ($products as $product) {
                $body .= '_' . $product['title'];
            }
            //MWEB
            $platfrom = $this->request->header('platform', 'MP-WEIXIN');

            switch ($platfrom) {
                case 'MP-WEIXIN':
                    $trade_type = 'JSAPI';
                    break;
                case 'H5':
                case 'APP-PLUS':
                    $trade_type = 'MWEB';
                    break;
            }
            // 如果是微信内访问 公众号等
            if (Wechat::h5InWechat()) {
                $trade_type = 'wap';
            }
            $params = [
                'amount' => bcmul($order['total_price'], 100),
                'orderid' => $order->out_trade_no,
                'type' => "wechat",
                'title' => $body,
                'notifyurl' => Config::getByName('notify_url')['value'],
                'trade_type' => $trade_type,

            ];
            return Service::submitOrder($params);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 支付通知回调
     */
    public function notify()
    {
        // 添加行为
        Hook::add('paid_success', 'addons\\unishop\\behavior\\Order');
        Hook::add('paid_fail', 'addons\\unishop\\behavior\\Order');

        $paytype = $this->request->param('type');
        file_put_contents(ROOT_PATH . '/runtime/log/' . date('Ym') ."/".date("d"). '.log', $paytype . PHP_EOL, FILE_APPEND);
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];

//            $paytype="alipay";
//            $payamount =11;
//            $out_trade_no = "202009205f6707697421b23";

            //你可以在此编写订单逻辑
            //Log::record('Alipay notify ,支付成功');

            // 条件一
            $orderModel = new \addons\unishop\model\Order(); //($message['out_trade_no']);
            $order = $orderModel->where(['out_trade_no' => $out_trade_no])->find();
            if (!$order || $order->have_paid != \addons\unishop\model\Order::PAID_NO) {
                throw new Exception('订单不存在或已完成');
            }

            // 条件二
            if ($order->total_price > $payamount || $order->total_price < $payamount) {
                throw new Exception('金额不一');
            }

            // 添加行为
            Hook::add('paid_success', 'addons\\unishop\\behavior\\Order');
            $payTypeString = $paytype == 'alipay' ? \addons\unishop\model\Order::PAY_ALIPAY : \addons\unishop\model\Order::PAY_WXPAY;
            Hook::listen('paid_success', $order, ['pay_type' => $payTypeString]);
        } catch (Exception $e) {
        }
        $pay = new \Yansongda\Pay\Pay();
        echo $pay->success();
    }

    /**
     * 在线支付
     */
    public function offline()
    {
        $orderId = $this->request->get('order_id', 0);
        $orderId = Hashids::decodeHex($orderId);

        $orderModel = new \addons\unishop\model\Order();
        $order = $orderModel->where(['id' => $orderId])->find();

        if (!$order) {
            $this->error(__('Order does not exist'));
        }
        try {
            Db::startTrans();

            Hook::add('paid_success', 'addons\\unishop\\behavior\\Order');
            Hook::listen('paid_success', $order, ['pay_type' => \addons\unishop\model\Order::PAY_OFFLINE]);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('', true);
    }

    /**
     * 微信内H5-JSAPI支付
     */
    public function jssdkBuildConfig()
    {
        $app = Wechat::initEasyWechat('payment');
        $configData = $app->jssdk->buildConfig(['chooseWXPay'], false, true, false);
        $this->success('', $configData);
    }

    /**
     * 支付宝支付
     */
    public function alipay()
    {
        $orderId = $this->request->request('order_id', 0);
        $orderId = Hashids::decodeHex($orderId);

        $orderModel = new \addons\unishop\model\Order();
        $order = $orderModel->where(['id' => $orderId])->find();

        try {
            if (!$order) {
                $this->error(__('Order does not exist'));
            }
            $products = $order->products()->select();

            $body = Config::getByName('name')['value'];
            foreach ($products as $product) {
                $body .= '_' . $product['title'];
            }
            $params = [
                'amount' => $order->total_price,
                'orderid' => $order->out_trade_no,
                'type' => "alipay",
                'title' => $body,
                'notifyurl' => Config::getByName('ali_notify_url')['value'],
                'returnurl' => Config::getByName('ali_return_url')['value'],
                'method' => "wap",
            ];

            return Service::submitOrder($params);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

    }


}