<?php
/**
 * Created by PhpStorm.
 * User: z-yang
 * Date: 2020/4/28
 * Time: 16:38
 */

namespace App\Console\Commands\Wechat;

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

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

    /**
     * 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()
    {
        $option = $this->option('type');
        if($option == 'order'){
            $this->reportOrders();
        }
        if($option == 'register'){
            $this->reportRegister();
        }
    }

    private function reportRegister(){
        $action_type = 'REGISTER';
        $users = $this->getRegisterData($action_type);
        if(!$users) return ;
        $client = new Client();
        foreach ($users  as $item){

            $user_action_set_id = $this->getDataSurce($item['appid'],'WEB');
            $action_time = strtotime($item['created_at']);
            $data = [
                'user_action_set_id'=>$user_action_set_id,
                'url'=>'',
                'action_time'=>$action_time,
                'action_type'=>$action_type,
                'openid'=>$item['openid'],
                'appid'=>$item['appid'],
                'product_id'=>$item['id'],
                'value'=>0,
                'created_at'=>date('Y-m-d H:i:s'),
                'updated_at'=>date('Y-m-d H:i:s'),
                'result_status'=>'FAIL',
                'result_msg'=>'',
                'result'=>'',
            ];
            $book_info = $this->getBookNameByBid($item['bid']);
            $product_id = '';
            $product_name = '';
            $data['bid'] = $book_info['en_bid'];
            if($book_info['en_bid'] && $book_info['book_name']){
                $product_id = $book_info['en_bid'];
                $data['bid'] = $book_info['en_bid'];
                $product_name = $book_info['book_name'].'-'.env('PROJECT_NAME');
                $data['product_name'] = $product_name;
                $data['url'] = env('GDT_REPORT_URL').'/detail?id='.$book_info['en_bid'];
            }
            $token = $this->getAccessToken($item['appid']);
            if(!$user_action_set_id || !$token) {
                $data['result_msg'] = $this->error_msg;
                DB::table('wechat_advertise_gdt_report_record')->insert($data);
                continue;
            };
            $result = $this->request($client, $user_action_set_id, $action_time, $action_type, $item['appid'], $item['openid'], 0, $product_name, $product_id,$token,'');
            $data['result_status'] = $result['result_status'];
            $data['result_msg'] = $result['result_msg'];
            $data['result'] = $result['result'];
            try{
                DB::table('wechat_advertise_gdt_report_record')->insert($data);
                if($data['result_status'] == 'SUCCESS'){
                    DB::connection('api_mysql')->table('distribution_channel_weixin_spread_users')->where('uid',$item['id'])->update([
                        'report_status'=>1,
                        'updated_at'=>date('Y-m-d H:i:s')
                    ]);
                }

            }catch (\Exception $e){}
            //second
            $data['action_type'] = 'FOLLOW';
            $result = $this->request($client, $user_action_set_id, $action_time, 'FOLLOW', $item['appid'], $item['openid'], 0, $product_name, $product_id,$token,'');
            $data['result_status'] = $result['result_status'];
            $data['result_msg'] = $result['result_msg'];
            $data['result'] = $result['result'];
            DB::table('wechat_advertise_gdt_report_record')->insert($data);

        }
    }

    private function reportOrders(){
        $action_type = 'COMPLETE_ORDER';
        $orders = $this->getOrderData($action_type);
        if(!$orders) return ;
        $client = new Client();
        foreach ($orders  as $item){
            $report_type = $this->transferReportType($item['report_type'],$item['created_at'],$item['id']);

            $user_action_set_id = $this->getDataSurce($item['appid'],'WEB');
            $action_time = strtotime($item['created_at']);
            $data = [
                'user_action_set_id'=>$user_action_set_id,
                'url'=>'',
                'action_time'=>$action_time,
                'action_type'=>$action_type,
                'openid'=>$item['openid'],
                'appid'=>$item['appid'],
                'product_id'=>$item['id'],
                'value'=>$item['price']*100,
                'created_at'=>date('Y-m-d H:i:s'),
                'updated_at'=>date('Y-m-d H:i:s'),
                'result_status'=>'FAIL',
                'result_msg'=>'',
                'result'=>'',
                'object'=>$report_type
            ];
            $book_info = $this->getBookNameFromOrer($item['id']);
            $product_id = '';
            $product_name = '';
            $data['bid'] = $book_info['en_bid'];
            if($book_info['en_bid'] && $book_info['book_name']){
                $product_id = $book_info['en_bid'];
                $data['bid'] = $book_info['en_bid'];
                $product_name = $book_info['book_name'].'-'.env('PROJECT_NAME');
                $data['product_name'] = $product_name;
                $data['url'] = env('GDT_REPORT_URL').'/detail?id='.$book_info['en_bid'];
            }
            $token = $this->getAccessToken($item['appid']);
            if(!$user_action_set_id || !$token) {
                $data['result_msg'] = $this->error_msg;
                DB::table('wechat_advertise_gdt_report_record')->insert($data);
                DB::connection('api_mysql')->table('distribution_channel_weixin_report_orders')->where('order_id',$item['id'])->update([
                    'report_status'=>5,
                    'updated_at'=>date('Y-m-d H:i:s')
                ]);
                continue;
            };
            $result = $this->request($client, $user_action_set_id, $action_time, $action_type, $item['appid'], $item['openid'], $item['price']*100, $product_name, $product_id,$token,$report_type);
            $data['result_status'] = $result['result_status'];
            $data['result_msg'] = $result['result_msg'];
            $data['result'] = $result['result'];
            try{
                DB::table('wechat_advertise_gdt_report_record')->insert($data);
                if($data['result_status'] == 'SUCCESS'){
                    DB::connection('api_mysql')->table('distribution_channel_weixin_report_orders')->where('order_id',$item['id'])->update([
                        'report_status'=>1,
                        'updated_at'=>date('Y-m-d H:i:s')
                    ]);
                }

            }catch (\Exception $e){}
            //second
            $data['action_type'] = 'PURCHASE';
            $result = $this->request($client, $user_action_set_id, $action_time, 'PURCHASE', $item['appid'], $item['openid'], $item['price']*100, $product_name, $product_id,$token,$report_type);
            $data['result_status'] = $result['result_status'];
            $data['result_msg'] = $result['result_msg'];
            $data['result'] = $result['result'];
            DB::table('wechat_advertise_gdt_report_record')->insert($data);
            try{
                if($data['result_status'] == 'SUCCESS'){
                    DB::connection('api_mysql')->table('distribution_channel_weixin_report_orders')->where('order_id',$item['id'])->update([
                        'report_status'=>1,
                        'updated_at'=>date('Y-m-d H:i:s')
                    ]);
                }
            }catch (\Exception $e){}
        }
    }

    private function getOrderData($action_type)
    {
        $data = [];
        $start = date('Y-m-d');
        if (date('H:i:s') < '02:00:00') {
            $start = date('Y-m-d H:i:s', time() - 3 * 3600);
        }
        $result = DB::connection('api_mysql')->table('distribution_channel_weixin_report_orders')
            ->where('report_status', 0)
            ->where('created_at', '>=', $start)
            ->where('type','WEB')
            ->where('action_type','ALL')
            ->select('order_id', 'appid', 'openid', 'price', 'report_status', 'created_at','report_type')
            ->get();
        if ($result) {
            foreach ($result as $item) {
                $report_info = DB::table('wechat_advertise_gdt_report_record')
                    ->where('product_id', $item->order_id)
                    ->where('action_type', $action_type)
                    ->where('result_status', 'SUCCESS')
                    ->count();
                if ($report_info) {
                    try {
                        DB::connection('api_mysql')->table('distribution_channel_weixin_report_orders')->where('order_id', $item->order_id)->update([
                            'report_status' => 1,
                            'updated_at' => date('Y-m-d H:i:s')
                        ]);
                    } catch (\Exception $e) {
                        \Log::info($e);
                    }
                    continue;
                }
                $data[] = ['created_at' => $item->created_at, 'openid' => $item->openid,'report_type'=>$item->report_type,
                    'id' => $item->order_id, 'appid' => $item->appid, 'price' => $item->price];
            }
        }
        return $data;
    }

    private function getRegisterData($action_type)
    {
        $data = [];
        $start = date('Y-m-d');
        if (date('H:i:s') < '02:00:00') {
            $start = date('Y-m-d H:i:s', time() - 3 * 3600);
        }
        $result = DB::connection('api_mysql')->table('distribution_channel_weixin_spread_users')
            ->where('report_status', 0)
            ->where('created_at', '>=', $start)
            ->select('uid', 'appid', 'openid', 'report_status', 'created_at', 'bid')
            ->get();
        if ($result) {
            foreach ($result as $item) {
                $report_info = DB::table('wechat_advertise_gdt_report_record')
                    ->where('product_id', $item->uid)
                    ->where('action_type', $action_type)
                    ->where('result_status', 'SUCCESS')
                    ->count();
                if ($report_info) {
                    continue;
                }
                $data[] = ['created_at' => $item->created_at, 'openid' => $item->openid,
                    'id' => $item->uid, 'appid' => $item->appid, 'bid' => $item->bid];
            }
        }
        return $data;
    }

    private function request(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;
        $request_data = [
            'user_action_set_id' => $user_action_set_id,
            'actions' => [
                ['url' => '', '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'=>$report_type
                    ]
                ]
            ]
        ];
        try {
            $result = $client->request('post', $url, [
                'headers' => ['Content-Type' => 'application/json'],
                'body' => \GuzzleHttp\json_encode($request_data)
            ])->getBody()->getContents();
            Log::info('gdt user_actions/add body is ' );
            Log::info(\GuzzleHttp\json_encode($request_data));
            Log::info('gdt 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) {
            $data['result_status'] = 'FAIL';
            $data['result_msg'] = $e->getMessage();
            Log::error($e);
            return $data;
        }
    }

    private function getDataSurce($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;
            }
            $this->error_msg = 'getDataSurce fail';
            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 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 '';
    }

    private function getBookNameFromOrer($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 getBookNameByBid($bid){
        $result = ['bid'=>'','book_name'=>'','en_bid'=>''];
        if(!$bid) return $result;
        $result['en_bid'] = \Hashids::encode($bid);
        $result['bid'] = $bid;
        $book_info = DB::connection('api_mysql')->table('book_configs')->select('book_name','is_on_shelf')->where('bid',$bid)->first();
        if($book_info){
            if($book_info->is_on_shelf == 2){
                $result['book_name'] = $book_info->book_name;
            }
        }
        return $result;
    }

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