<?php

namespace App\Console\Commands;

use App\Modules\Channel\Models\Channel;
use App\Modules\Finance\Models\CommissionRate;
use App\Modules\Trade\Services\OrderService;
use DB;
use GuzzleHttp\Client;
use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '云栖迁移渠道补偿';


    public function handle()
    {
       /* Channel::where([
            ['created_at','>=',date('Y-m-d H:i:s',strtotime('-1 month'))],
            ['is_yq_move','=',1]
        ])->chunk(1000,function($res){
            foreach ($res as $item){
                $commission = CommissionRate::where('distribution_channel_id',$item->id)->first();
                if($commission) {
                    $commission->rate = 1;
                    $commission->save();
                }else{
                    \Log::error('CompensateForMoveChannelFailed:'.$item->id);
                }
            }
        });*/
       $distribution_channels = DB::select("SELECT * FROM distribution_channels WHERE distribution_channels.is_yq_move=1 AND NOT EXISTS(SELECT * FROM yq_move_channels WHERE yq_move_channels.distribution_channel_id=distribution_channels.id)");
       foreach ($distribution_channels as $distribution_channel){
           //$moved =  DB::table('yq_move_channels')->where('distribution_channel_id',$distribution_channel->id)->first();
           DB::table('yq_move_channels')->insert(['distribution_channel_id'=>$distribution_channel->id,'created_at'=>date('Y-m-d H:i:s')]);
       }
       $to_modifys = DB::table('yq_move_channels')->where('created_at','>=',date('Y-m-d H:i:s',strtotime('-1 month')))->get();
       foreach ($to_modifys as $to_modify) {
           $commission = CommissionRate::where('distribution_channel_id',$to_modify->distribution_channel_id)->first();
           if($commission) {
               $commission->rate = 1;
               $commission->save();
           }else{
               \Log::error('CompensateForMoveChannelFailed:'.$to_modify->id);
           }
       }

       $to_withDraws = DB::table('yq_move_channels')->where('created_at','<',date('Y-m-d H:i:s',strtotime('-3 month')))->get();
       foreach ($to_withDraws as $to_withDraw) {
           $commission = CommissionRate::where('distribution_channel_id',$to_withDraw->distribution_channel_id)->first();
           if($commission) {
               $commission->rate = 0.9;
               $commission->save();
           }else{
               \Log::error('CompensateForMoveChannelFailed:'.$to_withDraw->id);
           }
       }
       $senven_days_ago = date('Y-m-d H:i:s',strtotime('-7 day'));
       $senven_days_later = DB::select("SELECT * FROM yq_move_channels WHERE created_at < '".$senven_days_ago."' AND distribution_channel_id NOT IN (4217) AND EXISTS (SELECT * FROM distribution_channels WHERE is_yq_move = 1 AND distribution_channels.id=yq_move_channels.distribution_channel_id)");//DB::table('yq_move_channels')->where('created_at','<',date('Y-m-d H:i:s',strtotime('-7 day')))->get();
        \Log::info('distribution_channels_to_modify:'.json_encode($senven_days_later));
        self::update_distribution($senven_days_later);
        $month_ago = date('Y-m-d H:i:s',strtotime('-1 month'));
        $res = DB::select("SELECT * FROM yq_move_channels WHERE created_at < '".$month_ago."' AND distribution_channel_id IN (4217) AND EXISTS (SELECT * FROM distribution_channels WHERE is_yq_move = 1 AND distribution_channels.id=yq_move_channels.distribution_channel_id)");
        self::update_distribution($res);
    }

    static public function getUserClient()
    {
        return new Client(['base_uri' => env('AUTH_API_BASE_URI')]);
    }
     private function update_distribution($data){
         foreach ($data as $item) {
             //DB::beginTransaction();
             //if(!in_array($item->distribution_channel_id,[4217])){
                 $distribution_channel = Channel::where('id',$item->distribution_channel_id)->first();
                 $distribution_channel->is_yq_move = 0;
                 $distribution_channel->save();

                 $res = DB::table('official_accounts')
                     ->where('distribution_channel_id',$item->distribution_channel_id)
                     ->get();
                 foreach ($res as $officail_account) {
                     $gzh_app_id = isset($officail_account->appid)?$officail_account->appid:env('WECHAT_AUTH_APPID');

                     try {

                         $timestamp = time();
                         $params = array('authorizer_appid' => $officail_account->appid,'set_type'=>'menu', "timestamp" => $timestamp);
                         $sign = get_sign($params);

                         $resJson = self::getUserClient()->request("GET", "auto_set_menu_and_template_test",
                             ['query' => ['set_type' => 'menu','authorizer_appid'=>$officail_account->appid, 'timestamp' => $timestamp, 'sign' => $sign]]
                         )->getBody()->getContents();
                         //\Log::info('authorize_menu_done:'.json_encode($resJson));
                         //if($resJson){

                         //}
                     } catch (\Exception $e) {
                         \Log::error('menu_authorized_fail:'.$e->getMessage());
                         DB::rollback();
                         continue;
                     }
                     DB::commit();
                     \Log::info('authorized_accounts:'.json_encode($officail_account));
                 }
             }

         }
     //}
}
