<?php

/**
 * Created by PhpStorm.
 * User: pc
 * Date: 2021/11/25
 * Time: 10:38
 */

namespace app\api\controller;

use app\api\model\PaymentLogModel;
use app\common\controller\Api;
use app\admin\model\users\Users as UsersModel;
use EasyWeChat\Factory;
use stdClass;
use think\Log;
use think\Exception;
use think\Config;


class Weixinpay extends Api
{
    protected $noNeedLogin = ['weixincallback'];
    protected $noNeedRight = ['*'];


    /**
     * 微信支付
     */
    public function weixinPay()
    {
        $log_id = $this->request->post('log_id', 0);
        $amount = $this->request->post('amount', 0);
        //        $user_type = $this->request->post('user_type','wechat');//wechat:小程序    app
        $pay_log = PaymentLogModel::where(['id' => $log_id, 'status' => 1])->find();
        if (!$pay_log) {
            $this->error('该支付记录不存在');
        }

        $userinfo = UsersModel::where(['id' => $this->auth->id])->find();
        $ret = PaymentLogModel::checkPayMoney($pay_log,$amount);
        if (!$ret) {
            $this->error('支付金额不对');
        }
        try{
            $openid = $userinfo['wx_openid'];
            $login_config = Config::get('testConfig');
            $app = Factory::payment($login_config);
            $res = $app->order->unify([
                'body' => $pay_log['order_type']=='goods'?'商城购物订单':'充电桩购买订单',
                'out_trade_no' => $pay_log['order_sn'],
                'total_fee' => (int)($amount * 100),
                'notify_url' => getDomain() . '/api.php/Weixinpay/weixinCallback', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
                'openid' => $openid,
            ]);
            Log::record('微信回调地址' . getDomain() . '/api.php/Weixinpay/weixinCallback', 'debug');
            $result = $app->jssdk->bridgeConfig($res['prepay_id'], false);
            Log::record('调起微信支付成功log_id：' . $log_id, 'debug');
        }catch (Exception $e){
            Log::record($log_id . '调起微信支付失败！', 'debug');
            $this->error('调起微信支付失败！' . $e->getMessage());
        }
        $this->success('调起微信支付成功', ['result' => $result]);

    }

    /**
     *
     * 微信支付回调
     */
    public function weixinCallback()
    {
        $login_config = Config::get('testConfig');
        $app = Factory::payment($login_config);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            //判断是否成功拉起支付
            if ($message['return_code'] != 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                return $fail('通信失败，请稍后再通知我');
            }

            // 用户是否支付成功
            if ($message['return_code'] === 'SUCCESS') {
                if (strpos($message['out_trade_no'], 'D') === 0) {
                    $ret = PaymentLogModel::dealCallBack($message); //支付成功后回调
                }
                if (strpos($message['out_trade_no'], 'R') === 0) {
                    $ret = PaymentLogModel::dealRechargeBack($message); //充值支付成功后回调
                }
                if (strpos($message['out_trade_no'], 'G') === 0) {
                    $ret = PaymentLogModel::dealGoodsBack($message); //商城支付成功后回调
                }
                if (isset($ret) && $ret != true) {
                    Log::record('订单支付日志' . $ret['out_trade_no'] . '微信支付回调处理失败！'.$ret['msg'], 'debug');
                    throw new Exception('回调失败'.$ret['msg']);
                }
            } else {
                Log::record('订单支付日志' . $message['out_trade_no'] . '微信支付失败！', 'error');
            }
            return true;
        });
        $response->send(); // return $response;
    }

    public function testback(){
        $message = $this->request->post();
        if (strpos($message['out_trade_no'], 'R') === 0) {
            $ret = PaymentLogModel::dealRechargeBack($message); //充值支付成功后回调
        }
        dump($ret);die;
        if (isset($ret) && $ret != true) {
            Log::record('订单支付日志' . $ret['out_trade_no'] . '微信支付回调处理失败！'.$ret['msg'], 'debug');
            $this->error($ret['msg']);
        }
    }
}