<?php

namespace App\Http\Controllers;


use App\Authority;
use App\Batch;
use App\City;
use App\Events\CancelOrder;
use App\Logistic;
use App\OracleActAllocationDetails;
use App\OracleDOCOrderHeader;
use App\OracleDocOrderPackingSummary;
use App\OracleDOCWaveDetails;
use App\OracleDOCWaveHeader;
use App\OracleIdxAsrsReceive;
use App\Order;
use App\Package;
use App\Process;
use App\ProcessesContent;
use App\ProcessStatistic;
use App\Rejected;
use App\RejectedBill;
use App\RejectedBillItem;
use App\Unit;
use App\UploadFile;
use App\User;
use App\UserToken;
use App\Waybill;
use App\OraccleBasCustomer;
use App\WMSReflectReceive;
use Carbon\Carbon;
use Faker\Factory;
use Illuminate\Support\Facades\Cache;
use function Couchbase\zlibCompress;
use function Couchbase\zlibDecompress;
use Endroid\QrCode\Response\QrCodeResponse;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use function PHPSTORM_META\map;
use Zttp\Zttp;

class TestController extends Controller
{
    private $data = [];

    public function __construct()
    {
        $this->data["active_test"] = "active";
    }

    public function method(Request $request, $method)
    {
        return call_user_func([$this, $method], $request);
    }

    function packageFromLog(Request $request)
    { //x        $packagesBatch=Package::where('batch_number',$batch_number)->first();

        ini_set('max_execution_time', 2500);
        ini_set('memory_limit', '1526M');
        $uploaded = 0;
        $count = DB::table('logs')->where('operation', 'like', "%PackageController::new_%")
            ->where('created_at', '>', "2020-06-08 15:46:00")
            ->where('created_at', '<', "2020-06-08 15:47:00")
            ->where('type', "request_new_")
            ->count();
        $requests = DB::table('logs')->where('operation', 'like', "%PackageController::new_%")
            ->where('created_at', '>', "2020-06-08 15:46:00")
            ->where('created_at', '<', "2020-06-08 15:47:00")
            ->where('type', "request_new_")
            ->get();
        $requests->each(function ($request) use (&$uploaded) {
            $requestJson = json_decode($request->description, true);
            $response = Zttp::withHeaders(['content-type' => 'application/json',
            ])->post('https://was.baoshi56.com/api/thirdPart/flux/package/new',
                $requestJson
            );
            if ($response->json() && $response->json()['response'] && $response->json()['response']['flag'] == 'Y')
                $uploaded += 1;
        });
        dd($uploaded . '/' . $count);


    }

    function t2(Request $request)
    { //x        $packagesBatch=Package::where('batch_number',$batch_number)->first();

        $user = factory(User::class)->create();
        dd($user);

    }

