<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */

namespace app\common\logic;

use app\api\controller\Group;
use app\common\enum\AccountLogEnum;
use app\common\enum\NoticeEnum;
use app\common\enum\OrderEnum;
use app\common\enum\OrderLogEnum;
use app\common\enum\PayEnum;
use app\common\model\Article;
use app\common\model\ArticleRewardOrder;
use app\common\model\Merchant;
use app\common\model\MerchantTopList;
use app\common\model\MerchantTopOrder;
use app\common\model\MerchantVipLevel;
use app\common\model\MerchantVipOrder;
use app\common\model\Order;
use app\common\model\TwoOrder;
use app\common\model\TwoPromiseMoneyOrder;
use app\common\model\TwoPromiseMoneyRecord;
use app\common\model\VipOrder;
use app\common\model\TwoOrderLog;
use app\common\model\OrderGoods;
use app\common\model\OrderLog;
use app\common\model\RechargeOrder;
use app\common\model\ArticleOrder;
use app\common\model\GroupOrder;
use app\common\model\CircleOrder;
use app\common\model\User;
use app\common\service\ConfigService;
use think\facade\Db;
use think\facade\Log;

/**
 * 支付成功后处理订单状态
 * Class PayNotifyLogic
 * @package app\api\logic
 */
class PayNotifyLogic extends BaseLogic
{
    public static function handle($action, $orderSn, $extra = [])
    {
        Db::startTrans();
        try {
            self::$action($orderSn, $extra);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            dd($e->getMessage());
            Db::rollback();
            Log::write(implode('-', [
                __CLASS__,
                __FUNCTION__,
                $e->getFile(),
                $e->getLine(),
                $e->getMessage()
            ]));
            self::setError($e->getMessage());
            return $e->getMessage();
        }
    }

    private static function release($orderSn, $extra = [])
    {
        // echo '发帖付费逻辑处理';die;
        // dd($orderSn);

        $order = \app\common\model\Article::where('id', $orderSn)->findOrEmpty();

        $res = \app\common\model\Article::update([
            'release_pay'=>1,
        ],['id'=>$order['id']]);



        // 更新充值订单状态
        // $order->transaction_id = $extra['transaction_id'];
        // $order->pay_status = PayEnum::ISPAID;
        // $order->pay_time = time();
        // $order->save();

         //更新订单状态
        // ArticleOrder::update([
        //     'pay_status' => PayEnum::ISPAID,
        //     'pay_time' => time(),
        //     'transaction_id' => $extra['transaction_id'] ?? ''
        // ], ['id' => $order['id']]);
        
    }
    
    //自营商城下单回调 //调用回调方法统一处理 更新订单支付状态
    private static function order($orderSn, $extra = [])
    {
        $order = Order::with(['order_goods'])->where(['sn' => $orderSn])->findOrEmpty();

        //增加用户累计消费额度
        User::where(['id' => $order['user_id']])
            ->inc('total_order_amount', $order['order_amount'])
            ->inc('total_order_num')
            ->update();


        //更新订单状态
        Order::update([
            'pay_status' => PayEnum::ISPAID,
            'pay_time' => time(),
            'order_status' => OrderEnum::STATUS_WAIT_DELIVERY,
            'transaction_id' => $extra['transaction_id'] ?? ''
        ], ['id' => $order['id']]);


        //订单日志
        (new OrderLog())->record([
            'type' => OrderLogEnum::TYPE_USER,
            'channel' => OrderLogEnum::USER_PAID_ORDER,
            'order_id' => $order['id'],
            'operator_id' => $order['user_id']
        ]);



        // 消息通知 - 通知买家
        event('Notice', [
            'scene_id' =>  NoticeEnum::ORDER_PAY_NOTICE,
            'params' => [
                'user_id' => $order['user_id'],
                'order_id' => $order['id'],
                'mobile'    => $order['address']['mobile'],
                'order_type' => 'order'
            ]
        ]);

        // 消息通知 - 通知卖家
        $mobile = ConfigService::get('shop', 'mall_contact_mobile', '');
        event('Notice', [
            'scene_id' =>  NoticeEnum::SELLER_ORDER_PAY_NOTICE,
            'params' => [
                'mobile' => $mobile,
                'order_id' => $order['id'],
            ]
        ]);
        //更新用户等级
        // UserLogic::updateLevel($order['user_id']);
        
    }

