<?php

namespace app\controller\api;

use app\exception\RepositoryException;
use app\repository\BusinessRepository;
use app\repository\RechargeRepository;
use app\service\wx\WechatPay;
use app\model\Recharge as RechargeModel;
use think\facade\Db;
use think\facade\Log;

/**
 * 充值
 *
 * Class Recharge
 * @package app\controller\api
 */
class Recharge extends Base
{
    protected $noNeedLogin = ['query',"notify"];

    /**
     * 查询是否支付成功
     * */
    public function query()
    {
        $orderNum = input("order_num/s");
        if (empty($orderNum)) {
            return $this->json("4001", "参数错误");
        }
        $recharge = RechargeRepository::getInstance()->getModel()->where(["order_num" => $orderNum])->lock(true)->find();
        if (empty($recharge)) {
            return $this->json("4001", "订单不存在");
        }
        if ($recharge['state'] == RechargeModel::state_on) {
            return $this->json(0,"该订单已支付成功");
        }
        $business = BusinessRepository::getInstance()->getModel()->where(["code" => $recharge['business_code']])->lock(true)->find();
        if (empty($business)) {
            return $this->json("4001", "商家不存在");
        }
        //查询  交易成功判断条件: return_code、result_code和trade_state都为SUCCESS
        $res = WechatPay::getInstance()->order->queryByOutTradeNumber($orderNum);
        if ($res['return_code'] == 'SUCCESS') { // return_code 表示通信状态,不代表支付状态
            if (isset($res['result_code']) && $res['result_code'] == 'SUCCESS') {
                if (isset($res['trade_state']) && $res['trade_state'] == 'SUCCESS') {
                    Db::startTrans();
                    try {
                        //这里确定支付成功
                        $total_fee = $res['total_fee'] / 100;
                        //加余额
                        $business->save([
                            "balance" => ($business["balance"] + $total_fee),
                            "total_recharge" => ($business["total_recharge"] + $total_fee)
                        ]);
                        //修改支付状态
                        $recharge->save([
                            "money" => $total_fee,
                            "state" => RechargeModel::state_on,
                            "open_id" => $res['openid'],
                            "update_time" => date("Y-m-d H:i:s"),
                            "balance" => $business->balance
                        ]);
                        Db::commit();
                        return $this->json();
                    } catch (RepositoryException $e) {
                        Db::rollback();
                        return $this->json("5001", $e->getMessage());
                    } catch (\Exception $e) {
                        Db::rollback();
                        return $this->json("5001", "充值失败");
                    }
                }
            }
        }
        return $this->json("4001", "未支付成功");
    }

    /**
     * 微信的回调
     *
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function notify(){
        if ($this->request->isPost()) {
            $this->log("回调触发了");
            $app      = WechatPay::getInstance();
            $response = $app->handlePaidNotify(function ($message, $fail) {
                //                $aa = '{"appid":"wxa02e44170bc722cd","bank_type":"OTHERS","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1605090111","nonce_str":"60f7d8a1e4ac8","openid":"oKrEm0ehgsy2ZTWzEva4tbLuUgFw","out_trade_no":"16268555858753004863","result_code":"SUCCESS","return_code":"SUCCESS","sign":"DB3F6CDCB7FBB3B9DDF7C0CC8BBD5AAD","time_end":"20210721162000","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200001200202107217942681078"}';
                //                $message = json_decode($aa, true);
                $m     = json_encode($message, JSON_UNESCAPED_UNICODE);
                $this->log($m);
                $recharge = RechargeRepository::getInstance()->getModel()->where(["order_num" => $message['out_trade_no']])->lock(true)->find();
                if (empty($recharge)) {
                    $this->log(sprintf("[微信支付回调][%s][%s]订单支付成功,但系统查无此订单", date('Y-m-d H:i:s'), $message['out_trade_no']), 'error');
                    return true;//订单不存在
                }
                if ($recharge['state'] == RechargeModel::state_on) {
                    $this->log("订单已支付". $message['out_trade_no']);
                    return true;//订单已经支付
                }
                $business = BusinessRepository::getInstance()->getModel()->where(["code" => $recharge['business_code']])->lock(true)->find();
                if (empty($business)) {
                    $this->log(sprintf("[微信支付回调][%s][%s]订单支付成功,但商家不存在", date('Y-m-d H:i:s'), $message['out_trade_no']), 'error');
                    return true;
                }


                if ($message['return_code'] == 'SUCCESS') { // return_code 表示通信状态,不代表支付状态
                    if (isset($message['result_code']) && $message['result_code'] == 'SUCCESS') {
                            $this->log("开始数据操作");
                            Db::startTrans();
                            try {
                                //这里确定支付成功
                                $total_fee = $message['total_fee'] / 100;
                                //加余额
                                $business->save([
                                    "balance" => ($business["balance"] + $total_fee),
                                    "total_recharge" => ($business["total_recharge"] + $total_fee)]
                                );
                                //修改支付状态
                                $recharge->save([
                                    "money" => $total_fee,
                                    "state" => RechargeModel::state_on,
                                    "open_id" => $message['openid'],
                                    "update_time" => date("Y-m-d H:i:s"),
                                    "balance" => $business->balance
                                ]);
                                Db::commit();
                                //记录日志
                                $this->log(sprintf("[微信支付回调][%s][%s]订单支付成功-数据修改成功", date('Y-m-d H:i:s'), $message['out_trade_no']), 'info');
                                return true;
                            } catch (RepositoryException $e) {
                                Db::rollback();
                                $this->log(sprintf("[微信支付回调][%s][%s]订单支付成功-修改订单状态失败-RepositoryException", date('Y-m-d H:i:s'), $message['out_trade_no']), 'info');
                                return $fail('Order status edit failed.');
                            } catch (\Exception $e) {
                                Db::rollback();
                                $this->log(sprintf("[微信支付回调][%s][%s]订单支付成功-修改订单状态失败-Exception", date('Y-m-d H:i:s'), $message['out_trade_no']), 'info');
                                return $fail('Order status edit failed.');
                            }

                    }
                }
                return $fail('通信失败,请稍后再通知我');
            });

            $response->send();
        }
    }
    /**
     * 记录订单日志
     *
     * @param string $message
     * @param string $type
     */
    private function log(string $message, string $type = 'info'): void
    {
        Log::channel('order')->write($message, $type);
    }
}