<?php


namespace App\Console\Commands\Wechat;

use GuzzleHttp\Client;
use Illuminate\Console\Command;
use App\Http\Controllers\WechatController;
use Exception;
use Log;
use DB;
use Redis;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command 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()
    {
        $this->start();
    }
    private function start(){
        $client = new Client();
        $repair_list = Redis::LRANGE('Wechat:AdReport',0,-1);
        if($repair_list){
            $this->repair = true;
            foreach ($repair_list as $repair_item){
                $item = json_decode($repair_item);
                $time = date('Y-m-d H:i:s');
                if($item->action_type == 'ALL'){
                    $this->reportOne($client,$item->id,$item->order_id,$item->appid,$item->openid,$item->price,$time,$item->report_type,'COMPLETE_ORDER',$item->type);
                    $this->reportOne($client,$item->id,$item->order_id,$item->appid,$item->openid,$item->price,$time,$item->report_type,'PURCHASE',$item->type);
                }else{
                    $this->reportOne($client,$item->id,$item->order_id,$item->appid,$item->openid,$item->price,$time,$item->report_type,$item->action_type,$item->type);
                }
            }
            Redis::del('Wechat:AdReport');
        }
    }

    private function reportOne(Client $client,$record_id,$order_id,$appid,$openid,$price,$created_at,$p_report_type,$action_type,$type){
        $report_type = $this->transferReportType($p_report_type,$created_at,$order_id);
        $user_action_set_id = $this->getDataSource($appid,$type);
        $book_info = $this->getBookName($order_id);
        $bid = $book_info['en_bid'];
        $product_name = $book_info['book_name'].'-'.env('PROJECT_NAME');
        $token = $this->getAccessToken($appid);

        if(!$user_action_set_id || !$token){
            $this->saveRecord($user_action_set_id,$created_at,$action_type,
                $appid,$openid,$price,$report_type,$bid,
                $order_id,$product_name,$type,'FAIL','',$this->error_msg);
            return ;
        }
        $action_time = strtotime($created_at);
        $value = $price*100;
        $result = [
            'result_status'=>'FAIL',
            'result_msg'=>'type error',
            'result'=>''
        ];
        if($type == 'WECHAT'){
            $result = $this->requestMp($client, $user_action_set_id, $action_time, $action_type, $appid, $openid, $value, $product_name, $bid,$token,$report_type);
        }

        if($type == 'WEB'){
            $result = $this->requestGdt($client, $user_action_set_id, $action_time, $action_type, $appid, $openid, $value, $product_name, $bid,$token,$report_type);
        }

        $this->saveRecord($user_action_set_id,$created_at,$action_type,
            $appid,$openid,$price,$report_type,$bid,
            $order_id,$product_name,$type,$result['result_status'],$result['result'],$result['result_msg']);
        if($result['result_status'] == 'SUCCESS'){
            $status = 7;
            DB::connection('api_mysql')->table('distribution_channel_weixin_report_orders')->where('id',$record_id)
                ->update(['report_status'=>$status,'updated_at'=>date('Y-m-d H:i:s')]);
        }
    }


    private function requestGdt(Client $client, $user_action_set_id, $action_time, $action_type, $appid, $openid, $value, $product_name, $product_id,$token,$report_type)
    {
        $data['result_status'] = 'FAIL';
        $data['result_msg'] = '';
        $data['result'] = '';
        $url = 'https://api.weixin.qq.com/marketing/user_actions/add?version=v1.0&access_token=' . $token;
        $object = $report_type;
        if($action_type == 'PURCHASE'){
            $object = 1;
        }
        $request_data = ['user_action_set_id' => $user_action_set_id,
            'actions' => [['url' => env('GDT_REPORT_URL').'/detail?id='.$product_id, 'action_time' => $action_time, 'action_type' => $action_type,
                'user_id' => ['wechat_app_id' => $appid, 'wechat_openid' => $openid],
                'action_param' => ['product_name' => $product_name, 'product_id' => $product_id, 'value' => $value, 'object'=>$object]]]];
        try {
            $result = $client->request('post', $url, [
                'headers' => ['Content-Type' => 'application/json'],
                'body' => \GuzzleHttp\json_encode($request_data)
            ])->getBody()->getContents();
            $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;
            }
        } catch (Exception $e) {
            $data['result_status'] = 'FAIL';
            $data['result_msg'] = $e->getMessage();

        }
        return $data;
    }


    private function requestMp(Client $client, $user_action_set_id, $action_time, $action_type, $appid, $openid, $value, $product_name, $product_id,$token,$report_type){
        $data['result_status'] = 'FAIL';
        $data['result_msg'] = '';
        $data['result'] = '';
        $object = $report_type;
        if($action_type == 'PURCHASE'){
            $object = 1;
        }
        $request_data = [
            'actions'=>[
                [
                    'user_action_set_id'=>$user_action_set_id,
                    //'url'=>'https://sitexyvz5mexll52mzn4.zhuishuyun.com/detail?id='.$product_id,
                    'url'=>env('GDT_REPORT_URL').'/detail?id='.$product_id,
                    'action_time'=>$action_time,
                    'action_type'=>$action_type,
                    'user_id'=>[
                        'wechat_app_id'=>$appid,
                        'wechat_openid'=>$openid
                    ],
                    'action_param'=>[
                        'object'=>$object,
                        'product_name'=>$product_name,
                        'product_id'=>$product_id,
                        'source'=>'Biz',
                        'wechat_app_id'=>'',
                        'claim_type'=>0,
                        'value'=>$value
                    ]
                ]
            ]
        ];

        $url = 'https://api.weixin.qq.com/marketing/user_actions/add?version=v1.0&access_token='.$token;
        try{
            $result = $client->request('post',$url,[
                'headers'=>['Content-Type'=>'application/json'],
                'body'=>\GuzzleHttp\json_encode($request_data)
            ])->getBody()->getContents();
            $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;
            }

        }catch (Exception $e){
            Log::error($e);
        }
        return $data;
    }

    private function saveRecord($user_action_set_id,$created_at,$action_type,
                                $appid,$openid,$price,$report_type,$bid,
                                $product_id,$product_name,$type,$result_status,$result,$result_msg)
    {
        $action_time = strtotime($created_at);
        $data = [
            'user_action_set_id'=>$user_action_set_id,
            //'url'=>'https://sitexyvz5mexll52mzn4.zhuishuyun.com/detail?id='.$bid, 'action_time'=>$action_time,
            'url'=>env('GDT_REPORT_URL').'/detail?id='.$bid,
            'action_type'=>$action_type, 'openid'=>$openid,
            'appid'=>$appid, 'product_id'=>$product_id,
            'value'=>$price*100,'result_status'=>$result_status,
            'created_at'=>date('Y-m-d H:i:s'), 'updated_at'=>date('Y-m-d H:i:s'),
            'bid'=>$bid,'product_name'=>$product_name,'result'=>$result,
            'result_msg'=>$result_msg,'object'=>$report_type
        ];
        $table = 'wechat_advertise_gdt_report_record';
        if($type == 'WECHAT'){
            $data['source'] = 'Biz';
            $data['claim_type'] = 0;
            $table = 'wechat_advertise_report_record';
        }
        DB::table($table)->insert($data);

    }


    private function getDataSource($appid,$type='WECHAT'){
        if(!isset($this->user_action_set_id[$appid])){
            $result = $this->getDataSourceFromDB($appid,$type);
            if($result){
                $this->user_action_set_id[$appid] = $result;
                return $result;
            }
            $result = $this->createDataSource($appid,$type);
            if($result){
                $this->user_action_set_id[$appid] = $result;
                return $result;
            }
            return '';
        }
        return  $this->user_action_set_id[$appid];

    }


    private function getDataSourceFromDB($appid, $type)
    {
        $result = DB::table('wechat_advertise_data_source')->where('appid', $appid)->where('type', $type)->select('user_action_set_id')->first();
        if ($result) {
            return $result->user_action_set_id;
        }
        return 0;
    }

    private function createDataSource(string $appid,string $type){
        $token = $this->getAccessToken($appid);
        if(!$token) return 0;
        $url = 'https://api.weixin.qq.com/marketing/user_action_sets/add?version=v1.0&access_token='.$token;
        $client = new Client();
        $name = '支付下单';
        $description = '支付下单,充值统计';
        $body = json_encode([
            'type'=>$type,
            'wechat_app_id'=>$appid,
            'name'=>$name,
            'description'=>$description
        ]);
        try{
            $result = $client->request('post',$url,[
                'headers'=>['Content-Type'=>'application/json'],
                'body'=>$body
            ])->getBody()->getContents();
            $result = \GuzzleHttp\json_decode($result,1);
            if($result['errcode'] == 0 && isset($result['data']) && isset($result['data']['user_action_set_id'])){
                $user_action_set_id = $result['data']['user_action_set_id'];
                $this->saveDataSource($appid,$name,$type,$description,$user_action_set_id);
                return $user_action_set_id;
            }
            if($result['errcode'] == 900351000){
                $msg_array = explode(':',$result['errmsg']);
                if(isset($msg_array[1])){
                    $user_action_set_id = trim($msg_array[1]);
                    $this->saveDataSource($appid,$name,$type,$description,$user_action_set_id);
                    return $user_action_set_id;
                }
            }
        }catch (Exception $e){
            Log::error($e);
        }
        $this->error_msg = $appid.',createDataSource fail';
        return 0;
    }

    private function transferReportType($report_type,$order_time,$order_id){
        $map = [
            'one_day_first_pay'=>'read_1',
            'one_day_all_pay'=>'read_2',
            'current_day_register_first_pay'=>'read_3',
            'current_day_register'=>'read_4',
            'three_day_first_pay'=>'read_5',
            'three_day_all_pay'=>'read_6'
        ];
        if(isset($map[$report_type])){
            return $map[$report_type];
        }
        $order_info = DB::connection('api_mysql')->table('orders')->where('id',$order_id)->select('uid')->first();
        if(!$order_info){
            return '';
        }
        $uid = $order_info->uid;
        $user_info = DB::connection('api_mysql')->table('users')->where('id',$uid)->select('created_at')->first();
        if(!$user_info) return '';
        $register_time = $user_info->created_at;
        $register_timestamp = strtotime($register_time);
        $order_timestamp = strtotime($order_time);
        if(date('Y-m-d',$register_timestamp) == date('Y-m-d',$order_timestamp)){
            return 'read_4';
        }
        if(strtotime($order_time) -  strtotime($register_time)  < 86400){
            return 'read_2';
        }
        if(strtotime($order_time) -  strtotime($register_time)  < 3*86400){
            return 'read_6';
        }
        return '';
    }
    private function saveDataSource(string $appid,string $name,string $type,string $description,int $user_action_set_id){
        DB::table('wechat_advertise_data_source')->insert([
            'appid'=>$appid,
            'name'=>$name,
            'type'=>$type,
            'description'=>$description,
            'user_action_set_id'=>$user_action_set_id,
            'created_at'=>date('Y-m-d H:i:s'),
            'updated_at'=>date('Y-m-d H:i:s')
        ]);
    }


    private function getBookName($order_id){
        $result = ['bid'=>'','book_name'=>'','en_bid'=>''];
        try{
            $order_info = DB::connection('api_mysql')->table('orders')->select('from_bid')->where('id',$order_id)->first();
            if($order_info && $order_info->from_bid){
                $result['bid'] = $order_info->from_bid;
                $result['en_bid'] = \Hashids::encode($order_info->from_bid);
                $book_info = DB::connection('api_mysql')->table('book_configs')
                    ->select('book_name','is_on_shelf')
                    ->where('bid',$order_info->from_bid)->first();
                if($book_info){
                    if($book_info->is_on_shelf == 2){
                        $result['book_name'] = $book_info->book_name;
                    }
                }
                return $result;
            }
        }catch (\Exception $e){

        }
        return $result;
    }

    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 '';
    }
}