    //二手商城下单回调 //调用回调方法统一处理 更新订单支付状态
    private static function two_order($orderSn, $extra = [])
    {
        $order = TwoOrder::with(['order_goods'])->where(['sn' => $orderSn])->findOrEmpty();

        //增加用户累计消费额度
        User::where(['id' => $order['user_id']])
            ->inc('total_order_amount', $order['order_amount'])
            ->inc('total_order_num')
            ->update();

            
        // 卖家卖出商品增加余额
        // dd($order['order_goods']['goods_snap']);

        //更新订单状态
        TwoOrder::update([
            'pay_status' => PayEnum::ISPAID,
            'pay_time' => time(),
            'order_status' => OrderEnum::STATUS_WAIT_DELIVERY,
            'transaction_id' => $extra['transaction_id'] ?? ''
        ], ['id' => $order['id']]);

        // 卖家卖出一件商品
        \app\common\model\TwoGoodsLog::create([
            'user_id'=>$order->sell_user_id,
            'goods_id'=>$order['order_goods']['goods_snap']['goods_id'],
            'name'=>$order['order_goods']['goods_snap']['goods_name'],
            'image'=>$order['order_goods']['goods_snap']['image'],
            'price'=>$order['order_amount'],
            'desc'=>"卖出了一件宝贝"
        ]);



        //订单日志
        (new TwoOrderLog())->record([
            'type' => OrderLogEnum::TYPE_USER,
            'channel' => OrderLogEnum::USER_PAID_ORDER,
            'order_id' => $order['id'],
            'operator_id' => $order['user_id']
        ]);



        // 消息通知 - 通知买家
        event('Notice', [
            'scene_id' =>  NoticeEnum::ORDER_PAY_NOTICE,
            'params' => [
                'user_id' => $order['user_id'],
                'order_id' => $order['id'],
                'mobile'    => $order['address']['mobile'],
                'order_type' => 'two_order',
            ]
        ]);

        // 消息通知 - 通知卖家
        $mobile = ConfigService::get('shop', 'mall_contact_mobile', '');
        event('Notice', [
            'scene_id' =>  NoticeEnum::SELLER_ORDER_PAY_NOTICE,
            'params' => [
                'mobile' => $mobile,
                'order_id' => $order['id'],
            ]
        ]);

        //更新用户等级
        // UserLogic::updateLevel($order['user_id']);
        
    }

    private static function vip_order($orderSn, $extra = [])
    {

        // echo 'vip订单';die;
        $order = VipOrder::with('level')->where(['sn' => $orderSn])->findOrEmpty();

        $user = User::find($order['user_id']);
        
        //增加用户累计消费额度
        User::where(['id' => $order['user_id']])
            ->inc('total_order_amount', $order['order_amount'])
            ->inc('total_order_num')
            ->update();


        if($user->vip_expire_time > time()){// 如果有会员
            // 如果 升级vip 重新计算时间
            if($user->vip_level_id != $order->vip_level_id){
                $user->vip_expire_time =  time() + $order->vip_time;
            }else{
                $user->vip_expire_time =  $user->vip_expire_time+$order->vip_time;
            }
            
        }else{
            $user->vip_expire_time = time() + $order->vip_time;
        }
        $user->vip_level_id = $order->vip_level_id;
        $user->save();


        
        // 给用户修改vip身份
        // User::where(['id' => $order['user_id']])
        // ->update([
        //         'vip_level_id'=> $order->vip_level_id,
        //         'vip_expire_time'=> time() + $order->vip_time,
        //     ]);


        //更新订单状态
        VipOrder::update([
            'pay_status' =>1,
            'pay_time' => time(),
            'order_status' => 3,
        ], ['id' => $order['id']]);

        


        // //订单日志
        // (new TwoOrderLog())->record([
        //     'type' => OrderLogEnum::TYPE_USER,
        //     'channel' => OrderLogEnum::USER_PAID_ORDER,
        //     'order_id' => $order['id'],
        //     'operator_id' => $order['user_id']
        // ]);



        // // 消息通知 - 通知买家
        // event('Notice', [
        //     'scene_id' =>  NoticeEnum::ORDER_PAY_NOTICE,
        //     'params' => [
        //         'user_id' => $order['user_id'],
        //         'order_id' => $order['id'],
        //         'mobile'    => $order['address']->mobile,
        //         'order_type' => 'two_order',
        //     ]
        // ]);

        // //更新用户等级
        // // UserLogic::updateLevel($order['user_id']);
        
    }

