<?php
namespace app\admin\controller;

use app\model\Admins;
use app\model\Onlines;
use app\model\OrderBooks;
use app\model\Orders;
use app\model\Products;
use app\model\ProductSchedules;
use Illuminate\Support\Facades\DB;
use support\Log;
use support\Request;
use support\Redis;

class ProductsController extends base {
    /**
     * 线路列表
     * @param Request $request
     * @return \support\Response
     * @throws \think\db\exception\DbException
     */
    public function list(Request $request) {
        $params = $request->all();
        $query = Products::where('status', 1)->order('id', 'desc');
        if(isset($params['product_name']) && !empty($params['product_name'])) {
            $query->whereLike('product_name', "%{$params['product_name']}%");
        }
        if(isset($params['third_product_id']) && !empty($params['third_product_id'])) {
            $query->where('third_product_id', $params['third_product_id']);
        }

        $list = $query->append(['os_name'])->paginate($request->get('limit',1000));
        return $this->success($list,null,['oss' => array_values(array_map(function ($os, $k) {
            return ['id' => $k, 'os' => $os];
        }, Orders::OSS, array_keys(Orders::OSS)))]);
    }

    public function add(Request $request) {
        if (!$request->post('os')) {
            return $this->error(2001, '请选择平台.');
        }
        if (!$request->post('product_name')) {
            return $this->error(2001, '线路名称必填');
        }
        if (!$request->post('third_product_id')) {
            return $this->error(2001, '线路id必填');
        }
        if (!$request->post('type') || !in_array($request->post('type'), [1, 2])) {
            return $this->error(2001, '请选择区域');
        }
        if (!$request->post('day') || !is_numeric($request->post('day'))) {
            return $this->error(2001, '请输入天数');
        }

        $where = ['os' => $request->post('os'), 'third_product_id' => $request->post('third_product_id')];
        $product = (new Products())->where($where)->find();
        if (empty($product)) {
            $product = new Products();
        }

        $product->os = $request->post('os');
        $product->third_product_id = $request->post('third_product_id');
        $product->product_name = $request->post('product_name');
        $product->status = 1;
        $product->type = $request->post('type');
        $product->day = $request->post('day');
        $product->night = $request->post('night');
        $product->trip_info = $request->post('trip_info');
        $product->save();
        Log::info('product:' . json_encode($product));
        return $this->success([]);
    }

    /**
     * 商品排期列表
     * @param Request $request
     * @return \support\Response
     */
    public function productSchedules(Request $request) {
        if (!$request->get('id')) {
            return $this->error(2001, '请选择商品');
        }
        $date = $request->get('date', date('Y-m'));
        $firstDay = date('Y-m-01', strtotime($date));
        $lastDay = date('Y-m-t', strtotime($date));
        // 排期列表
        $productSchedules = ProductSchedules::where('product_id', $request->get('id'))
            ->whereBetween('date', [$firstDay, $lastDay])
            ->select()
            ->toArray();
        $productSchedules = array_column($productSchedules, null, 'date');

        // 预约列表
        $books = OrderBooks::join('orders', 'orders.id=order_books.order_id')
                ->whereBetween('order_books.travel_date', [$firstDay, $lastDay])
                ->group(['order_books.travel_date', 'orders.product_id'])
                ->fieldRaw('order_books.travel_date, orders.product_id, count(1) as num')
                ->select()
                ->toArray();
        $books = array_column($books, null, 'travel_date');

        // 遍历日期范围
        $dates = [];
        $firstDay = strtotime($firstDay);
        $lastDay = strtotime($lastDay);
        for ($currentDay = $firstDay; $currentDay <= $lastDay; $currentDay = strtotime('+1 day', $currentDay)) {
            $date = date('Y-m-d', $currentDay);
            $current = [
                'date' => $date,
                'books_num' => 0,
                'left_num' => 0
            ];
            // 预约数量
            if (isset($books[$date])) {
                $current['books_num'] = $books[$date]['num'];
            }
            // 剩余数量
            if (isset($productSchedules[$date]) && $productSchedules[$date]['num'] > 0) {
                $leftNum = $productSchedules[$date]['num'] - $current['books_num'];
                $current['left_num'] = $leftNum ?: 0;
            }
            array_push($dates, $current);
        }

        return $this->success($dates);
    }

    /**
     * 商品排期
     * @param Request $request
     * @return \support\Response
     */
    public function addProductSchedules(Request $request) {
        if (!$request->post('id')) {
            return $this->error(2001, '请选择商品');
        }
        if (!$request->post('date')) {
            return $this->error(2001, '选择设置日期');
        }
        if (!$request->post('num') || !is_numeric($request->post('num'))) {
            return $this->error(2001, '数量格式异常');
        }
        $thirdProductId = Products::where('id', $request->post('id'))->value('third_product_id');
        if (!$thirdProductId) {
            return $this->error('商品信息未找到');
        }

        $where = ['product_id' => $request->post('id'), 'date' => $request->post('date')];
        $productSchedules = (new ProductSchedules())->where($where)->find();
        if (empty($productSchedules)) {
            $productSchedules = new ProductSchedules();
        }
        $productSchedules->product_id = $request->post('id');
        $productSchedules->date = $request->post('date');
        $productSchedules->num = $request->post('num');
        $productSchedules->third_product_id = $thirdProductId;
        $productSchedules->save();
        return $this->success([]);
    }
}