<?php

namespace App\Modules\Subscribe\Services;

use App\Modules\Subscribe\Models\Order;
use DB;

class OrderService
{

	static function getByTradeNo($trade_no)
	{
		return Order::where('trade_no',$trade_no)->first();
	}

    static function getById($order_id)
    {
        return Order::where('id',$order_id)->first();
    }

	public static  function  getOrderList($uid,$page_size){
	    return Order::select('id','price','created_at','status','trade_no')->where('uid',$uid)->where('from_type','!=','order_add')->orderBy('created_at','desc')->paginate($page_size);
    }

    public static function getSuccessOrderList($uid,$page_size){
        return Order::select('id','price','created_at','status','trade_no','order_type')->where('uid',$uid)->where('status','PAID')->where('from_type','!=','order_add')->orderBy('created_at','desc')->paginate($page_size);
    }

    public static function isUserHasOrder($uid){
        return Order::where('uid',$uid)->where('from_type','!=','order_add')->count();
    }

    /**
     * 获取充值订单
     * @param $uid
     * @return mixed
     */
    public static function totalChargeList($uid){
        return Order::join('products','orders.product_id','=','products.id')
            ->select('products.price','products.given')
            ->where('orders.order_type','RECHARGE')
            ->where('orders.status','PAID')
            ->where('orders.uid',$uid)
            ->get();
    }

    /**
     * 订单生成
     */
    static function generate($data)
    {
        //订单号生成
        $data['trade_no'] = $data['product_id'].date("YmdHis").hexdec(uniqid());
        return Order::create($data);
    }


    static function save_order($data){
        $insert_data = array();
        $insert_data['uid'] = $data['uid'];
        $insert_data['price'] = $data['price'];
        $insert_data['status'] = $data['status'];
        $insert_data['pay_type'] = $data['pay_type'];
        $insert_data['product_id'] = $data['product_id'];
        $insert_data['distribution_channel_id'] = $data['distribution_channel_id'];
        $insert_data['trade_no'] = $data['trade_no'];
        $insert_data['pay_merchant_source'] = $data['pay_merchant_source'];
        $insert_data['pay_merchant_id'] = $data['pay_merchant_id'];
        $insert_data['order_type'] = $data['order_type'];
        $insert_data['transaction_id'] = $data['transaction_id'];
        $insert_data['from_bid'] = $data['from_bid'];
        $insert_data['pay_end_at'] = $data['pay_end_at'];
        $insert_data['create_ip'] = $data['create_ip'];
        $insert_data['send_order_id'] = $data['send_order_id'];
        $insert_data['send_order_name'] = isset($data['send_order_name'])?$data['send_order_name']:'';
        $insert_data['from_type'] = $data['from_type'];
        $insert_data['activity_id'] = $data['activity_id'];
        $insert_data['inner_send_order_id'] = isset($data['inner_send_order_id'])?$data['inner_send_order_id']:'';
        return $result = Order::save_order($insert_data);
    }

    /**
     * 获取所有分销渠道
     * @return mixed
     */
    static function getAllChannelId(){
        return Order::select('distribution_channel_id')->distinct()->get()->toArray();
    }

    /**
     * 获取渠道下最近20条订单记录
     * @param $distribution_channel_id
     * @param int $num
     */
    static function getLatestOrderByChannleId($source,$num=20){
        return Order::select('orders.id','orders.status','orders.created_at')
            ->orderBy('orders.created_at','desc')
            ->where('orders.pay_merchant_source',$source)
            ->where('orders.created_at','<=',date('Y-m-d H:i:s',time()-10))
            ->limit($num)
            ->get();
    }

    /**
     * 获取最后一条订单,用于订单预警
     * @return mixed
     */
    public static function getLastOrder(){
        return Order::orderBy('created_at','desc')->first();
    }

    public static function userIsParticipateActivity($uid,$activity_id){
        return Order::where('uid',$uid)->where('activity_id',$activity_id)->where('status','PAID')->count();
    }

    /**
     * 渠道公众号重充值统计
     */
    public static function OfficialAccountOrderStat($distribution_channel_id,$start_time,$end_time,$page_size=15){
        return Order::OfficialAccountOrderStat($distribution_channel_id,$start_time,$end_time,$page_size);
    }

    /**
     * 渠道公众号重充值统计
     */
    public static function OfficialAccountOrderSum($distribution_channel_id,$start_time,$end_time,$appid){
        return Order::OfficialAccountOrderSum($distribution_channel_id,$start_time,$end_time,$appid);
    }

    /**
     * 根据派单获取充值总量
     * @param int $send_order_id
     * @param int $distribution_channel_id
     * @return float
     */
    public static function getSumBySendOrderId(int $send_order_id,int $distribution_channel_id):float {
        return (float)Order::where('send_order_id',$send_order_id)
            //->where('distribution_channel_id',$distribution_channel_id)
            ->whereIn('order_type',['RECHARGE','YEAR'])
            ->where('status','PAID')->sum('price');
    }

    /**
     * @param int $send_order_id
     * @return array
     */
    public static function getSuccessRate(int $send_order_id):array {
        $sql_format = "select 
count(*) as total,count(case when `status`='PAID' then `status` else null end) as success 
from orders 
WHERE  send_order_id = %s and order_type= 'RECHARGE' ";
        $sql = sprintf($sql_format,$send_order_id);
        $res = DB::select($sql);
        $total = $res[0]->total;
        $success = $res[0]->success;
        return compact('total','success');
    }
    /**
     * 判断用户首充
     */
    public static function judgeUserFirstRecharge($uid) {
        $user_recharge = Order::where([
            ['status','=','PAID'],
            ['uid','=',$uid]
        ])->first();
        if(!$user_recharge){
            return true;
        }
        return false;
    }

    /**
     * @param $inner_send_order_id
     */
    public static function getInnerSendOrderStats($inner_send_order_id){
        return Order::where('inner_send_order_id',$inner_send_order_id)
            ->select(
                DB::raw('count(distinct uid) as pay_user_num'),
                DB::raw('sum(price) as charge_amount')
            )
            ->where('status','PAID')
            ->first();
    }

    public static function getUserOrderByProductId($uid,$product_id){
        return Order::where('uid',$uid)->where('product_id',$product_id)->where('status','PAID')->first();
    }

    /**
     * 是否是付费用户
     * @param $uid
     * @return bool
     */
    public static function isPaidUser($uid){
        if(empty($uid)){
            return false;
        }
        $result = Order::select('id')->where('uid',$uid)->where('status','PAID')->first();
        if($result && $result->id){
            return true;
        }
        return false;
    }
}