    /**
     * @notes 充值成功回调
     * @param $orderSn
     * @param array $extra
     */
    public static function recharge($orderSn, $extra = [])
    {
        $order = RechargeOrder::where('sn', $orderSn)->findOrEmpty();
        // 增加用户累计充值金额及用户余额
        $user = User::findOrEmpty($order->user_id);
        $user->total_recharge_amount = $user->total_recharge_amount + $order->order_amount;
        $user->user_money = $user->user_money + $order->order_amount;
        $user->save();

        // 记录账户流水
        AccountLogLogic::add($order->user_id, AccountLogEnum::BNW_INC_RECHARGE, AccountLogEnum::INC, $order->order_amount, $order->sn, '用户充值');

        // 更新充值订单状态
        $order->transaction_id = $extra['transaction_id'];
        $order->pay_status = PayEnum::ISPAID;
        $order->pay_time = time();
        $order->save();

        // 充值奖励
        foreach($order->award as $item) {
            if(isset($item['give_money']) && $item['give_money'] > 0) {
                // 充值送余额
                self::awardMoney($order, $item['give_money']);
            }
        }

    }

    /**
     * @notes 付费帖成功回调
     * @param $orderSn
     * @param array $extra
     */
    public static function article($orderSn, $extra = [])
    {
        $order = ArticleOrder::where('sn', $orderSn)->findOrEmpty();

        // 更新充值订单状态
        // $order->transaction_id = $extra['transaction_id'];
        // $order->pay_status = PayEnum::ISPAID;
        // $order->pay_time = time();
        // $order->save();

         //更新订单状态
        ArticleOrder::update([
            'pay_status' => PayEnum::ISPAID,
            'pay_time' => time(),
            'transaction_id' => $extra['transaction_id'] ?? ''
        ], ['id' => $order['id']]);

    }

    /**
     * @notes 付费帖成功回调
     * @param $orderSn
     * @param array $extra
     */
    public static function article_reward($orderSn, $extra = [])
    {
        $order = ArticleRewardOrder::where('sn', $orderSn)->findOrEmpty();
        $article = Article::where('id', $order->article_id)->findOrEmpty();

        // 更新充值订单状态
        // $order->transaction_id = $extra['transaction_id'];
        // $order->pay_status = PayEnum::ISPAID;
        // $order->pay_time = time();
        // $order->save();

        \app\common\model\Rewards::create([
            "article_id"=>$article->id,
            "from_user_id"=>$order->user_id,
            'to_user_id'=>$article->user_id,
            'amount'=>$order->order_amount,
            'message'=>$order->message,
        ]);

        $user = User::findOrEmpty($article->user_id);
        $user->user_money = $user->user_money + $order->order_amount;
        $user->save();

        // 记录账户流水
        AccountLogLogic::add($order->user_id, AccountLogEnum::BW_INC_ARTICLE_REWARD, AccountLogEnum::INC, $order->order_amount, $order->sn, '文章打赏');

        //更新订单状态
        ArticleRewardOrder::update([
            'pay_status' =>1,
            'pay_time' => time(),
            'order_status' => 3,
        ], ['id' => $order['id']]);

    }

    /**
     * @notes 付费帖成功回调
     * @param $orderSn
     * @param array $extra
     */
    public static function two_promise_money($orderSn, $extra = [])
    {
        $order = TwoPromiseMoneyOrder::where('sn', $orderSn)->findOrEmpty();

        $detail = TwoPromiseMoneyRecord::where('user_id', $order->user_id)->find();

        if (!$detail) {
            $detail = TwoPromiseMoneyRecord::create([
                'user_id' => $order->user_id,
                'money' => $order->order_amount,
            ]);
        } else {
            $detail->money = $detail->money + $order->order_amount;
            $detail->save();
        }

        //更新订单状态
        TwoPromiseMoneyOrder::update([
            'pay_status' =>1,
            'pay_time' => time(),
            'order_status' => 3,
        ], ['id' => $order['id']]);

    }

