<?php

namespace app\controller;

use support\Request;
use support\Db;
use process\TaskGetSale;

class SalesController
{
    public function test(Request $request)
    {
        set_time_limit(3600 * 10);
        
		$data = [];
        $page = 0;
        $pageSize = 1000;
		$yearRegion =  date("Y-m-d", strtotime("-3 year"));
        while(true){
            $rows = Db::table('gsp_new_saledataall_bi')
                    ->select('transfernewno','custnumber', Db::raw('SUM(quantity) as qty'), Db::raw('MAX(orderdate) as orderdate'))
					->where( 'deliverydate','>=', $yearRegion )
                    ->groupBy('custnumber','transfernewno')
                    ->offset($page * $pageSize)
                    ->limit($pageSize)
					//->toSql();
                    ->get();
            if(empty($rows)){
                break;
            }else{
                echo $page."\r\n";
                $insertData = [];
                foreach($rows as $row){
                    return response(put($row));
                   $proRow = Db::table('smt_pro')
                            ->where([
                                ['smt_p_outnum',$row->transfernewno]
                            ])
                            ->first();
                    $custRow = Db::table('api_crm_customer')
                            ->orWhere([
                                ['AccountNumber',$row->custnumber],
                                //['NewSAPCode',$row->newno]
                            ])
                            ->first();
                        $countryRow = Db::table('smt_customer')
                                ->where([
                                    ['c_id',$custRow->guid]
                                ])
                                ->first();
                        $data = [$proRow,$custRow,$countryRow];
                        $insertData[] = [
                            'ssale_p_id'=>$proRow->smt_p_id,
                            'ssale_guid'=>$custRow->guid,
                            'ssale_cc_id'=>$countryRow->c_country,
                            'ssale_qty'=>$row->qty,
                        ];
                        return response(put($data));
                        exit();
                }
                if(!empty($insertData)){
                    
                }
            }
            $page++;
        }
		return response(put($data));
    }

	public function getSaleCountry(Request $request)
    {
		$ccids= explode(',', $request->get('ccids')); $rate = $request->get('rate');$min = $request->get('min');
		$TaskGetSale = new TaskGetSale();
		$addArr = $TaskGetSale->getSaleCountry($ccids, $rate, $min);
		return json($addArr);
	}

    //同市场交叉销售
	public function createSaleIdxByCountry(Request $request)
    {
        set_time_limit(3600 * 100);
        ini_set('memory_limit', '2048M');
		$yearRegion =  date("Y-m-d", strtotime("-3 year"));
        $countryRows = Db::table('smt_sale_base')
        ->select('ssb_country')
        ->groupBy('ssb_country')
        ->orderBy('ssb_country')
        ->get();
        Db::table('smt_sale_cross')->truncate();
        foreach($countryRows as $k=>$countryRow){
           $country = $countryRow->ssb_country;
           $rows = Db::table('smt_sale_base')
            ->select('ssb_cid','ssb_country','ssb_p_id')
            ->where('ssb_country','=',$country)
            ->where('ssb_deliverydate','>=',$yearRegion)
            ->distinct()
			->orderBy('ssb_country','asc')
			->orderBy('ssb_p_id','asc')
            ->get();
           $dataset = [];
           $total = Db::table('smt_sale_base')
             ->selectRaw('COUNT(DISTINCT ssb_cid) as total')
             ->where('ssb_country','=',$country)
             ->first();
           $total = $total->total;
           $isInsert = false;
           $oldKey = '';
           echo "country: ".$country."\r\n";
           foreach($rows as $row){
                $key = $country.','.$row->ssb_p_id;
                if($oldKey!='' && count($dataset)>=1000 && $oldKey != $key){
                    Db::table('smt_sale_cross')->insert($dataset);
                    $dataset = [];
                }
                if($oldKey=='' || $oldKey!=$key) $oldKey = $key;

                if(!isset($dataset[$key])){
                    $dataset[$key]['ssc_find'] = 0;
                    $dataset[$key]['ssc_country'] = $country;
                    $dataset[$key]['ssc_pid'] = $row->ssb_p_id;
                    $dataset[$key]['ssc_total'] = $total;
                }
                $dataset[$key]['ssc_find']++;
                $dataset[$key]['ssc_bl'] = round($dataset[$key]['ssc_find'] / $total,4);
           }
           if(!empty($dataset)) Db::table('smt_sale_cross')->insert($dataset);
        }
		return response(put(['OK']));
	}
}