<?php

namespace App\Modules\Xcx\Models;

use DB;
use Illuminate\Database\Eloquent\Model;

class XcxOrder extends Model
{
    protected $table = 'xcx_orders';

    protected $fillable = [
        'distribution_channel_id',
        'uid',
        'product_id',
        'price',
        'status',
        'pay_type',
        'trade_no',
        'pay_merchant_source',
        'pay_merchant_id',
        'transaction_id',
        'pay_end_at',
        'create_ip',
        'send_order_id',
        'send_order_name',
        'order_type',
        'from_bid',
        'from_type',
        'activity_id'
    ];

    public static function getTotalChargeAmount($sendOrderId, $distribution_channel_id)
    {
        $totalChargeAmount = self::where(['distribution_channel_id' => $distribution_channel_id, 'send_order_id' => $sendOrderId, 'status' => 'PAID'])
            ->select(DB::raw(" sum(price) as totalChargeAmount "))->first();
        return isset($totalChargeAmount->totalChargeAmount) ? $totalChargeAmount->totalChargeAmount : '0';
    }

    public static function getTotalOrderNum($sendOrderId, $distribution_channel_id)
    {
        return self::where(['distribution_channel_id' => $distribution_channel_id, 'send_order_id' => $sendOrderId])->count();
    }

    public static function getSucOrderNum($sendOrderId, $distribution_channel_id)
    {
        return self::where(['distribution_channel_id' => $distribution_channel_id, 'send_order_id' => $sendOrderId, 'status' => 'PAID'])->count();
    }

    static function save_order($data)
    {

        return self::firstOrCreate($data);
    }

    public static function getDistributionTodayChargeAmount($distribution_channel_id)
    {
        $today = date('Y-m-d');
        $totalChargeAmount = self::where(['distribution_channel_id' => $distribution_channel_id, 'status' => 'PAID'])
            ->where('created_at', '>=', $today)
            ->select(DB::raw(" sum(price) as totalChargeAmount "))->first();
        return isset($totalChargeAmount->totalChargeAmount) ? $totalChargeAmount->totalChargeAmount : '0';
    }

    public static function getDistributionTotalChargeAmount($distribution_channel_id)
    {
        $today = date('Y-m-d');
        $totalChargeAmount = self::where(['distribution_channel_id' => $distribution_channel_id, 'status' => 'PAID'])
            ->select(DB::raw(" sum(price) as totalChargeAmount "))->first();
        return isset($totalChargeAmount->totalChargeAmount) ? $totalChargeAmount->totalChargeAmount : '0';
    }
}