    /**
     * @notes 付费帖成功回调
     * @param $orderSn
     * @param array $extra
     */
    public static function merchant_vip($orderSn, $extra = [])
    {
        $order = MerchantVipOrder::where('sn', $orderSn)->find();

        if (!$order) {
            return;
        }

        $vip = MerchantVipLevel::where('id', $order->vip_level_id)->find();

        if (!$vip) {
            return;
        }

        MerchantVipOrder::update([
            'pay_status' => PayEnum::ISPAID,
            'pay_time' => time(),
            'transaction_id' => $extra['transaction_id'] ?? ''
        ], ['id' => $order['id']]);
    }

    public static function merchant_top($orderSn, $extra = [])
    {
        $order = MerchantTopOrder::where('sn', $orderSn)->find();

        if (!$order) {
            return;
        }

        MerchantTopOrder::update([
            'pay_status' => PayEnum::ISPAID,
            'pay_time' => time(),
            'transaction_id' => $extra['transaction_id'] ?? ''
        ], ['id' => $order['id']]);

        MerchantTopList::create([
            'merchant_id' => $order->merchant_id,
            'expire_time' => $order->days * 86400 + time()
        ]);
    }

    
    /**
     * @notes 搭子付费订单
     * @param $orderSn
     * @param array $extra
     */
    public static function blind_boxe($orderSn, $extra = [])
    {
        $order = \app\common\model\BlindBoxeOrder::where('sn', $orderSn)->findOrEmpty();
        //更新订单状态
        \app\common\model\BlindBoxeOrder::update([
            'pay_status' => PayEnum::ISPAID,
            'pay_time' => time(),
            'transaction_id' => $extra['transaction_id'] ?? ''
        ], ['id' => $order['id']]);

        
        try{
           
            // 2.匹配搭子
            // $order->sex 1=男 2=女
            $math_user = \app\common\model\BlindBoxe::alias('b')
            ->where([
                ['status','=',1],
            ])
            ->leftJoin('user u','b.user_id=u.id')
            ->where([
                ['u.sex','=',$order->sex]
            ])
            ->field('b.*,u.id as u_user_id')
            ->find();

            // 搭子状态改成已匹配
            \app\common\model\BlindBoxe::where('id',$math_user->id)->update([
                'status'=>2
            ]);
            
            // 订单记录已匹配对象
            $order->blind_boxe_id = $math_user->id;
            $order->save();

        }catch(\Exception $e){
            dd($e->getMessage());
        }


    }


    /**
     * @notes 付费群成功回调
     * @param $orderSn
     * @param array $extra
     */
    public static function group($orderSn, $extra = [])
    {
        $order = GroupOrder::where('sn', $orderSn)->findOrEmpty();

         //更新订单状态
        GroupOrder::update([
            'pay_status' => PayEnum::ISPAID,
            'pay_time' => time(),
            'transaction_id' => $extra['transaction_id'] ?? ''
        ], ['id' => $order['id']]);

        // dd($order->group_id);
        // dd("拉入群聊");
        // dd($order->user_id);
        $res = \app\common\model\ChatGroupMember::create([
            'group_id'=>$order->group_id,
            'user_id'=>$order->user_id,
        ]);

    }

    /**
     * @notes 付费推广成功回调
     * @param $orderSn
     * @param array $extra
     */
    public static function pin($orderSn, $extra = [])
    {
        $order = \app\common\model\PinOrder::with('package')
        ->where('sn', $orderSn)->findOrEmpty();

        //更新订单状态
        \app\common\model\PinOrder::update([
            'pay_status' => PayEnum::ISPAID,
            'pay_time' => time(),
            'transaction_id' => $extra['transaction_id'] ?? ''
        ], ['id' => $order['id']]);
        

        // 增加推广记录
        $record = [
            'order_id'=>$order->id,
            'user_id'=>$order->user_id,
            'article_id'=>$order->article_id,
            'start_time'=>time(),
            'end_time'=>time() + $order->package->time,
            'position_id'=>$order->package->position_id
        ];

        \app\common\model\PinRecord::create($record);
        
    }


