<?php

namespace app\workerapi\lists\shops;

use app\common\model\shops\ShopOrders;
use app\workerapi\lists\BaseWorkerDataLists;
use think\db\Query;

class ShopOrderLists extends BaseWorkerDataLists
{
    protected $count = 0;

    public function querySearch(): array
    {
        $where = [];
        $where[] = ['worker_id', '=', $this->userId];
        if (isset($this->params['shop_order_type']) && $this->params['shop_order_type'] != 'all') {
            $where[] = ['shop_order_type', '=', $this->params['shop_order_type']];
        }
        return $where;

    }

    public function lists(): array
    {
        $lists = ShopOrders::with(['orderGoods' => function (Query $query) {
            $query->field(['sn', 'goods_name', 'goods_image', 'number', 'service_fee', 'service_total', 'company_name', 'delivery_type', 'shop_goods_type', 'goods_specs_inventory_id', 'specs_type', 'custom_attribute_items', 'specs'])->append(['spec_arr', 'delivery_type_text', 'shop_goods_type_text']);
            $query->with(['goodsSpecsInventory' => function (Query $query) {
                $query->field(['id', 'remaining_inventory']);
            }]);
        }])->where($this->querySearch())
            ->when(!empty($this->params['name']), function (Query $query) {
                $query->where(function (Query $query) {
                    $name = '%' . $this->params['name'] . '%';
                    $query->where('sn', 'like', '%' . $name . '%');
                    $query->whereOr('EXISTS(SELECT 1 FROM la_shop_order_goods og 
                               left JOIN la_shop_orders o ON og.sn = o.sn 
                               WHERE og.goods_name LIKE "' . $name . '" and o.sn=la_shop_orders.sn) ');
                    $query->whereOr(' EXISTS(SELECT 1 FROM la_shop_order_logistic ol 
                               left JOIN la_shop_orders o ON ol.order_id = o.id 
                               WHERE ol.logistic_number LIKE "' . $name . '" and ol.order_id=la_shop_orders.id)');
                });
            })
            ->field(['id, sn, real_name, mobile, address, pay_time, paw_way, pay_status, refund_status, create_time, amount_total, address_json, order_amount,shop_order_type'])
            ->append(['pay_way_text', 'pay_status_text', 'refund_status_text'])
            ->limit($this->limitOffset, $this->limitLength)
            ->order('id', 'desc')
            ->select()
            ->toArray();
        foreach ($lists as &$item) {
            $companyNameArr = array_unique(array_column($item['orderGoods'], 'company_name'));
            $orderGoodsArr = [];
            foreach ($companyNameArr as $val) {
                $orderGoods = [];
                foreach ($item['orderGoods'] as $goodVal) {
                    $goodVal['remaining_inventory'] = isset($goodVal['goodsSpecsInventory']['remaining_inventory']) ? $goodVal['goodsSpecsInventory']['remaining_inventory'] : 0;
                    if ($val == $goodVal['company_name']) {
                        unset($goodVal['goodsSpecsInventory'], $goodVal['custom_attribute_items'], $goodVal['specs'], $goodVal['sn'], $goodVal['goods_specs_inventory_id'], $goodVal['company_name']);
                        $orderGoods[] = $goodVal;
                    }
                }
                if (!empty($orderGoods)) {
                    $orderGoodsArr[] = [
                        'company_name' => $val,
                        'goods' => $orderGoods
                    ];
                }
            }
            $item['orderGoods'] = $orderGoodsArr;
        }
        return $lists;
    }

    public function count(): int
    {
        return ShopOrders::where($this->querySearch())
            ->when(!empty($this->params['name']), function (Query $query) {
                $query->where(function (Query $query) {
                    $name = '%' . $this->params['name'] . '%';
                    $query->where('sn', 'like', '%' . $name . '%');
                    $query->whereOr(' EXISTS(SELECT 1 FROM la_shop_order_goods og 
                               left JOIN la_shop_orders o ON og.sn = o.sn 
                               WHERE og.goods_name LIKE "' . $name . '" and o.sn=la_shop_orders.sn)');
                    $query->whereOr(' EXISTS(SELECT 1 FROM la_shop_order_logistic ol 
                               left JOIN la_shop_orders o ON ol.order_id = o.id 
                               WHERE ol.logistic_number LIKE "' . $name . '" and ol.order_id=la_shop_orders.id)');
                });
            })->count();
    }
}