<?php

namespace app\common\logic;

use app\common\enum\OrderEnum;
use app\common\enum\PayEnum;
use app\common\enum\user\UserShipEnum;
use app\common\model\dict\DictType;
use app\common\model\finance\PayNotifyLog;
use app\common\model\pay\PayNotify;
use app\common\model\store_finance_flow\StoreFinanceFlow;
use app\common\model\store_order\StoreOrder;
use app\common\model\system_store\SystemStore;
use app\common\model\user\User;
use app\common\model\user\UserRecharge;
use app\common\model\user\UserShip;
use app\common\service\PushService;
use support\Log;
use think\facade\Db;
use Webman\RedisQueue\Redis;

/**
 * 支付成功后处理订单状态
 * Class PayNotifyLogic
 * @package app\api\logic
 */
class PayNotifyLogic extends BaseLogic
{

    public static function handle($action, $orderSn, $extra = [])
    {
        Db::startTrans();
        try {
            if ($action != 'cash_pay' && $action != 'balancePay') {
                $payNotifyLogLogic = new PayNotifyLogLogic();
                if($action == 'refund'){
                    $payNotifyLogLogic->insert($action, $extra,PayNotifyLog::TYPE_REFUND);
                }else{
                    $payNotifyLogLogic->insert($action, $extra);
                }

            }
            self::$action($orderSn, $extra);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('支付回调处理失败' . $e->getMessage().',lien:'.$e->getLine().',file:'.$e->getFile());
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 余额支付
     * @param $orderSn
     * @param $extra
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
   public static function balancePay($orderSn, $extra = [])
    {
        $order = StoreOrder::where('order_id', $orderSn)->findOrEmpty();
        $user = User::where('id', $order['uid'])->find();
        if ($user['now_money'] < $order['pay_price']) {
            throw new \Exception('余额不足');
        }
        $order->money = $order['pay_price'];
        $order->paid = 1;
        $order->pay_time = time();
        if (!$order->save()) {
            throw new \Exception('订单保存出错');
        }
        $capitalFlowDao = new CapitalFlowLogic($user);
        $capitalFlowDao->userExpense('user_order_pay', 'order', $order['id'], $order['pay_price']);
        self::afterPay($order);
    }

    /**
     * @notes 微信通用回调
     * @param $orderSn
     * @param array $extra
     * @date 2023/2/27 15:28
     */
    public static function wechat_common($orderSn, $extra = [])
    {
        $order = StoreOrder::where('order_id', $orderSn)->findOrEmpty();

        if ($order->isEmpty() || $order->paid == PayEnum::ISPAID) {
            return true;
        }
        if ($order->pay_type != 10) {
            $order->pay_price = bcdiv($extra['amount']['payer_total'], 100, 2);
            $order->paid = 1;
            $order->pay_time = time();
            $order->status = 1;
            $order->save();
        } else {
            $extra['transaction_id'] = time();
        }
        $user = User::where('id', $order['uid'])->find();
        if ($order->pay_type == 9) {
            $order->status = 2;
        }else{
            $capitalFlowDao = new CapitalFlowLogic($user);
            //微信支付和用户余额无关
            $capitalFlowDao->userExpense('user_order_pay', 'order', $order['id'], $order->pay_price,'',1);
        }
        self::afterPay($order,$extra['transaction_id']);

        //活动期间消费
        $check = DictType::where('type','activities')->find();
        if(isset($check) && $check['status'] == 1 && $user['user_ship'] == 0){
            self::dealChange($order['uid']);
        }

        if ($order->pay_type == 9) {
            $extra['create_time'] = $order['create_time'];
            PushService::push('store_merchant_' . $order['store_id'], $order['store_id'], ['type' => 'cash_register', 'msg' => '您有一笔订单已支付', 'data' => $extra]);
        } else {
            PushService::push('store_merchant_' . $order['store_id'], $order['store_id'], ['type' => 'store_merchant', 'msg' => '您有一笔新的订单']);
            Redis::send('push-platform-print', ['id' => $order['id']], 60);
            //            Db::name('order_middle')->insert(['c_order_id' => $order['id']]);
        }
        if (!empty($extra['payer']['openid']) && $order->pay_type != 9) {
            Redis::send('push-delivery', ['order_sn' => $order['order_id'], 'openid' => $extra['payer']['openid']], 5);
        }
        return true;
    }

    //退款
    public static function refund($orderSn, $extra = [])
    {
        //更新状态
        $order = StoreOrder::where('order_id',$orderSn)->findOrEmpty();
        if ($order->isEmpty() || $order->status == OrderEnum::REFUND_PAY) {
            return true;
        }
        $order->status = OrderEnum::REFUND_PAY;
        $order->refund_status = OrderEnum::REFUND_STATUS_FINISH;
        $order->refund_price = bcdiv($extra['amount']['refund'], 100, 2);
        $order->refund_reason_time = time();
        $order->refund_num +=  1;
        $order->save();

//        self::afterPay($order,$extra['transaction_id']);
    }

    public static function recharge($orderSn, $extra = [])
    {
            $order = UserRecharge::where('order_id', $orderSn)->findOrEmpty();
            if ($order->isEmpty() || $order->paid == PayEnum::ISPAID) {
                return true;
            }
            $price =  bcdiv($extra['amount']['payer_total'], 100, 2);
            $order->price = $price;
            $order->paid = 1;
            $order->pay_time = time();
            $order->save();
            $uid = $order->uid;
            $user = User::where('id',$uid)->findOrEmpty();
            if ($user->isEmpty()) {
                return true;
            }
            bcscale(2);
            $user->now_money = bcadd($user->now_money, $price, 2);
            $user->total_recharge_amount = bcadd($user->total_recharge_amount, $price, 2);
            $user->save();
            //用户的财务add
            $capitalFlowDao = new CapitalFlowLogic($user);
            $capitalFlowDao->userIncome('user_balance_recharge', 'user_recharge', $order['id'], $price);
            //更新等级
            self::dealLevel($uid,$user->total_recharge_amount);
            return true;

    }

    /**
     * 现金支付
     */
    public static function cash_pay($orderSn)
    {
        $order = StoreOrder::where('order_id', $orderSn)->findOrEmpty();

        if ($order->isEmpty() || $order->paid == PayEnum::ISPAID) {
            return true;
        }
        $order->paid = 1;
        $order->pay_time = time();
        $order->status = 2;
        if (!$order->save()) {
            throw new \Exception('订单保存出错');
        }
        $cashFlowLogic = new CashFlowLogic();
        $cashFlowLogic->insert($order['store_id'], $order['pay_price']);
    }

    /**
     * @notes 阿里回调
     * @param $orderSn
     * @param array $extra
     * @author 段誉
     * @date 2023/2/27 15:28
     */
    public static function alipay_cashier($orderSn, $extra = [])
    {
        $order = StoreOrder::where('order_id', $orderSn)->findOrEmpty();

        if ($order->isEmpty() || $order->paid == PayEnum::ISPAID) {
            return true;
        }
        if ($order->pay_type != 10) {
            $order->money = $extra['buyer_pay_amount'];
            $order->paid = 1;
            $order->pay_time = time();
            $order->status = 1;
            $order->save();
        } else {
            $extra['transaction_id'] = time();
        }
        if ($order->pay_type == 9) {
            $order->status = 2;
        }
        self::afterPay($order);

        if ($order->pay_type == 9) {
            $extra['create_time'] = $order['create_time'];
            PushService::push('store_merchant_' . $order['store_id'], $order['store_id'], ['type' => 'cash_register', 'msg' => '您有一笔订单已支付', 'data' => $extra]);
        } else {
            PushService::push('store_merchant_' . $order['store_id'], $order['store_id'], ['type' => 'store_merchant', 'msg' => '您有一笔新的订单']);
            Redis::send('push-platform-print', ['id' => $order['id']], 60);
        }
        return true;
    }

    /**
     * 支付后逻辑
     * @param $order
     * @return void
     */
    public static function afterPay($order,$transaction_id=0)
    {
        $financeLogic = new StoreFinanceFlowLogic();
        $financeLogic->order = $order;
        $financeLogic->user = ['uid' => $order['uid']];
        if ($order->pay_type != 9 || $order->pay_type != 10) {
            $financeLogic->in($transaction_id, $order['pay_price'], OrderEnum::USER_ORDER_PAY);  //用户单入账
            //商户应该获得的钱 每个商品的price-ot_price 利润
            if ($order->profit !== "0.00") {
                //手续费
                $fees = bcdiv(bcmul($order['pay_price'], '0.02', 2), 1, 2);
                $financeLogic->in($transaction_id, $fees, OrderEnum::ORDER_COMMITION, $order['store_id']);  //手续费入账

                $financeLogic->out($transaction_id, $order['profit'], OrderEnum::MERCHANT_ORDER_OBTAINS, $order['store_id'], $order['staff_id'], 0);//商户获得的
                //冻结金额的
                $frozen = bcsub($order->profit, $fees, 2);
                //缴纳齐全了就加商户没有就加到平台
                $money_limt = SystemStore::where('id', $order['store_id'])->field('paid_deposit,security_deposit')->find();
                $deposit = bcsub($money_limt['security_deposit'], $money_limt['paid_deposit'], 2);//剩余额度
                if ($deposit > 0 && $frozen > 0) {
                    $amount = min($deposit, $frozen);
                    $financeLogic->in($transaction_id, $amount, OrderEnum::ORDER_MARGIN, $order['store_id'], $order['staff_id']);
                }

            }
            $financeLogic->save();
        }
    }

    //等级处理
    public static function dealLevel($uid,$total_money)
    {
        $userShip = UserShip::where('limit', '<=', $total_money)
            ->field('id,title,limit')
            ->order('limit', 'desc')
            ->find();
        $info = User::where('id',$uid)->findOrEmpty();
        if($info && $userShip){
            if ($info->user_ship != $userShip['id']) {
                $info->user_ship = $userShip['id'];
                $info->save();
            }
        }
        return true;

    }

    //处理活动期间直接改用户的等级
    public static function dealChange($uid)
    {
        User::where('id',$uid)->update(['user_ship'=>UserShipEnum::LEVEL_ONE]);
        return true;
    }


    /**
     * 回调日志
     * @param $order
     * @param $extra
     * @return void
     */
    public static function notifyLog($order,$extra)
    {
        $data = [
            'pay_type'=>'wechat',
            'type'=>OrderEnum::PAY,
            'amount'=>$extra['amount']['payer_total'],//分
            'order_sn'=>$order,
            'out_trade_no'=>$extra['transaction_id'],
            'attach'=>$extra['attach'],
            'create_time'=>date('Y-m-d H:i:s',time()),
        ];
        PayNotify::create($data);
    }

}