<?php

/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2020/5/5
 * Time: 11:29
 */

namespace App\Jobs;

use App\Modules\Subscribe\Services\OrderService;
use GuzzleHttp\Client;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Redis;
use DB;

class AsyncOrderStats implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    const SUCCESS = 'success';

    private $orderId;
    private $order_info = null;

    private $uid = 0;

    public function __construct(int $order_id)
    {
        $this->orderId = $order_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $this->init();
        //activity 活动统计
        $this->activityStats();
        //$this->saveActivityOrder();
        //图书充值统计
        $this->bookChargeStats();
        //订单上报给渠道
        $this->reportToChannel();
    }

    private function init()
    {
        $this->order_info = OrderService::getById($this->orderId);
        $this->uid = $this->order_info->uid;
    }


    private function activityStats()
    {
        $item = $this->order_info;
        if ($item->status != 'PAID') return;
        if (!$item->activity_id) return;
        $day = date('Y-m-d', strtotime($item->created_at));
        $exist = DB::table('activity_statistic_all')
            ->where('activity_id', $item->activity_id)
            ->where('day', $day)
            ->select('id', 'amount')
            ->where('distribution_channel_id', $item->distribution_channel_id)->first();
        if ($exist) {
            DB::table('activity_statistic_all')->where('id', $exist->id)->update(
                [
                    'amount' => $exist->amount + $item->price * 100,
                    'updated_at' => date('Y-m-d H:i:s')
                ]
            );
            return;
        }
        $pv = 0;
        $uv = 0;
        DB::table('activity_statistic_all')->insert([
            'activity_id' => $item->activity_id, 'day' => $day, 'distribution_channel_id' => $item->distribution_channel_id,
            'amount' => $item->price * 100, 'pv' => $pv, 'uv' => $uv, 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')
        ]);
    }


    private function bookChargeStats(){
        $bid = $this->order_info->from_bid;
        if(!$bid) return ;
        $day = date('Y-m-d', strtotime($this->order_info->created_at));
        $price = $this->order_info->price * 100;
        Redis::hincrby('book:charge:stats:'.$day, $bid, $price);
    }

   private function reportToChannel(){
       $link = $this->getReportUrl($this->distribution_channel_id);
       if(!$link) return ;
       $uid = $this->uid;
       $distribution_channel_id = $this->order_info->distribution_channel_id;
       $price = $this->order_info->price;
       $order_created_at = $this->order_info->created_at->format('Y-m-d H:i:s');
       $client = new Client(['timeout'=>3.0]);
       try{
           $result = $client->request('post',$link,['form_params'=>[
               'uid'=>$uid,
               'distribution_channel_id'=>$distribution_channel_id,
               'price'=>$price,
               'order_created_at'=>$order_created_at,
           ]])->getBody()->getContents();
           if($result && str_contains(strtolower($result),self::SUCCESS)){
               return ;
           }
           $error = 'result error ,'.$result;
       }catch (\Exception $e){
           $error = 'exception,'.$e->getMessage();
       }
       DB::table('report_to_channel_orders')->insert([
           'uid'=>$uid,
           'distribution_channel_id'=>$distribution_channel_id,
           'price'=>$price,
           'order_created_at'=>$order_created_at,
           'report_status'=>0,
           'error_msg'=>$error,
           'created_at'=>date('Y-m-d H:i:s'),
           'updated_at'=>date('Y-m-d H:i:s'),
       ]);
   }

    private function getReportUrl($distribution_channel_id){
        return '';
    }
}
