<?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\ais\controller\api\v1;
use app\common\facade\WechatPay;
use app\ais\controller\api\Base;
use app\ais\model\AisBank;
use app\ais\model\AisBill;
use app\ais\model\AisCouponUser;
use app\ais\model\AisOrder;
use app\ais\model\AisShop;
use app\ais\model\AisShopCoupon;
use app\ais\model\AisShopOrder;
use app\ais\model\AisStoreBill;
use app\ais\model\AisVip;
use app\ais\model\AisVipOrder;
use app\ais\model\AisVipUser;
use app\ais\model\AisInfo;
use app\ais\model\AisInfoOrder;
use app\ais\model\AisConfig;
use think\facade\Log;
use filter\Filter;
use Exception;

class Notify extends Base{

    /**
     * 微信付款买单
     * @return void
     */
    public function storePay(){
        try {
            $response = WechatPay::doPay($this->miniapp_id)->handlePaidNotify(function ($message,$fail) {
                $result = AisOrder::where(['state' => 0,'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'){
                                    //订单状态
                                    $result->state     = 1;
                                    $result->paid_time = strtotime($ispay['time_end']);
                                    $result->paid_no   = $ispay['transaction_id'];
                                    //收益计算
                                    $result = AisOrder::income($result,money($ispay['total_fee'] / 100),$ispay['attach']);
                                    //消费日志
                                    AisBill::add([
                                        'member_miniapp_id' => $this->miniapp_id,
                                        'store_id'          => $result->store_id,
                                        'money'             => -$result->price,
                                        'uid'               => $result->uid
                                    ],'微信支付[消费]');
                                    AisStoreBill::add([
                                        'member_miniapp_id' => $this->miniapp_id,
                                        'store_id'          => $result->store_id,
                                        'store_chain_id'    => $result->store_chain_id,
                                        'money'             => $result->real,
                                        'pay_uid'           => $result->uid
                                    ],'微信支付[收款]');
                                    if ($result->coupon_user_id > 0) {
                                        AisCouponUser::where(['id' => $result->coupon_user_id])->update(['is_end' => 1,'money' => money($result->amount - $result->price),'update_time' => time()]);    //优惠券减少
                                    }
                                    $vip_user = AisVipUser::where(['member_miniapp_id' => $this->miniapp_id,'uid' => $result->uid])->find();
                                    if(empty($vip_user)){
                                        $vip = AisVip::where(['member_miniapp_id' => $this->miniapp_id,'is_lock' => 0])->order('sort desc')->find();
                                        if(!empty($vip)){
                                            AisVipUser::create([
                                                'update_time'       => time(),
                                                'is_lock'           => 0,
                                                'vip_id'            => $vip->id,
                                                'uid'               => $result->uid,
                                                'member_miniapp_id' => $this->miniapp_id
                                            ]);
                                            AisVipOrder::create([
                                                'create_time'       => time(),
                                                'amount'            => 0,
                                                'vip_id'            => $vip->id,
                                                'uid'               => $result->uid,
                                                'member_miniapp_id' => $this->miniapp_id,
                                                'state'             => $result->state,
                                                'order_no'          => $result->order_no,
                                                'paid_time'         => $result->paid_time,
                                                'paid_no'           => $result->paid_no
                                            ]);
                                        }
                                    }
                                    //积分增加
                                    $bank = AisBank::where(['uid' => $result->uid])->find();
                                    if(empty($bank)){
                                        $bank = new AisBank;
                                        $bank->uid = $result->uid;
                                        $bank->member_miniapp_id = $result->member_miniapp_id;
                                        $bank->point = 0;
                                    }
                                    $bank->point = $bank->point + intval($result->price);
                                    $bank->save();
                                    $result->allowField(true)->save();
                                    AisOrder::subsidy($result);
                                    return true;
                                }
                            }
                        }
                    }
                }
                return $fail('通信失败,请稍后再通知我');
            });
            $response->send();
        }catch (Exception $e) {
            $this->error('页面不存在');
        }
    }

   /**
     * 优选下单
     * @return void
     */
    public function shop(){
        try{
            $response = WechatPay::doPay($this->miniapp_id)->handlePaidNotify(function ($message,$fail) {
                $result = AisShopOrder::where(['status'=>0,'paid_at'=>0,'is_del'=>0,'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') {
                                    //修改订单状态和减少库存
                                    $result->paid_at   = 1;
                                    $result->paid_time = strtotime($ispay['time_end']);
                                    $result->paid_no   = $ispay['transaction_id'];
                                    AisShop::where(['id' => $result->shop_id])->setDec('warehouse_num',1);  //减库存
                                    //减去所用积分
                                    if($result['points']){
                                        $user = AisVipUser::where(['member_miniapp_id'=>$this->miniapp_id,'uid' => $result->user_id,'is_lock' => 0])->find();
                                        $user->point  = $user->point - $result->points;
                                        $user->point  = $user->point + intval($result->amount);
                                        $user->update_time = time();
                                        $user->save();
                                    }
                                    //增加日志
                                    AisBill::add([
                                        'miniapp_id' => $this->miniapp_id,
                                        'store_id'   => $result->store_id,
                                        'money'      => -$result->amount,
                                        'uid'        => $result->user_id
                                    ],'微信支付[购买商品]');
                                    $result = AisShopOrder::income($result->toArray(),money($ispay['total_fee'] / 100),$ispay['attach']);
                                    AisStoreBill::add([
                                        'miniapp_id' => $result->member_miniapp_id,
                                        'uid'        => $result->user_id,
                                        'store_id'   => $result->store_id,
                                        'pay_uid'    => $result->uid,
                                        'money'      => $result->real
                                    ],'优选下单结算到商户号');
                                    //赠送优惠券
                                    AisCouponUser::addUserCoupon(json_encode(AisShopCoupon::where(['member_miniapp_id'=>$this->miniapp_id,'shop_id' => $result->shop_id])->column('coupon_id')),$result->user_id);
                                    $result->allowField(true)->save();
                                    return true;
                                }
                            }
                        }
                    }
                }
                return $fail('通信失败,请稍后再通知我');
            });
            $response->send();
        }catch (Exception $e) {
            $this->error('页面不存在');
        }
    } 

    /**
     * 发布付费城市号
     *  @return void
     */
    public function infoSend(){
        try {
            $response = WechatPay::doPay($this->miniapp_id)->handlePaidNotify(function($message,$fail){
                $order = AisInfo::where(['paid_at'=>0,'order_no' => Filter::filter_escape($message['out_trade_no'])])->find();
                if (empty($order)) {
                    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($order->order_no);
                        if ($ispay['return_code'] === 'SUCCESS') {
                            if ($ispay['result_code'] === 'SUCCESS') {
                                if ($ispay['trade_state'] === 'SUCCESS') {
                                    $order->is_top    = 1;
                                    $order->paid_at   = 1;
                                    $order->paid_no   = $ispay['transaction_id'];
                                    $order->paid_time =  strtotime($ispay['time_end']);
                                    $order->save();
                                    $vip_user = AisVipUser::where(['member_miniapp_id' => $this->miniapp_id,'uid' => $order->uid])->find();
                                    if($vip_user){
                                        //增加积分
                                        $vip_user->point  = $vip_user->point + intval($order->price);
                                        $vip_user->update_time = time();
                                        $vip_user->save();
                                    }
                                    return true;
                                }
                            }
                        }
                    }
                }
                return $fail('通信失败,请稍后再通知我');
            });
            $response->send();
        }catch (Exception $e) {
            $this->error('页面不存在');
        }
    }

    /**
     * 城市号下单
     * @return void
     */
    public function infoOrder(){
        try {
            $response = WechatPay::doPay($this->miniapp_id)->handlePaidNotify(function($message,$fail){
                $order = AisInfoOrder::where(['paid_at'=>0,'order_no' => Filter::filter_escape($message['out_trade_no'])])->find();
                if (empty($order)) {
                    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($order->order_no);
                        if ($ispay['return_code'] === 'SUCCESS') {
                            if ($ispay['result_code'] === 'SUCCESS') {
                                if ($ispay['trade_state'] === 'SUCCESS') {
                                    //修改订单状态
                                    $order->paid_at   = 1;
                                    $order->paid_no   = $ispay['transaction_id'];;
                                    $order->paid_time = strtotime($ispay['time_end']);
                                    $order->save();
                                    //扣除服务费到账
                                    $setting = AisConfig::getConfig($this->miniapp_id);
                                    $amount = money($order->amount-(money(abs($order->amount*$setting->charge/100))));
                                    AisBill::add(['member_miniapp_id' => $this->miniapp_id,'store_id' => 0,'money' => $amount,'uid' => $order->uid,'pay_uid' => $order->uid], '城市号下单');
                                    AisBill::add(['member_miniapp_id' => $this->miniapp_id,'store_id' => 0,'money' => $amount,'uid' => $order->info_uid,'pay_uid' => $order->uid], '城市号订单');
                                    $vip_user = AisVipUser::where(['member_miniapp_id' => $this->miniapp_id,'uid' => $order->uid])->find();
                                    if($vip_user){
                                        //增加积分
                                        $vip_user->point  = $vip_user->point + intval($order->amount);
                                        $vip_user->update_time = time();
                                        $vip_user->save();
                                    }
                                    return true;
                                }
                            }
                        }
                    }
                }
                return $fail('通信失败,请稍后再通知我');
            });
            $response->send();
        }catch (Exception $e) {
            $this->error('页面不存在');
        }
    }

    /**
     * 开通会员支付回调
     */
    public function vipPay(){
        try {
            $response = WechatPay::doPay($this->miniapp_id)->handlePaidNotify(function ($message,$fail) {
                $result = AisVipOrder::where(['state' => 0,'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->member_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'){
                                    //订单状态
                                    $result->state     = 1;
                                    $result->paid_time = strtotime($ispay['time_end']);
                                    $result->paid_no   = $ispay['transaction_id'];
                                    //收益计算
                                    AisVipOrder::income($result,money($ispay['total_fee']/100));
                                    //消费日志
                                    AisBill::add(['member_miniapp_id' => $this->member_miniapp_id,'store_id' => 0,'money' =>-$result->amount,'uid' => $result->uid],'微信支付[开通会员]');
                                    //重置并锁定其它级别会员
                                    AisVipUser::where(['uid' => $result->uid])->update(['is_lock' => 1]);
                                    //新增开通当前会员
                                    AisVipUser::create(['member_miniapp_id' => $this->member_miniapp_id,'uid' => $result->uid,'vip_id' => $result->vip_id,'is_lock' => 0,'update_time' => time()]);
                                    AisBank::points($this->member_miniapp_id,$result->uid,$result->amount);
                                    //领取的优惠券
                                    AisCouponUser::addUserCoupon($result->coupon_ids,$result->uid);
                                    $result->allowField(true)->save();
                                    return 'true';
                                }
                            }
                        }
                    }
                }
                return $fail('通信失败,请稍后再通知我');
            });
            $response->send();
        }catch (Exception $e) {
            $this->error('页面不存在');
        }
    }
}