<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;
class RepeatBookOrderRecover extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'book:bor {--type=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '单本订购重复订单恢复';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $options = $this->option('type');
        if($options){
            echo $this->stats();
        }else{
            echo $this->start();
        }
        return;
    }

    public function  start(){
        $sql = "SELECT uid,bid,COUNT(*) FROM book_orders where uid>0 and bid>0 GROUP BY uid,bid HAVING COUNT(*) >=2";
        $res = DB::select($sql);
        $i = 0;
        foreach ($res as $v){
            $order = DB::table('book_orders')->where('bid',$v->bid)->where('uid',$v->uid)->first();
            $update_user_sql = "UPDATE users set balance = balance+{$order->fee},reward_balance=reward_balance+{$order->reward_balance},charge_balance=charge_balance+{$order->charge_balance} where id = {$order->uid}";
            DB::update($update_user_sql);
            DB::table('book_orders')->where('id',$order->id)->update(['uid'=>-$order->uid]);
            $i++;
        }
        return '修改了'.$i.'个用户';
    }

    public function stats(){
        $sql = "SELECT  id,bid,fee,date(created_at) as days,send_order_id,charge_balance,reward_balance FROM book_orders WHERE uid<0 and fee >0";
        $res = DB::select($sql);
        $i = 0;
        foreach ($res as $v){
            $update_sql = "update book_order_statistical set fee=fee-{$v->fee}, reward_balance=reward_balance-{$v->reward_balance}, charge_balance=charge_balance-{$v->charge_balance} where bid={$v->bid} and `day`='{$v->days}'";
            DB::update($update_sql);
            DB::table('book_orders')->where('id',$v->id)->update(['fee'=>0]);
            //DB::table('book_order_statistical')->where('bid',$v->bid)->where('day',$v->days)->
            $i++;
        }
        return '修改了'.$i.'个记录';
    }
}
