<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\common\logic;

use app\common\enum\PayEnum;
use app\common\enum\user\AccountLogEnum;
use app\common\enum\WorkEnum;
use app\common\model\recharge\OrderGoods;
use app\common\model\recharge\RechargeOrder;
use app\common\model\shops\ShopOrders;
use app\common\model\user\User;
use app\common\model\works\ServiceWork;
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) {
            Db::rollback();
            Log::write(implode('-', [
                __CLASS__,
                __FUNCTION__,
                $e->getFile(),
                $e->getLine(),
                $e->getMessage()
            ]));
            self::setError($e->getMessage());
            return $e->getMessage();
        }
    }


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

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

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

    /**
     * @notes 服务回调
     * @param $orderSn
     * @param array $extra
     */
    public static function goods($orderSn, array $extra = [])
    {
        $order = RechargeOrder::where('sn', $orderSn)->findOrEmpty();
        Log::write($order->toArray(),JSON_UNESCAPED_UNICODE);
        if(!$order->isEmpty()){
            // 更新充值订单状态
            $order->transaction_id = $extra['transaction_id'] ?? '';
            $order->pay_status = PayEnum::ISPAID;
            $order->pay_time = time();
            $order->paid_amount = $order->order_amount;

            //判断是否是一口价预支付订单，支付成功后生成尾款订单
            $order_goods = OrderGoods::where('sn',$order->sn)->findOrEmpty();
            if(!$order_goods->isEmpty() and $order_goods->goods_payment_type == 3 and bcsub($order_goods->base_service_fee,$order_goods->service_fee,2)>=0){
                //新增待支付尾款
                $order_data = [
                    'order_type'=>$order['order_type'],
                    'sn'=>generate_sn(\app\common\model\orders\RechargeOrder::class, 'sn'),
                    'work_id'=>$order['work_id'],
                    'user_id'=>$order['user_id'],
                    'payment_type'=>2,
                    'order_total'=>bcsub($order_goods->base_service_fee,$order_goods->service_fee,2),
                    'order_amount'=>bcsub($order_goods->base_service_fee,$order_goods->service_fee,2),
                    'order_terminal'=>$order['order_terminal']
                ];
                RechargeOrder::create($order_data);
            }

            $order->save();
            $work = ServiceWork::findOrEmpty($order->work_id);

            if(!$work->isEmpty()){
                $work->work_pay_status = WorkEnum::IS_PAY_STATUS;

                $orders = \app\common\model\orders\RechargeOrder::where(['work_id'=>$order->work_id])->select()->toArray();

                $order_total = 0;
                $order_amount = 0;
                foreach ($orders as $k=>$v){
                    $order_total += $v['order_total'];
                    $order_amount += $v['order_amount'];
                }
                $work->work_total = $order_total;
                $work->work_amount = $order_amount;
                if($work->work_status != 0 and $work->work_status != 1 and $work->work_status != 2){
                    $work->work_status = 7;
                    $work->user_confirm_status = 5;
                    $work->service_status = 3;
                }
                $work->work_pay_status = 1;
                $work->save();
            }
        }
    }

    public static function shop_goods($orderSn, array $extra = [])
    {
        $order = ShopOrders::where('sn', $orderSn)->findOrEmpty();
        // 更新充值订单状态
        $order->transaction_id = $extra['transaction_id'] ?? '';
        $order->pay_status = PayEnum::ISPAID;
        $order->pay_time = time();
        $order->shop_order_type = 2;
        $order->save();
    }


}
