<?php

namespace app\controller;

use app\repository\OrderRepository;
use app\service\wx\WechatPay;
use Exception;
use think\facade\Log;
use think\response\Redirect;

class Index extends Base
{
    /**
     * @return Redirect
     * @throws Exception
     */
    public function index(): Redirect
    {
        return $this->redirect('/manager');
    }

    /**
     * 退出
     *
     * @return Redirect
     */
    public function logout(): Redirect
    {
        session('frontend_auth', null);
        $req = $this->request->header('referer');
        return $this->redirect($req);
    }

    /**
     * 微信的回调
     *
     * @throws \EasyWeChat\Kernel\Exceptions\Exception
     */
    public function callback()
    {
        if ($this->request->isPost()) {
            $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);
                if (!$order = OrderRepository::getInstance()->findOneByWhere(['coding' => $message['out_trade_no']])) {
                    $this->log(sprintf("[微信支付回调][%s][%s]订单支付成功，但系统查无此订单 info:%s", date('Y-m-d H:i:s'), $message['out_trade_no'], $m), 'error');
                    return true;//订单不存在
                }

                //记录日志
                $this->log(sprintf("[微信支付回调][%s][%s]订单支付成功 info:%s", date('Y-m-d H:i:s'), $message['out_trade_no'], $m), 'info');

                if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                    //更改订单状态
                    try {
                        $res = false;
                        // 用户是否支付成功
                        if (isset($message['result_code']) && $message['result_code'] === 'SUCCESS') {
                            //记录日志
                            $res = OrderRepository::getInstance()->setPaid($order['coding']);

                            $this->log(sprintf("[微信支付回调][%s][%s]订单支付成功 修改订单状态为%s", date('Y-m-d H:i:s'), $message['out_trade_no'], $res), 'info');

                            // 用户支付失败
                        } elseif (isset($message['result_code']) && $message['result_code'] === 'FAIL') {
                            //记录日志
                            $this->log(sprintf("[微信支付回调][%s][%s]订单支付失败 修改订单状态为%s", date('Y-m-d H:i:s'), $message['out_trade_no'], $res), 'info');
                        }

                        if (!$res) {
                            return $fail('Order status edit failed.');
                        }
                    } catch (Exception $e) {
                        $this->log(sprintf("[微信支付回调][%s][%s]订单支付失败 失败原因：%s", date('Y-m-d H:i:s'), $message['out_trade_no'], $e->getMessage()), 'info');
                        //错误信息 触发
                        return $fail('Order error.');
                    }
                } else {
                    return $fail('通信失败，请稍后再通知我');
                }

                return true;
            });

            $response->send();
        }
    }

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