<?php

namespace app\admin\controller\order;

use app\admin\service\order\PayDetailService;
use app\admin\validate\order\OrderValidate;
use app\controller\Curd;
use app\model\Goods;
use app\model\Order;
use app\model\OrderSheet;
use app\model\SysDept;
use support\Request;
use support\Response;
use Tinywan\Jwt\JwtToken;

class DishesController extends Curd
{
    public function __construct()
    {
        $this->model = new Order();
        $this->validate = true;
        $this->validateClass = new OrderValidate();
    }

    /**
     * @Desc 列表
     * @Author Gorden
     * @Date 2024/3/28 15:01
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function select(Request $request): Response
    {
        // 缓存的用户信息
        $user = JwtToken::getExtend();
        $timeType = $request->get('time_type', 'add');
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);

        $where['order_classify'] = 'DISHES';
        if (!empty($where['order_addtimes']) && $timeType == 'add') {
            $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
            $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
        }
        // 场所
        $premise = $request->get('premises');
        if (!empty($user['join_user_dept_id']) && SysDept::where('dept_id', $user['join_user_dept_id'])->where('dept_category', '餐厅')->exists()) {
            $where['json'] = ['order_config_json', 'dept', $user['join_user_dept_id']];
        } else if (!empty($premise)) {
            $where['json'] = ['order_config_json', 'dept', $premise];
        }

        if (!empty($where['order_status_system']) && $where['order_status_system'] == 'AWAITING') {
            $where['order_status_system'] = 'PAYING';
            $where['order_status_payment'] = 'AWAITING';
        }


        $order = $request->get('order', 'desc');
        $orderId = $request->get('order_id', '');

        $field = $field ?? 'order_addtimes';
        if (!empty($where['order_status_system']) && in_array($where['order_status_system'], ['PENDING', 'WAITING', 'SENDING', 'RECVING', 'SIGNED', 'CONFIRM'])) {
            $where['order_is_complete'] = 'N';
            $where['order_category'] = ['<>', 'RETURN'];
        }
        $orderIds = [];
        if (!empty($orderId)) {
            $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
                ->where('order_classify', 'DISHES')
                ->pluck('order_id')
                ->toArray();
        }
        $goodsName = $request->get('goods_name', '');
        if (!empty($goodsName)) {
            $goodsIds = Goods::where('goods_classify', 'MEALS')
                ->where('goods_name', 'like', '%' . $goodsName . '%')
                ->pluck('goods_id')
                ->toArray();
            $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
            if (!empty($where['order_id'])) {
                $orderIds = array_intersect($orderIds, $goodsOrderIds);
            } else {
                $orderIds = $goodsOrderIds;
            }
        }
        // 付款时间
        $payOrderIds = [];
        if ($timeType == 'pay' && !empty($where['order_addtimes'])) {
            $payTimeStart = strtotime($where['order_addtimes'][0]);
            $payTimeEnd = strtotime($where['order_addtimes'][1]);
            unset($where['order_addtimes']);
            $payOrderIds = PayDetailService::getPayOrderId($payTimeStart, $payTimeEnd, ['MEALS','DISHES']);
        }
        if ((!empty($orderId) || !empty($goodsName)) && $timeType == 'pay') {
            $orderIds = array_intersect($orderIds, $payOrderIds);
            $where['order_id'] = ['in', implode(',', $orderIds)];
        } elseif (!empty($orderId) || !empty($goodsName)) {
            $where['order_id'] = ['in', implode(',', $orderIds)];
        } elseif ($timeType == 'pay') {
            $where['order_id'] = ['in', implode(',', $payOrderIds)];
        }

        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model->with([
            'sheets' => function ($query) {
                $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id', 'order_sheet_num', 'order_sheet_price');
            },
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile');
            },
            'cert' => function ($query) {
                $query->select('join_cert_member_id', 'member_cert_name');
            },
            'express' => function ($query) {
                $query->select('join_express_order_id', 'order_express_type');
            }
        ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id');
        foreach ($where as $column => $value) {
            if (is_array($value)) {
                if ($value[0] === 'like' || $value[0] === 'not like') {
                    $model = $model->where($column, $value[0], "%$value[1]%");
                } elseif ($column == 'json') {
                    $model = $model->where(function ($query) use ($value){
                        $query->whereJsonContains($value[0] . '->' . $value[1], intval($value[2]))
                            ->orWhereJsonContains($value[0] . '->' . $value[1], strval($value[2]));
                    });
//                    $model = $model->whereJsonContains($value[0] . '->' . $value[1], intval($value[2]));
                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
                    $model = $model->where($column, $value[0], $value[1]);
                } elseif ($value[0] == 'in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereIn($column, $valArr);
                } elseif ($value[0] == 'not in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereNotIn($column, $valArr);
                } elseif ($value[0] == 'null') {
                    $model = $model->whereNull($column);
                } elseif ($value[0] == 'not null') {
                    $model = $model->whereNotNull($column);
                } elseif ($value[0] !== '' || $value[1] !== '') {
                    $model = $model->whereBetween($column, $value);
                }
            } else {
                $model = $model->where($column, $value);
            }
        }
        if ($field) {
            $model = $model->orderBy($field, $order);
        }
        $model = $model->select('order.*', 'order_return.orders_return_id', 'order_return.join_return_order_id', 'order_return.order_return_status', 'order_return.order_return_apply_json', 'order_return.order_return_refund_json', 'order_return.order_return_remark');
        return $model;
    }

    public function afterQuery($items)
    {
        foreach ($items as &$item) {
            $sheetDeng = '';
            $item['sheet'] = $item['sheets'][0] ?? [];
            if (!empty($item['sheet'])) {
                $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();
                if (count($item['sheets']) > 1 && $goods && $goods->goods_classify == 'MEALS') {
                    $sheetDeng = ' 等餐品';
                }
                $item['sheet']['goods_name'] = ($goods && $goods->goods_name) ? $goods->goods_name . $sheetDeng : '';
                $item['sheet']['goods_classify'] = $goods->goods_classify ?? '';
                $item['sheet']['order_sheet_num'] = intval($item['sheet']['order_sheet_num']);
            }
            unset($item['sheets']);
            $item['order_return_amount'] = 0;
            if (isset($item['orders_return_id'])) {
                $item['return'] = [
                    'orders_return_id' => $item['orders_return_id'],
                    'join_return_order_id' => $item['join_return_order_id'],
                    'order_return_status' => $item['order_return_status'],
                    'order_return_apply_json' => $item['order_return_apply_json'],
                    'order_return_remark' => $item['order_return_remark']
                ];
                if (!empty($item['order_return_refund_json'])) {
                    $refundJson = json_decode($item['order_return_refund_json'], true);
                    if (isset($refundJson['amount'])) {
                        $item['order_return_amount'] = $refundJson['amount'];
                    }
                }
            }
            $item['payDetail'] = PayDetailService::getPayWay($item['order_groupby'], $item['order_id']);
        }

        return $items;
    }
}