<?php

namespace App\Http\Controllers\Business;

use App\Exports\BusinessOrderExport;
use App\Exports\OrderBlankExport;
use App\Http\Controllers\Controller;
use App\Models\BusinessOrder;
use App\Models\BusinessOrderItem;
use App\Models\GoodsSku;
use App\Models\Shop;
use App\Models\Waybill;
use App\Services\WayBill\JingDong\WayBillService;
use App\Utils\DateTimeUtils;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Resources\BusinessOrderResource;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class BusinessOrderController extends Controller
{
    public function index(Request $request)
    {
        $shopIds = Shop::query()
            ->pluck('id');
        $builder = BusinessOrder::query()
            ->with([
                'shop:id,name',
                'items:id,business_order_id,goods_name,goods_number,external_sku_id',
                "waybill"
            ])
            ->whereIn('shop_id', $shopIds)
            ->filter();
        $externalSkuIds = $request->get('external_sku_ids');
        $externalSkuId = $request->get('external_sku_id');
        if (!empty($externalSkuId)) {
            $externalSkuIds = $externalSkuId;
        }
        if ($externalSkuIds) {
            if (is_string($externalSkuIds)) {
                $externalSkuIds = explode(",", $externalSkuIds);
            }
            $ids = BusinessOrderItem::query()->whereIn('external_sku_id', $externalSkuIds)->pluck('business_order_id');
            $builder->whereIn('id', $ids);
        }

        if ($request->get("is_export")) {
            $params = $request->validate([
                'confirm_at_start' => 'required',
                'confirm_at_end' => 'required',
            ], [
                'confirm_at_start.required' => '请输入开始确认时间',
                'confirm_at_end.required' => '请输入结束确认时间',
            ]);
            $startDate = Carbon::parse($params['confirm_at_start']);
            $endDate = Carbon::parse($params['confirm_at_end']);

            if ($endDate->gt($startDate->copy()->addMonth())) {
                throw new \Exception("导出时间超出一个月");
            }

            return Excel::download(new BusinessOrderExport($builder->get()->toArray()), $startDate . '~' . $endDate . "订单数据" . '.xlsx');
        }

        $businessOrders = $builder->orderByDesc('confirm_at')
            ->paginate($request->get('per_page'));

        return BusinessOrderResource::collection($businessOrders);
    }

    private function getOrderIdsWitmGoodsNum($goodsSkuNum, $orders)
    {
        $map = [
            1 => [
                'min' => 1,
                'max' => 1
            ],
            2 => [
                'min' => 2,
                'max' => 5
            ],
            6 => [
                'min' => 6,
                'max' => 999999
            ],
        ];
        $numMap = $map[$goodsSkuNum];

        // 获取订单商品编码
        $externalSkuIds = [];
        foreach ($orders as $order) {
            foreach ($order->items as $item) {
                if ($item['external_sku_id']) {
                    $externalSkuIds [] = $item['external_sku_id'];
                }
            }
        }
        $goodsSkus = GoodsSku::query()
            ->with('combinationGoods')
            ->whereIn('external_sku_id', $externalSkuIds)
            ->get('external_sku_id');
        $goodsSkuItems = [];
        foreach ($goodsSkus as $goodsSku) {
            $goodsSkuItems[$goodsSku['external_sku_id']] = $goodsSku->combinationGoods->count() ?: 1;
        }

        $ids = [];
        foreach ($orders as $order) {
            $itemNum = 0;
            foreach ($order->items as $item) {
                if (0 === $item['cancel_status']) {
                    $itemNum = isset($goodsSkuItems[$item['external_sku_id']]) ? $itemNum + $goodsSkuItems[$item['external_sku_id']] : $itemNum + 1;
                }
            }
            if ($itemNum >= $numMap['min'] && $itemNum <= $numMap['max']) {
                $ids[] = $order['id'];
            }
        }

        return $ids;
    }

    public function exportOrderBlank(Request $request)
    {
        $orderIds = $request->get('order_ids');
        $orders = BusinessOrder::query()
            ->with([
                'items:id,business_order_id,external_sku_id,goods_number,goods_name,already_cancel_number',
                'items.goodsSkuLocation:id,external_sku_id,location,goods_name'
            ])
            ->whereIn('id', $orderIds)
            ->get(['id']);
        $distribution = [];
        $no = [];
        foreach ($orders as $key => $order) {
            $index = $key + 1;
            $no[] = 'P' . $index;
            foreach ($order->items as $item) {
                $num = $item['goods_number'] - $item['already_cancel_number'];
                $local = $item['goods_sku_location'] ? $item['goods_sku_location']['location'] : '无';
                $index = $key + 1;
                $index = "P{$index}*{$num}";
                [$goodsCode, $skuCode] = explode('_', $item['external_sku_id']);
                if (isset($distribution[$item['external_sku_id']])) {
                    $distribution[$item['external_sku_id']]['p'][] = $index;
                    $distribution[$item['external_sku_id']]['num'] += $num;
                } else {
                    $distribution[$item['external_sku_id']] = [
                        'p' => [$index],
                        'local' => $local,
                        'num' => $num,
                        'goods_name' => $item['goods_name'],
                        'goods_code' => $goodsCode,
                        'sku_code' => $skuCode,
                    ];
                }
            }
        }
        $fileName = time();
        ob_end_clean();

        return Excel::download(new OrderBlankExport($fileName, $no, $distribution), $fileName . date('Y-m-d H:i:s') . '.xlsx');
    }

    public function groupActivity(Request $request, $shopId)
    {
        $todayTime = Carbon::today()->timestamp;
        $todayTime = DateTimeUtils::getMicroTime($todayTime);

        return BusinessOrder::query()
            ->where('shop_id', $shopId)
            ->where('confirm_at', '>=', $todayTime)
            ->groupBy(['activity_no', 'activity_title'])
            ->get(['activity_title', 'activity_no'])
            ->toArray();
    }

    public function print(Request $request)
    {
        $builder = BusinessOrder::query()
            ->with('items')
            ->filter();
        $externalSkuIds = $request->get('external_sku_ids');

        if ($externalSkuIds) {
            $ids = BusinessOrderItem::query()->whereIn('external_sku_id', $externalSkuIds)->pluck('business_order_id');
            $builder->whereIn('id', $ids);
        }
        if ($ids = $request->input('ids')) {
            if (is_string($ids)) {
                $ids = explode(",", $ids);
            }
            $builder->whereIn('id', $ids);
        }
        $businessOrders = $builder->get();

        $waybill = new WayBillService();
        $waybill->setOrders($businessOrders);
        $contents = $waybill->getWayBillContents();

        return response([
            'data' => $contents
        ]);
    }

    private function combinationPrintDocuments($documents)
    {
        $documentData = [
            'data' => [
                'height' => 240,
                'list' => [
                    [
                        'fontSize' => 28,
//                        'height' => 60, // 外部的height/此处的height
                        'left' => 5,
                        'text' => '', // 备注
                        'top' => 10,
                        'width' => 550
                    ]
                ],
                'waterdata' => [
                    'text' => ''
                ],
                'width' => 560
            ],
            'templateURL' => "http://pinduoduoimg.yangkeduo.com/logistics/2019-07-14/5d7e8b5969d954539fcfba3268bbeb3a.xml" // 自定义区域模板
        ];
        $data = [];
        foreach ($documents as &$document) {
            $documentData['data']['list'][0]['text'] = $document['participate_no'] ? '[跟团号: ' . $document['participate_no'] . '] ' : '';
            $documentID = $document['documentID'];
            $count = 0;
            foreach ($document['items'] as $item) {
                $count += $item['count'];
                $documentData['data']['list'][0]['text'] .= $item['name'] . ' ' . $item['count'] . '件;';
            }
            $documentData['data']['list'][0]['text'] .= ' 总计: ' . $count . '件';
            if ($document['note']) {
                $documentData['data']['list'][0]['text'] .= ' 备注:' . $document['note'];
            }
            unset($document['documentID'], $document['items'], $document['order_id'], $document['participate_no'], $document['note']);
            $data[] = [
                'documentID' => $documentID,
                'contents' => [
                    $document,
                    $documentData
                ]
            ];
        }

        return $data;
    }

    public function printSuccess(Request $request)
    {
        $orderIds = $request->input('order_ids');
        $orderIds = explode(',', $orderIds);
        BusinessOrder::query()
            ->whereIn('id', $orderIds)
            ->update(['print_status' => 1]);
        Waybill::query()
            ->where('order_id', $orderIds)
            ->update(['status' => Waybill::$STATUS_PRINT_SUCCESS]);
        return response(['message' => 'success']);
    }
}
