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



namespace app\common\service\pay;


use app\common\enum\AccountLogEnum;
use app\common\enum\AfterSaleEnum;
use app\common\enum\AfterSaleLogEnum;
use app\common\enum\NoticeEnum;
use app\common\enum\OrderEnum;
use app\common\enum\PayEnum;
use app\common\logic\AccountLogLogic;
use app\common\model\AfterSale;
use app\common\model\User;
use app\common\service\after_sale\AfterSaleService;


/**
 * 余额支付
 * Class BalancePayService
 * @package app\common\server
 */
class BalancePayService extends BasePayService
{

    /**
     * @notes 余额支付
     * @param $from //订单类型 (order-普通商品订单, recharge-充值订单, ....)
     * @param $order //订单信息
     * @return array|false
     */
    public function pay($from, $order)
    {
        \think\facade\Db::startTrans();
        try {
            $user = User::findOrEmpty($order['user_id']);
            if ($user->isEmpty() || $user['user_money'] < $order['order_amount']) {
                throw new \Exception('余额不足');
            }

            //扣除余额
            // User::update([
            //     'user_money' => ['dec', $order['order_amount']]
            // ], ['id' => $order['user_id']]);
            $user->dec('user_money',$order['order_amount'])->save();
  
            
            //余额流水
            AccountLogLogic::add(
                $user->id,
                AccountLogEnum::BNW_DEC_ORDER,
                AccountLogEnum::DEC,
                $order['order_amount'],
                $order['sn'],
                $from,
            );

            if($from == 'circle'){
                // 圈主收益分佣
                $circle_profit_pct = \app\common\service\ConfigService::get('circle', 'circle_profit_pct',0);
                if($circle_profit_pct > 0){
                    $order['order_amount'] = $order['order_amount'] * $circle_profit_pct/100;
                }
            };

            if($from == 'group'){
                // 群主收益分佣
                $group_profit_pct = \app\common\service\ConfigService::get('chat', 'group_profit_pct',0);
                if($group_profit_pct > 0){
                    $order['order_amount'] = $order['order_amount'] * $group_profit_pct/100;
                }
            };

            //卖家增加收入
            $sell_user = User::find($order['sell_user_id']);
            if($sell_user){
                // 有卖家
                $sell_user->inc('user_earnings',$order['order_amount'])->save();
                // 卖家收入变动流水;
                AccountLogLogic::add(
                    $order['sell_user_id'],
                    AccountLogEnum::BW_INC_SELL,
                    AccountLogEnum::INC,
                    $order['order_amount'],
                    $order['sn'],
                    $from
                );
            }
            
            \think\facade\Db::commit();
            return [
                'pay_way' => PayEnum::BALANCE_PAY
            ];
        } catch (\Exception $e) {
            \think\facade\Db::rollback();
            $this->setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 余额退款
     * @param $order
     * @param $refundAmount
     */
    public function refund($order, $refundAmount,$afterSaleId,$type)
    {
        //返回余额
        User::where('id', $order['user_id'])->inc('user_money', $refundAmount)->save();

        $modelClass = AfterSale::class;

        if ($type == 'two') {
            $modelClass = \app\common\model\TwoAfterSale::class;
        }

        //余额流水
        $afterSale = ($modelClass)::findOrEmpty($afterSaleId);
        AccountLogLogic::add(
            $order['user_id'],
            AccountLogEnum::BNW_INC_AFTER_SALE,
            AccountLogEnum::INC,
            $refundAmount,
            $afterSale->sn
        );

        // 更新售后状态
        $afterSale->status = AfterSaleEnum::STATUS_SUCCESS;
        $afterSale->sub_status = AfterSaleEnum::SUB_STATUS_SELLER_REFUND_SUCCESS;
        $afterSale->refund_status = AfterSaleEnum::FULL_REFUND;
        $afterSale->save();

        AfterSaleService::createAfterLog($afterSale->id, '系统已完成退款', 0, AfterSaleLogEnum::ROLE_SYS);


        // 消息通知
        event('Notice', [
            'scene_id' => NoticeEnum::REFUND_SUCCESS_NOTICE,
            'params' => [
                'user_id' => $afterSale->user_id,
                'order_sn' => $order['sn'],
                'after_sale_sn' => $afterSale->sn,
                'refund_type' => AfterSaleEnum::getRefundTypeDesc($afterSale->refund_type),
                'refund_total_amount' => $afterSale->refund_total_amount,
                'refund_time' => date('Y-m-d H:i:s'),
            ]
        ]);
    }


}