    /**
     * @notes 付费圈子成功回调
     * @param $orderSn
     * @param array $extra
     */
    public static function circle($orderSn, $extra = [])
    {
        $order = CircleOrder::where('sn', $orderSn)->findOrEmpty();

         //更新订单状态
        CircleOrder::update([
            'pay_status' => PayEnum::ISPAID,
            'pay_time' => time(),
            'transaction_id' => $extra['transaction_id'] ?? ''
        ], ['id' => $order['id']]);

    }

    /**
     * @notes 充值送余额
     * @param $userId
     * @param $giveMoney
     */
    public static function awardMoney($order, $giveMoney)
    {
        // 充值送余额
        $user = User::findOrEmpty($order->user_id);
        $user->user_money = $user->user_money + $giveMoney;
        $user->save();
        // 记录账户流水
        AccountLogLogic::add($order->user_id, AccountLogEnum::BNW_INC_RECHARGE_GIVE, AccountLogEnum::INC, $giveMoney, $order->sn, '充值赠送');
    }



    public static function getOrderInfo($orderId)
    {
        $field = [
            'id',
            'sn',
            'pay_way',
            'delivery_type',
            'goods_price',
            'order_amount',
            'discount_amount',
            'express_price',
            'user_remark',
            'address',
            'selffetch_shop_id',
            'create_time',
        ];
        $order = Order::field($field)->with(['orderGoods' => function($query) {
            $query->field(['goods_num', 'order_id', 'goods_price', 'goods_snap']);
        }])
            ->append(['delivery_address', 'pay_way_desc', 'delivery_type_desc'])
            ->findOrEmpty($orderId);
        if ($order->isEmpty()) {
            throw new \Exception("订单不存在");
        }

        return $order->toArray();
    }

    /**
     * 圈子创建支付订单
     */
    public static function create_circle($orderSn, $extra = [])
    {
        $order = \app\common\model\CircleCreateOrder::where('sn', $orderSn)->findOrEmpty();
        Db::startTrans();
        try{

            // 圈子状态改为已支付
            \app\common\model\Circle::update([
                'is_pay' => 1,
            ], ['id' => $order['circle_id']]);

            //更新订单状态
            \app\common\model\CircleCreateOrder::update([
                'pay_status' => PayEnum::ISPAID,
                'pay_time' => time(),
                'transaction_id' => $extra['transaction_id'] ?? ''
            ], ['id' => $order['id']]);

            Db::commit();
       }catch(\Exception $e){
            Db::rollback();
            throw new \Exception(message: $e->getMessage());
       }

    }

    // 商家商品订单
    public static function merchant_goods($orderSn, $extra = [])
    {
        $order = \app\common\model\MerchantGoodsOrder::where('sn', $orderSn)->findOrEmpty();

        //更新订单状态
        \app\common\model\MerchantGoodsOrder::update([
            'pay_status' => PayEnum::ISPAID,
            'pay_time' => time(),
            'transaction_id' => $extra['transaction_id'] ?? ''
        ], ['id' => $order['id']]);

    }

    // 商家团购商品订单
    public static function merchant_goods_package($orderSn, $extra = [])
    {
        $order = \app\common\model\MerchantGoodsPackageOrder::where('sn', $orderSn)->findOrEmpty();

        //更新订单状态
        \app\common\model\MerchantGoodsPackageOrder::update([
            'pay_status' => PayEnum::ISPAID,
            'pay_time' => time(),
            'transaction_id' => $extra['transaction_id'] ?? ''
        ], ['id' => $order['id']]);

    } 

    /**
     * 搭子订单
     */
    public static function partner($orderSn, $extra = [])
    {
        $order = \app\common\model\PartnerOrder::where('sn', $orderSn)->findOrEmpty();
        Db::startTrans();
        try{
            
            // 记录搭子参与者成员
            $member = [
                'partner_id'=>$order->partner_id,
                'user_id'=>$order->user_id,
                'create_time'=>time(),
            ];
            \app\common\model\PartnerMember::create($member);

            //更新订单状态
            \app\common\model\PartnerOrder::update([
                'pay_status' => PayEnum::ISPAID,
                'pay_time' => time(),
                'transaction_id' => $extra['transaction_id'] ?? ''
            ], ['id' => $order['id']]);

            Db::commit();
       }catch(\Exception $e){
            Db::rollback();
            throw new \Exception(message: $e->getMessage());
       }

    }

}
