<?php
namespace App\Services\Views;

use Cache;
use App\Models\Link;
use App\Models\Setting;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

class ListService
{
    use \App\Traits\ContentTrait;
    
    //内容列表
    public function lists($table = 'product', $pid = 0, $num = 20, $isPage = 1, $attribute = '', $order = 'orders', $sort = 'DESC')
    {
        $content = self::model($table)::with(['cates', 'description'])->flag();

        if ($table == 'news') {
            $content = $content->where('created_at', '<', Carbon::now());
        }

        if ($attribute) {
            $arr = explode('-', $attribute);
            if (count($arr) == 2) {
                $content = $content->where($arr[0], $arr[1]);
            } else {
                $content = $content->where($attribute, 1);
            }
        }

        $content = $pid ? $content->whereIn('pid', $this->ids($table.'-cate', $pid)) : $content;

        $content = $content->orderBy($order, $sort);

        $content = $isPage == 1 ? $content->paginate($num) : $content->limit($num)->get();

        return $content;
    }

    private function ids($table, $pid)
    {
        $cate  = self::model($table)::flag()->find($pid);

        if ($cate) {
            $ids   = $cate->getDescendantsAndSelf(['id'])->toArray();
            return array_column($ids, 'id');
        }

        return [];
    }

    //单页列表
    public function page($pid = 1)
    {
        static $data = null;

        $data[$pid] = $data[$pid] ?? self::model('page')::where('pid', $pid)->with('description')->flag()->oldest('orders')->get();

        return $data[$pid];
    }

    //上一页 | 下一页
    public function pageNextPrev($model = 'product', $cid = '', $id = '',$nextPrev = 'prev', $orderField = 'id') 
    {
        $langs = trans("language::system");

        $dire  = strtolower($nextPrev) == 'prev' ? '<' : '>';

        $table = self::model($model)::flag()->with('description');

        if ($model == 'news') {
            $table = $table->where('created_at', '<', Carbon::now());
        }

        $prev  = $table->where($orderField, $dire, $id);

        $prev = $cid ? $prev->where('pid', $cid) : $prev;

        $prev = $dire == '<' ? $prev->latest($orderField)->first() : $prev->oldest($orderField)->first();

        if ($prev) {
            $url      = url("{$model}/{$prev->slug}.html");
            $title    = $prev->description->title ?? '';
            $pageHtml = "<a href='{$url}' class='p-prev'>{$title}</a>";
        } else {
            $pageHtml = $langs['no'] ?? '';
        }
        
        return $pageHtml;
    }

    /**
     * @param int $status
     * @return 友情链接列表
     */
    public function link($status = 0)
    {
        $data = Link::lang()->oldest('orders');

        if ($status > 0) {
            $where = $status == 1 ? '=' : '!=';
            $data = $data->where('img', $where, null);
        }

        $data = $data->get();

        if (config('lang') == config('setting.lang') && $status != 2) {
            $outsideData = $this->getLink();
            $data = array_merge($data ? $data->toArray() : [], $outsideData);

            foreach ($data as $key => $value) {
                $data[$key] = (object) $value;
            }
        }

        return $data;
    }

    public function getLink()
    {
        $cacheKey = 'link_cache';
        $data = Cache::get($cacheKey);

        if ($data) {
            return $data;
        }

        $data = [];
        $httpClient = new \GuzzleHttp\Client();

        try {
            $res = $httpClient->get(config('setting.api_url') . '/links', [
                'headers' => [
                    'token' => Setting::get('apptoken'),
                    'Accept' => 'application/json'
                ]
            ]);

            $content = json_decode($res->getBody()->getContents());

            if ($content->status == 'success') {
                foreach ($content->data as $key => $value) {
                    $data[$key]['title'] = $value->site->keyword;
                    $data[$key]['url'] = 'http://' . str_replace(['http://', 'https://'], '', $value->site->url);
                    $data[$key]['content'] = '';
                    $data[$key]['img'] = '';
                }

                Cache::put($cacheKey, $data, 60 * 24);
            }
        } catch (\Exception $e) {

        }

        return $data;
    }

    /**
     * 获取购物车数量
     *
     * @return array
     */
    public function getCartNum()
    {
        if (Auth::member()->get()) return self::model('cart')::where('member_id', Auth::member()->get()->id)->count();

        return 0;
    }

}