<?php

namespace App\Http\Controllers\api\thirdPart\flux;

use App\Http\Controllers\Controller;
use App\Store;
use App\WMSReflectReceive;
use App\WMSReflectReceiveSku;
use Zttp\Zttp;

class StoreController extends Controller
{


    /**
     * 入库回传给WMS
     * @param Store $store
     * @return bool
     */
    public function accomplishToWMS(Store $store, array $inputs)
    {
        $METHOD = __METHOD__;
        $FUNCTION = __FUNCTION__;
        Controller::logS(__METHOD__, __FUNCTION__, '快递入库进入WMS接口：' . $store['asn_code']);
        $wmsReceiveds = WMSReflectReceive::query()->where('ASNNO', $store['asn_code'])->get();
        if ($wmsReceiveds->isEmpty()) {
            (new Controller())->log(__METHOD__, 'error_' . __FUNCTION__, '没有本地WMS入库单');
            return false;
        }
        $success = true;
        $wmsReceiveds->each(function ($wmsReceived) use (&$store, &$amountsItem, &$success, &$inputs, $METHOD, $FUNCTION) {

            $wmsSkus = $wmsReceived->skus()->get();
            $orderNumberCode = $wmsReceived['ASNREFERENCE1'] ?? $store['order_number'];
            $amountsSku = (function () use ($wmsSkus) {
                $result = [];
                $wmsSkus->each(function ($sku) use (&$result) {
                    $result[$sku['id']] = $sku['EXPECTEDQTY_EACH'];
                });
                return $result;
            })();
            $skuStrList = [];
            $customerCode = $store->owner()->first()['code'];
            $wmsSkus->each(function (WMSReflectReceiveSku $sku) use (&$skuList, &$amountsItem, &$amountsSku, &$skuStrList, $wmsReceived, $customerCode, &$inputs) {
                $STATUS = 'ZP';
                if (isset($inputs['quality']) && $inputs['quality']
                    && $inputs['quality'] != '正品') {
                    $STATUS = 'CC';
                }
                $repositoryCode = $sku['LOTATT05'];
                if (isset($inputs['depository_code']) && $inputs['depository_code']) {
                    $repositoryCode = $inputs['depository_code'];
                }
                $skuStr = "
                        {
                            \"ORDERNUMBERCODE\": \"{$wmsReceived['ASNNO']}\",
                            \"ASNLINENO\": \"{$sku['ASNLINENO']}\",
                            \"SKUCODE\": \"{$sku['SKU']}\",
                            \"QUANTITY\": \"{$sku['EXPECTEDQTY_EACH']}\",
                            \"LOTATT04\": \"{$sku['LOTATT04']}\",
                            \"LOTATT05\": \"{$repositoryCode}\",
                            \"STATUS\": \"{$STATUS}\",
                            \"USERDEFINE1\": \"{$inputs['follow_code']}\",
                            \"USERDEFINE2\": \"\",
                            \"USERDEFINE3\": \"\",
                            \"UNIQUE_CODE_LIST\": [" .
                    "]
                        }
                    ";
                $skuStrList[] = $skuStr;
            });
            $skuStrList = implode(',', $skuStrList);
            $json = "
                {
                    \"request\": [
                        {
                            \"ORDERNUMBERCODE\": \"{$wmsReceived['ASNNO']}\",
                            \"CUSTOMERID\": \"{$wmsReceived['CUSTOMERID']}\",
                            \"ASNTYPE\": \"{$wmsReceived['ASNTYPE']}\",
                            \"ASNREFERENCE1\": \"{$wmsReceived['ASNREFERENCE1']}\",
                            \"ADDWHO\": \"WCS\",
                            \"USERDEFINE1\": \"\",
                            \"USERDEFINE2\": \"\",
                            \"USERDEFINE3\": \"\",
                            \"SKU_LIST\": [{$skuStrList}]
                        }
                    ]
                }
        ";

            $sendingJson = json_decode($json, true);
            $url = url(config('api.flux.receive.new'));
//            (new Controller())->log($METHOD,$FUNCTION,$store['asn_code'].'||' .json_encode($sendingJson));
            Controller::logS(__METHOD__, __FUNCTION__, '快递入库请求WMS接口开始：' . $store['asn_code']);
            $response = Zttp::post($url, $sendingJson);
            Controller::logS(__METHOD__, __FUNCTION__, '快递入库请求WMS接口结束：' . $store['asn_code'] . '||' . $response->body());
            $noIssues = true;
            $json = $response->json();
            if (!$json || !isset($json['Response']) || !$json['Response']['return']['returnFlag'] == '1') {
                $noIssues = false;
            }
            if ($json && isset($json['Response'])) {
                if ($json['Response']['return']['returnFlag'] == '2') {
                    (new Controller())->log($METHOD, 'error_' . $FUNCTION, $store['asn_code'] . '||' . $response->body());
                    return true;
                }
//                if(isset($json['Response']['return']['returnDesc'])&&strpos($json['Response']['return']['returnDesc'],'唯一约束')!==false){
//                    (new Controller())->log($METHOD,'error_'.$FUNCTION,$response->body());
//                    return true;
//                }
                if (isset($json['Response']['return']['errordescr']) && strpos($json['Response']['return']['errordescr'], '已完成') !== false) {
                    (new Controller())->log($METHOD, 'error_' . $FUNCTION, $store['asn_code'] . '||' . $response->body());
                    return true;
                }
            }
            if ($noIssues && $json['Response']['return']['returnFlag'] == '1') {
                $wmsReceived['is_uploaded'] = 1;
                $wmsReceived->save();
                (new Controller())->log($METHOD, 'success_' . $FUNCTION, $store['asn_code'] . '||' . $response->body());
                return true;
            } else {
                $success = false;
                (new Controller())->log($METHOD, 'error_' . $FUNCTION, $store['asn_code'] . '||' . $response->body());
            }
        });

        return $success;
    }
}
