<?php

namespace App\Imports;

use App\Events\AddOrUpdateOrderIssues;
use App\OracleActAllocationDetails;
use App\OracleDOCOrderHeader;
use App\Order;
use App\OrderIssue;
use App\OrderIssueProcessLog;
use App\OrderIssueType;
use App\OrderPackage;
use App\Services\OrderService;
use App\Services\RejectedService;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithMultipleSheets;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;

HeadingRowFormatter::default('none');

class OrderIssueImport implements ToCollection, WithHeadingRow, WithMultipleSheets
{

    public function Collection(Collection $collection)
    {
        /** @var OrderService $orderService */
        $orderService = app('OrderService');

        $endIS = false;
        $headerRow =  $collection->toArray()[0];
        if (!isset($headerRow['原始运单号']) || !isset($headerRow['情况说明']) || !isset($headerRow['问题类别'])) {
            Cache::put('error', '请检查您第一行标题是否存在原始运单号，情况说明，问题类别');
        } else {
            $endIS = true;
        }
        $exception = [];
        $sum = 2;
        $rejectedService = new RejectedService();
        if ($endIS) {
            foreach ($collection as $row) {
                $logistic_number = trim($row['原始运单号'], ' ');
                if (!$row['原始运单号']) {
                    array_push($exception, ['第' . $sum . '行数据运单号为空!']);
                    $sum++;
                    continue;
                } else if (!$row['情况说明']) {
                    array_push($exception, ['第' . $sum . '行问题说明为空!']);
                    $sum++;
                    continue;
                } else if (!$row['问题类别']) {
                    array_push($exception, ['第' . $sum . '行问题类别为空!']);
                    $sum++;
                    continue;
                }
                $order_type = OrderIssueType::query()->where('name', $row['问题类别'])->first();
                if (!$order_type) {
                    array_push($exception, ['原始运单号' . $row['原始运单号'] . '对应的的问题件类别不存在']);
                    continue;
                }
                $count = OracleDOCOrderHeader::query()->where('soreference5', $logistic_number)->count();
                $detailCount = OracleActAllocationDetails::query()->where('picktotraceid', $logistic_number)->count();
                if (!$count && !$detailCount) {
                    array_push($exception, ['原始运单号' . $row['原始运单号'] . '对应的WMS运单不存在']);
                    $sum++;
                    continue;
                }
                $orderPackage = OrderPackage::query()->where('logistic_number', $logistic_number)->first();
                if ($orderPackage) {
                    $order = Order::query()->where('id', $orderPackage['order_id'])->first();
                    if ($order) {
                        $orderIssue = OrderIssue::query()->where('order_id', $order['id'])->first();
                        if ($orderIssue) {
                            array_push($exception, ['原始运单号' . $row['原始运单号'] . '对应的问题件已存在']);
                            continue;
                        }
                    }
                }
                $client_no = null;
                $order_nos = [];
                if ($count) {
                    $orderHeader = OracleDOCOrderHeader::query()->where('soreference5', $logistic_number)->first();
                    $client_no = $orderHeader['soreference1'];
                    $order_nos[] = $orderHeader['orderno'];
                } else if ($detailCount) {
                    $detail = OracleActAllocationDetails::query()->where('picktotraceid', $logistic_number)->first();
                    $orderHeader = OracleDOCOrderHeader::query()->where('orderno', $detail['orderno'])->first();
                    $client_no = $orderHeader['soreference1'];
                    $order_nos[] = $orderHeader['orderno'];
                }
                $orderService->syncOrderInfoByWmsOrderNos($order_nos);
                $order = Order::query()->where('code',$order_nos[0])->first();
                $orderIssue = OrderIssue::query()->where('order_id', $order['id'])->first();
                $rejectedBill = $rejectedService->getRejectedByClientNo($client_no);
                if ($orderIssue) {
                    array_push($exception, ['原始运单号' . $row['原始运单号'] . '对应的问题件已存在']);
                    $sum++;
                    continue;
                }
                $arr = ['order_id' => $order['id'], 'order_issue_type_id' => $order_type['id'],'result_explain'=>$row['情况说明'],'imported_status'=>'导入未处理'];
                if ($rejectedBill) {
                    $arr['rejected_bill_id'] = $rejectedBill['id'];
                }

                /** @var OrderIssue $orderIssue */
                $orderIssue = OrderIssue::query()->create($arr);
                event(new AddOrUpdateOrderIssues([$order['id']]));
                $orderIssue->syncRejectedBills();
                $orderIssue->syncRejectingStatus();

                if ($orderIssue) {
                    array_push($exception, ['订单' . $row['原始运单号'] . '问题件创建成功！']);
                    OrderIssueProcessLog::query()->create(['order_issue_id' => $orderIssue['id'], 'user_id' => Auth::user()['id'], 'content' => '', 'type' => '创建']);
                } else {
                    array_push($exception, ['订单' . $row['原始运单号'] . '问题件创建失败']);
                }
                $sum++;
            }
        }
        Cache::put('exception', $exception, 86400);
    }

    /**
     * 该方法是实现上传文件只选中 第一个表
     * ExcelImport 默认是有多少个分表就执行多少次的分表
     * @return OrderIssueImport[]|array
     */
    public function sheets(): array
    {
        return [0 => new OrderIssueImport()];
    }
}