    function setCache(Request $request)
    {
        $today = now();
        Cache::put('storedTest', $today);
        return "cacheing:'$today'<script>localStorage.setItem('storedTest','{$today}')</script>";
    }
    function getCache(Request $request)
    {
        $cache=Cache::get('storedTest');
        return "cacheing get:'$cache'<script>document.write('<br>localStorage:'+localStorage.getItem('storedTest'))</script>";
    }
    function t1(Request $request)
    {
        {
            $username=config('database.connections.oracle.username');
            $password=config('database.connections.oracle.password');
            $host=config('database.connections.oracle.host');
            $service_name=config('database.connections.oracle.service_name');
            $conn=oci_connect($username,$password,$host.'/'.$service_name); //连接oracle数据库
            $IN_WarehouseID='';
            $IN_TraceID='' ;
            $IN_WavenNo='';
            $IN_UserID='';
            $IN_Language='';
            $OUT_Return_Code='';
            $sql_sp="begin SPCUS_EDI_WCS001(:IN_WarehouseID,:IN_Process_Action_C,:IN_Process_By_C,
        :IN_WaveNO_C,:IN_OrderNO_C,:IN_OrderLineNO_C,:IN_AllocationDetailsID,:IN_Language,:IN_UserID,:OUT_Return_Code); end;";
            $stmt = oci_parse($conn, $sql_sp);
            oci_bind_by_name($stmt,':IN_Warehouse',$IN_WarehouseID);
            oci_bind_by_name($stmt,':IN_TraceID',$IN_TraceID);
            oci_bind_by_name($stmt,':IN_WavenNo',$IN_WavenNo);
            oci_bind_by_name($stmt,':IN_Language',$IN_Language);
            oci_bind_by_name($stmt,':IN_UserID',$IN_UserID);
            oci_bind_by_name($stmt,':OUT_Return_Code',$OUT_Return_Code);
            return oci_execute($stmt);

        }


    }


    function packageT(Request $request)
    {
        $package=Package::where('created_at','<','2020-07-08')->whereNotNull('logistic_number')->first();
        $package->fetchLogistic();
    }

    function injectJS(Request $request)
    {
        $items = RejectedBillItem::whereHas('rejectedBill', function ($query) {
            return $query->where('id_owner', 2);
        })->where('created_at', '>', '2019-12-23 18:11:00')->where('created_at', '<', '2019-12-24 11:25:00')->get();
        (new RejectedBillItemController())->collectionsToPackConfirm($items);
    }

    public function tj2(Request $request)
    {
        $numbersesOfBatch=OracleDOCWaveDetails::select('picktotraceid as logistic_number','act_allocation_details.orderno')->where('doc_wave_details.waveno','W190630000042')
            ->leftJoin('act_allocation_details','doc_wave_details.orderno','act_allocation_details.orderno')->get();

        $oneIdxAsrsReceive=OracleDocOrderPackingSummary::where('traceid',$numbersesOfBatch[0]['logistic_number'])->first();
        if(!$oneIdxAsrsReceive){
            $inserts='';
            $values=[];
            foreach($numbersesOfBatch as $numbers){
                $inserts .= " into doc_order_packing_summary (traceid,orderno,grossweight,addwho,addtime,editwho,edittime)values(?,?,?,?,?,?,?) ";
                $values[] = $numbers['logistic_number']??'';
                $values[] = $numbers['orderno']??'';
                $values[] = 12;
                $values[] = 'WAS';
                $values[] = Carbon::now();
                $values[] = 'WAS';
                $values[] = Carbon::now();
            }
            DB::connection('oracle')->insert("insert all {$inserts} select * from dual",$values);
        }else{
            $logisticNumbers=$numbersesOfBatch->map(function($numbers){return $numbers['logistic_number'];});
            OracleDocOrderPackingSummary::whereIn('traceid',$logisticNumbers)->update(['grossweight'=>32]);
        }
    }

    public function delme()
    {


        $fields = [
            'doc_order_header.userdefine1',
            'doc_order_header.userdefine2',
            'doc_order_header.SOReference5',
            'doc_order_header.waveno',
            'doc_order_header.orderno',
            'doc_order_header.customerid',
            'doc_order_header.Consigneename'
        ];
        if(''){
            $resultOracleObj=OracleDOCOrderHeader::select($fields)->where('orderno','SO200603004708');
        }else{
            $resultOracleObj=OracleActAllocationDetails::select($fields);
            $resultOracleObj->where('picktotraceid','546152742096');
            $resultOracleObj->leftJoin('DOC_Order_Header','act_allocation_details.orderno','doc_order_header.orderno');
        }
        $_temOracleInfo=$resultOracleObj->first();

        dd($_temOracleInfo);
    }
    public function excelIt()
    {
        $excel = new ExcelController();
        return $excel->makeExcel();
    }

    public function featureIt()
    {
        LogisticNumberFeatureController::loadRecentRejectedsToFeatures(5, 2500);
    }

    public function newSku()
    {
        $url = 'http://bswcs/api/sorting/flux/newSku';
        $response = Zttp::post($url, [
            'request' => [
                [
                    "SKU" => "1234567890",
                    "NAME" => "瑞士莲**巧克力",
                    "Alternate_SKU1" => "1122334455",
                    "GrossWeight" => "1.2",
                    "Cube" => "0.75",
                    "SKULength" => "0.25",
                    "SKUWidth" => "0.15",
                    "SKUHigh" => "0.05"
                ],
                [
                    "SKU" => "1234567892",
                    "NAME" => "跳跳饼",
                    "Alternate_SKU1" => "",
                    "GrossWeight" => "1.3",
                    "Cube" => "0.75",
                    "SKULength" => "0.25",
                    "SKUWidth" => "0.15",
                    "SKUHigh" => "0.25"
                ],
            ]
        ]);
        return $response->json();
    }

    public function changePackage()
    {
        $packages = Package::where('delivery_number', '<>', null)->where('logistic_id', null)->get();
        dd($packages);
        $packages = Package::whereRaw('delivery_number IS NOT NULL AND logistic_id IS NULL')->get();
        $logistics = Logistic::get();
        $packages->each(function ($package) use ($logistics) {
            $logistics->each(function ($logistic) use ($package) {
                if ($package->WMSReflectPackage->CarrierID == $logistic->code) {
                    $package->logistic_id = $logistic->id;
                    return;
                }
            });
        });
        return "OK";
    }

    public function tNull()
    {
    }

    public function deletePackageAuthority()
    {
        $authorities = Authority::where('name', 'like', '%包裹信息%')->get();
        $authorities->each(function ($authority) {
            $authority->delete();
        });
    }

    /*1*/
    function test(Request $request)
    {/**/
        $units=ProcessesContent::with('signCommodity')->get();
        foreach ($units as $unit){
            if ($unit->sign_commodity_name_mark)dd($unit->sign_commodity_name_mark);
        }

        header("Content-type:text/html;charset=utf-8");

        $stuid = "201301013";
        $pwd = "136";
        $uri = "127.0.0.1/login.php";//这里换成你服务器的地址
        // 参数数组
        $data = array (
            'stuid' => $stuid,
            'pwd' => $pwd
        );

        $ch = curl_init();  //初始化curl

        curl_setopt ( $ch, CURLOPT_URL, $uri );
        curl_setopt ( $ch, CURLOPT_POST, 1 );  //使用post请求
        curl_setopt ( $ch, CURLOPT_HEADER, 0 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data);  //提交数据
        curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, true);  //重定向地址也输出
        $return = curl_exec ( $ch ); //得到返回值

        curl_close ( $ch );  //关闭

        print_r($return);  //输出返回值
    }

}
