<?php

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

namespace app\api\controller;

use app\api\model\OrderModel;
use app\common\controller\Api;
use app\api\model\PaymentLogModel;
use app\api\model\UsersModel;
use app\api\model\PolypayQueryLogModel;
use app\lib\model\PaymentLogsModel;
use EasyWeChat\Factory;
use think\Log;
use think\Exception;
use think\Config;


class Weixinpay extends Api
{

    protected $noNeedLogin = ['weixincallback', 'polypaycallback'];

    /**
     * 微信支付
     */
    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('该支付记录不存在');
        }
        //        $this->login_type = $user_type;
//        $userinfo = UsersModel::where(['id' => $this->auth->id])->find();
        $userinfo = $this->auth->getUserinfo();
        $ret = PaymentLogModel::checkPayMoney($pay_log, $amount);
        if (!$ret) {
            $this->error('支付金额不对');
        }
        if($pay_log['order_type']=="goods"){
            $body="虚拟商品订单";
        }else if($pay_log['order_type']=="recharge"){
            $body="充值订单";
        }
        $params = [
            'body' => $body,
            'out_trade_no' => $pay_log['order_sn'],
            'total_fee' => (int)($amount * 100),
            'notify_url' => getDomain() . '/api.php/Weixinpay/weixinCallback', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
//                'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
        ];
        if ($this->login_type == 'app') {
            $params['trade_type'] = 'APP';//APP支付
//            $openid = $userinfo['app_openid'];
            $login_config = Config::get('appConfig');
        } else {
            $openid = $userinfo['wx_openid'];
            if(!$openid){
                $this->error('请先进行微信授权再行支付');
            }
            $params['trade_type'] = 'JSAPI';//小程序支付
            $params['openid'] = $openid;
            $login_config = Config::get('formalConfig');
        }

        try {
            $app = Factory::payment($login_config);
            $res = $app->order->unify($params);
            Log::record('微信回调地址' . getDomain() . '/api.php/Weixinpay/weixinCallback', 'debug');
            if ($this->login_type == 'app') {
                $result = $app->jssdk->appConfig($res['prepay_id']);
            } else {
                $result = $app->jssdk->bridgeConfig($res['prepay_id'], false);
            }
            Log::record('调起微信支付成功log_id：' . $log_id, 'debug');
            $this->success('调起微信支付成功', ['result' => $result]);
        } catch (Exception $e) {
            Log::record($log_id . '调起微信支付失败！', 'debug');
            $this->error('调起微信支付失败！' . $e->getMessage());
        }
    }


    /**
     *
     * 微信支付回调
     */
    public function weixinCallback()
    {
        if ($this->login_type == 'app') {
            $login_config = Config::get('appConfig');
        } else {
            $login_config = Config::get('formalConfig');
//            $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'], 'R') === 0||strpos($message['out_trade_no'], 'G') === 0) {
//                    Log::record('订单支付编号' . $message['out_trade_no'], 'debug');
                    $ret = PaymentLogModel::dealRechargeBack($message); //充值支付成功后回调
                }
                if (isset($ret) && $ret == false) {
                    Log::record('订单支付日志' . $_POST['out_trade_no'] . '微信支付回调处理失败！', 'debug');
                    throw new Exception('回调失败');
                }
            } else {

                Log::record('订单支付日志' . $message['out_trade_no'] . '微信支付失败！', 'error');
            }
            return true;
        });
        $response->send(); // return $response;
    }

    /**
     * 微信退款
     */
    // public function weixinRefund($log_id){
    //     $pay_log = PaymentLogModel::where(['id' =>$log_id,'order_type' =>'car'])->find();
    //     if(!$pay_log){
    //         return false;
    //     }
    //     try{
    //         $login_config =Config::get('testConfig');
    //         $app = Factory::payment($login_config);
    //         $out_refund_no = getOrdersn('car');
    //         $res = $app->refund->byOutTradeNumber(
    //             $pay_log['order_sn'],//商户订单号
    //             $out_refund_no,//商户退款单号
    //             (int)($pay_log['need_pay']*100),//订单金额
    //             (int)($pay_log['need_pay']*100),//退款金额
    //             ['refund_desc' =>'洗车工未接单']//退款原因
    //         );
    //         if($res['result_code'] == 'SUCCESS'){
    //             OrderModel::where(['order_id' =>$pay_log['order_id'],'order_type' =>'car'])->update(['status' =>-1]);//已取消
    //             PaymentLogModel::where(['order_id' =>$pay_log['order_id'],'order_type' =>'car'])->update(['status' =>-2]);//支付取消
    //             $users = UsersModel::where(['id' =>$pay_log['user_id']])->find();
    //             $user_money_log =[
    //                 'user_id' =>$pay_log['user_id'],
    //                 'money' =>$pay_log['need_pay'],
    //                 'before' =>$users['money'],
    //                 'after' =>$users['money'],
    //                 'memo' =>'用户取消洗车订单',
    //                 'createtime' =>time(),
    //             ];
    //             $result = UserDetailMoneyModel::create($user_money_log);//生成退款日志
    //             return true;
    //         }
    //     }catch (Exception $e){
    //         Log::record($pay_log['id'] . '微信退款失败！'.$e->getMessage(),'error');
    //         return false;
    //     }
    // }
}
