<?php
/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2020/9/30
 * Time: 17:09
 */

namespace App\Console\Commands\Wechat;

use DB;
use Log;
use Redis;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Console\Command;

class ReportRetry extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'Wechat:ReportRetry  {--start_time=} {--end_time=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '异常从新上报';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    private $user_action_set_id = [];

    private $assess_token = [];

    private $error_msg;

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $start_time = $this->option('start_time');
        if(!$start_time){
            $start_time = date('Y-m-d 00:00:00');
        }
        $end_time = $this->option('end_time');
        if(!$end_time){
            $end_time = date('Y-m-d 23:59:59');
        }
        $this->startMp($start_time,$end_time);
    }

    //mp重试
    private function startMp($start_time,$end_time){
        $error_record = DB::table('wechat_advertise_report_record')
            ->where('created_at','>=',$start_time)
            ->where('created_at','<=',$end_time)
            ->where('result_status','FAIL')
            ->select('id','user_action_set_id','url','action_time','action_type','openid','appid','product_id',
                'product_name','bid','value','source','claim_type','object')
            ->get();
        if(!$error_record) return ;
        $client = new Client();
        foreach ($error_record as $item){
            $report_info = DB::table('wechat_advertise_report_record')
                ->where('action_type',$item->action_type)
                ->where('product_id',$item->product_id)
                ->where('result_status','SUCCESS')->count();
            if($report_info) {
                continue;
            }
            $request_data = [
                'actions'=>[
                    [
                        'user_action_set_id'=>$item->user_action_set_id,
                        'url'=>$item->url,
                        'action_time'=>$item->action_time,
                        'action_type'=>$item->action_type,
                        'user_id'=>[
                            'wechat_app_id'=>$item->appid,
                            'wechat_openid'=>$item->openid
                        ],
                        'action_param'=>[
                            'object'=>$item->object,
                            'product_name'=>$item->product_name,
                            'product_id'=>$item->bid,
                            'source'=>$item->source,
                            'wechat_app_id'=>'',
                            'claim_type'=>$item->claim_type,
                            'value'=>$item->value
                        ]
                    ]
                ]
            ];
            $token = $this->getAccessToken($item->appid);
            $result = $this->sendReport($client,$request_data,$token);
            if($result && $result['result_status'] == 'SUCCESS'){
                $result['updated_at'] = date('Y-m-d H:i:s');
                DB::table('wechat_advertise_report_record')->where('id',$item->id)->update($result);

                DB::connection('api_mysql')->table('distribution_channel_weixin_report_orders')->where('order_id',$item->product_id)
                    ->where('type','WECHAT')
                    ->update(['report_status'=>1]);
            }
        }

    }


    private function sendReport(Client $client,$request_data,$token){
        if(!$token) return '';
        $url = 'https://api.weixin.qq.com/marketing/user_actions/add?version=v1.0&access_token='.$token;
        $data = [];
        try{
            $result = $client->request('post',$url,[
                'headers'=>['Content-Type'=>'application/json'],
                'body'=>\GuzzleHttp\json_encode($request_data)
            ])->getBody()->getContents();
            Log::info('user_actions/add result is: '.$result);
            $result_array = \GuzzleHttp\json_decode($result,1);
            if(isset($result_array['errcode']) && $result_array['errcode'] == 0){
                $data['result_status'] = 'SUCCESS';
                $data['result_msg'] = $result_array['errcode'];
                $data['result'] = $result;
            }else{
                $data['result_status'] = 'FAIL';
                $data['result_msg'] = isset($result_array['errcode'])?$result_array['errcode']:'unknown';
                $data['result'] = $result;
            }
            return $data;
        }catch (Exception $e){
            Log::error($e);
        }
        return $data;
    }


    private function getAccessToken($appid){
        if(isset($this->assess_token[$appid])){
            return $this->assess_token[$appid];
        }
        $access_token = Redis::get('Wechat:access_token:appid:'.$appid);
        if($access_token){
            $this->assess_token[$appid] = $access_token;
            return $this->assess_token[$appid];
        }

        $this->error_msg = $appid.',access_token fail';
        return '';
    }

}