<?php

namespace App\Console\Commands;

use App\Jobs\SendTexts;
use App\Modules\SendOrder\Services\SendOrderService;
use App\Modules\Subscribe\Services\YearOrderService;
use App\Modules\User\Models\UserMonthSign;
use App\Modules\User\Services\ReadRecordService;
use App\Modules\User\Services\UserMonthService;
use App\Modules\User\Services\UserService;
use Illuminate\Console\Command;
use App\Modules\Subscribe\Services\OrderService;
use Redis;
use Log;
use DB;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //$this->checkOne(157286149);
        $uid = $this->option('uid');
        if($uid) {
            $this->checkOne($uid);
        }else{
            $sql_format = 'SELECT uid,`type` FROM user_month_sign WHERE created_at >= DATE_ADD(NOW(),INTERVAL -1 hour)   and 
NOT EXISTS (SELECT id FROM user_month_order WHERE user_month_order.uid =user_month_sign.uid and created_at BETWEEN "%s" and "%s" )';
            $sql = sprintf($sql_format,date('Y-m-01'),date('Y-m-01',strtotime('+1 month')));
            $result = DB::select($sql);
            if($result){
                foreach ($result as $item){
                    $this->checkOne($item->uid,$item->type);
                }
            }
            /*$result = UserMonthSign::where('created_at','>=',date('Y-m-d H:i:s',time()-1800))->select('uid')->get();
            if($result->isNotEmpty()){
                foreach ($result as $item){
                    $this->checkOne($item->uid);
                }
            }*/
        }
    }
    public function checkOne($uid,$type){
        //int $user_id,int $plan_id,string $app_id,string $key,string $app_secret

        $app_id = env('MONTH_ORDER_APPID');
        if($type == 'MONTH'){
            $plan_id = env('MONTH_ORDER_PLAN_ID');
            $product_id = 6826;
        }elseif ($type == 'WEEK'){
            $product_id =7394;
            $plan_id = env('MONTH_WEEK_ORDER_PLAN_ID');
        }else{
            $product_id =0;
            $plan_id ='';
        }
        if(empty($plan_id)) {
            Log::info(sprintf('plan is not exist,uid is : %s,order is not exist',$uid));
            return '';
        }
        $key = env('MONTH_ORDER_KEY');
        $app_secret = env('MONTH_ORDER_APP_SECRET');
        $result = UserMonthService::checkOrderStatus($uid,$plan_id,$app_id,$key,$app_secret);

        if(isset($result['code']) && !$result['code']){
            echo sprintf('sign fail ,uid is :%s',$uid).PHP_EOL;
            return '';
        }
        //print_r($result);
        $trade_no = $result['trade_no'];
        $out_trade_no = $result['out_trade_no'];
        $money = $result['money'];
        if(empty($trade_no) || empty($out_trade_no) || empty($money)){
            Log::info(sprintf('uid is : %s,order is not exist',$uid));
            echo sprintf('uid is : %s,order is not exist',$uid).PHP_EOL;
            return '';
        }
        Log::info($result);
        if (!UserMonthService::getOrderByOrder($trade_no, $out_trade_no)) {
            Log::info('deal uid is :'.$uid);
            UserMonthService::createLOrder($uid, $plan_id, $money, $trade_no, $out_trade_no,$type);
            $this->addOrderAndVip($uid, $out_trade_no, $trade_no, $money,$type,$product_id);
        }
    }

    private function addOrderAndVip($uid, $out_trade_no, $trade_no, $price,$type,$product_id)
    {

        $order_info = OrderService::getByTradeNo($out_trade_no);
        //订单已经存在
        if ($order_info) {
            return;
        }
        $user_info = UserService::getById($uid);
        if (!$user_info) return;
        $this->createOrder($uid, $user_info->distribution_channel_id, $product_id, $price, $out_trade_no, $trade_no);
        /*YearOrderService::save_month_order([
            'uid' => $uid,
            'distribution_channel_id' => $user_info->distribution_channel_id,
            'fee' => $price / 100,
            'send_order_id' => 0
        ]);*/
        if($type == 'MONTH'){
            YearOrderService::save_month_order([
                'uid' => $uid,
                'distribution_channel_id' => $user_info->distribution_channel_id,
                'fee' => $price / 100,
                'send_order_id' => 0
            ]);
        }
        if($type == 'WEEK'){
            YearOrderService::save_vip_order_daynum([
                'uid' => $uid,
                'distribution_channel_id' => $user_info->distribution_channel_id,
                'fee' => $price / 100,
                'send_order_id' => 0,
                'day_num'=>7
            ]);
        }
    }

    private function createOrder($uid, $distribution_channel_id, $product_id, $price, $trade_no, $transaction_id)
    {
        $count = OrderService::getUserChargeTimes($uid);
        $count = $count + 1;
        $send_order_id = 0;
        try {
            $send_order_id = (int)Redis::hget('book_read:' . $uid, 'send_order_id');
        } catch (\Exception $e) {
        }
        $send_order_name = '';
        if ($send_order_id) {
            $send_order_info = SendOrderService::getById($send_order_id);
            if ($send_order_info && isset($send_order_info->name) && !empty($send_order_info->name)) {
                $send_order_name = $send_order_info->name;
            }
        }
        $from_bid = ReadRecordService::getSimpleFirstReadRecord($uid);
        $init_order = [
            'distribution_channel_id' => $distribution_channel_id,
            'uid' => $uid,
            'product_id' => 6826,
            'price' => $price / 100,
            'pay_type' => $count,
            'trade_no' => $trade_no,
            'pay_merchant_source' => 'MONTH',
            'pay_merchant_id' => 99,
            'create_ip' => '',
            'send_order_id' => $send_order_id,
            'send_order_name' => $send_order_name,
            'order_type' => 'RECHARGE',
            'from_bid' => $from_bid,
            'from_type' => 'auto_month',
            'activity_id' => 0,
            'inner_send_order_id' => '',
            'status' => 'PAID',
            'transaction_id' => $transaction_id,
            'pay_end_at' => date('Y-m-d H:i:s')
        ];
        OrderService::save_order($init_order);
    }

    protected function successPayPushMsg($uid)
    {
        try {
            $force_sub_info = DB::table('force_subscribe_users')->where('uid', $uid)->where('is_subscribed', 1)->first();
            $data = UserService::getById($uid);
            if (!$force_sub_info) {
                return;
            }

            $content_format = "包月购买成功通知:\r\n购买类型: 30元包月\r\n><a href='%s'>点击继续上次阅读</a>\r\n包月特权:\r\n 💝 全站所有作品免费阅读\r\n 💝 全站无广告\r\n 💝 阅读管家1对1服务\r\n为保障包月权益，请<a href='%s'>置顶公众号</a> ";

            $delay = 0;
            $url = env('PROTOCOL') . '://site' . encodeDistributionChannelId($data->distribution_channel_id) . '.' . env('CUSTOM_HOST') . '.com/continue';;
            $top_url = 'https://help.zhuishuyun.com/top.html';

            $content = sprintf($content_format, $url, $top_url);

            $res['openid'] = $force_sub_info->openid;
            $res['appid'] = $force_sub_info->appid;
            $res['content'] = $content;
            $res['type'] = 'one_task';
            $res['send_time'] = date("Y-m-d H:i:s");
            $res['task_id'] = md5('month_pay_success_push');
            $send_data = array(
                'send_time' => date("Y-m-d H:i:s"),
                'data' => $res
            );
            dispatch((new SendTexts($send_data))->onConnection('rabbitmq')->delay($delay)->onQueue('send_texts_list'));


        } catch (\Exception $e) {
            Log::error('pay_success_push error');
            Log::error($e);
        }
        return;
    }
}
