<?php namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Admin;
use App\Distributors;

class GroupFanAmountByMonth extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'GroupFanAmountByMonth';
	protected $date;

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = '新粉月销售额梯形图';

    public function handle()
    {
        try{
            $this->date = date('Y-m-01',strtotime('-1 months'));
            $this->TeamFanAmountByMonth();
        } catch (\Exception $e) {
            echo 'line:'.$e->getLine().' message:'.$e->getMessage();
        }

    }

    public function TeamFanAmountByMonth() {
        $team_ids = Admin::getTeams();
        foreach ($team_ids as $team_id) {
            $date = $this->date;
            $date_first = $this->date;
            $date_end = $this->getthemonth($date);
            #团队成员:
            $saler_ids = DB::table('admin')->where('team_id', $team_id)->lists('id');
            //第一步: 统计上月数据
            #上月加粉
            $phones = DB::table('customers')->whereIn('admin_id',$saler_ids)->where('fanTime', '>=', $date_first)->where('fanTime', '<=', $date_end)->lists('phone');
            $amount = DB::table('order')->whereIn('receiverMobile', $phones)->where('createTime','>=',$date)->where('createTime', '<=', $date_end. '23:59:59')->where('is_del', 0)->where('team_id', $team_id)->sum('receivedAmount');
            //存入数据表
            $result = $this->updateData($date, $amount, $date, $team_id);
            echo "\nDate:".$date." team_id:".$team_id." amount:".$amount." 处理结果:".$result;
            //第二布:统计往期数据
            #查日期列表
            $dates = DB::table('cust_month_remain')->select('idate')->where('team_id', $team_id)->where('idate','<', $date)->groupBy('idate')->orderBy('idate', 'desc')->get();
            if( !empty($dates) ) {
                $dates = json_decode(json_encode($dates),true);
                foreach ($dates as $k=>&$v) {
                    $idate_first = date('Y-m-01',strtotime($v['idate']));
                    $idate_end = $this->getthemonth($v['idate']);
                    $phones = DB::table('customers')->whereIn('admin_id',$saler_ids)->where('fanTime', '>=', $idate_first)->where('fanTime', '<=', $idate_end)->lists('phone');
                    $amount = DB::table('order')->whereIn('receiverMobile', $phones)->where('createTime','>=', $date_first)->where('createTime', '<', $date_end. '23:59:59')->where('is_del', 0)->where('team_id', $team_id)->sum('receivedAmount');
                    //存入数据表
                    $result = $this->updateData($v['idate'], $amount, $date, $team_id);
                    echo "\nDate:".$v['idate']." team_id:".$team_id." amount:".$amount." 处理结果:".$result;
                }
            }
        }
    }

    public function updateData($idate, $amount, $date, $team_id){
        #当前年份
        $month = date('Y-01', strtotime($date));
        $data = array(); 
        #如果是上个月的数据直接插入
        if($idate == $date ){
            $data['team_id'] = $team_id;
            $data['idate'] = $idate;
            $data['month_time'] = $month;
            $data['amount_data'] = json_encode([0=>['date'=>$date, 'amount'=>$amount]]);
            $data['create_time'] = date('Y-m-d H:i:s',time());
            $res = DB::table('cust_month_remain')->insert($data);
        }else{
            if(12 < $this->getMonthNum( $idate, $date)){
                return 0;
            }

            //往期成单
            $odata = DB::table('cust_month_remain')->where('team_id', $team_id)->where('idate', $idate)->first();
            $amount_data = json_decode($odata->amount_data, true);
            $amount_data[] = ['date'=>$date, 'amount'=>$amount];
            $data['amount_data'] = json_encode($amount_data);
            $res = DB::table('cust_month_remain')->where('team_id', $team_id)->where('idate', $idate)->update($data);
        }

        return $res;
    }

    public function getthemonth($date)
    {
        $firstday = date('Y-m-01', strtotime($date));
        $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
        return $lastday;
    }

    public function getMonthNum($date1,$date2){
        $date1_stamp=strtotime($date1);
        $date2_stamp=strtotime($date2);
        list($date_1['y'],$date_1['m'])=explode("-",date('Y-m',$date1_stamp));
        list($date_2['y'],$date_2['m'])=explode("-",date('Y-m',$date2_stamp));
        return abs($date_1['y']-$date_2['y'])*12 +$date_2['m']-$date_1['m'];
    }
}