<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 支付回调通知
 */
namespace app\allwin\controller\api\v4;
use app\allwin\controller\api\Base;
use app\allwin\model\AllwinUserAgent;
use app\allwin\model\BankBill;
use app\common\event\User;
use app\common\facade\Inform;
use app\common\facade\WechatPay;
use app\common\model\SystemMemberSms;
use filter\Filter;
use Exception;

class Agentnotify extends Base{

    /**
     * 开通社群主申请通知
     * @return void
     */
    public function agent(){
        try{
            $response = WechatPay::doPay($this->miniapp_id)->handlePaidNotify(function ($message,$fail) {
                $result = AllwinUserAgent::where(['pay_state'=>0,'is_type'=>1,'order_no' => Filter::filter_escape($message['out_trade_no'])])->find();
                if (empty($result)) {
                    return true;
                }
                if ($message['return_code'] === 'SUCCESS') {
                    if ($message['result_code'] === 'SUCCESS') {
                        $sub_mchid  = $message['sub_mch_id'] ?? '';
                        $ispay = WechatPay::doPay($this->miniapp_id,false,$sub_mchid)->order->queryByOutTradeNumber($result->order_no);
                        if ($ispay['return_code'] === 'SUCCESS') {
                            if ($ispay['result_code'] === 'SUCCESS') {
                                if ($ispay['trade_state'] === 'SUCCESS') {
                                    AllwinUserAgent::where(['id' => $result->id])->update(['pay_state' => 1,'paid_time' => time(),'wechat_order' =>$ispay['transaction_id']]);
                                    BankBill::add(['miniapp_id'=>$this->miniapp_id,'store_id' => 0,'money' => -$result->price,'uid'=>$result->uid,'pay_uid' => $result->uid], '微信支付[开通社群主]');
                                    //微信申请社群主审核通知
                                    SystemMemberSms::sms($this->miniapp_id,'您有一条社群主申请待审核',url('allwin/user/index'));
                                    //通知申请者到微信
                                    Inform::sms($result['uid'],$this->miniapp_id,['title' =>'业务进展通知','type' => '社群主申请','content' =>'您的社群主申请正在审核中']);
                                    //通知到后台管理的微信
                                    Inform::sms(User::isFounder($this->miniapp_id)->user_id,$this->miniapp_id,['title' =>'业务进展通知','type' => '社群主申请','content' =>'您有一条新的社群主申请待审核']);
                                    return true;
                                }
                            }
                        }
                    }
                }
                return $fail('通信失败,请稍后再通知我');
            });
            $response->send();
        }catch (Exception $e) {
            $this->error('页面不存在');
        }
    }
}