<?php

namespace app\controller;

use app\model\{DownloadModel, Category};
use page\DxtcPageA;
use think\Paginator;

class Download extends Base
{
    //列表页
    public function index($categoryId = 0)
    {
        $rule       = Category::RULE_DOWNLOAD;
        $categoryId = empty($categoryId) ? $this->request->param("category_id") : $categoryId;

        $category = Category::getById($categoryId);

        //没有category_id  则通过路由查询
        $category = $category ?: Category::getByRuleAlias($rule);

        $description = $category['seo_description'] ?: $category['title'];
        $keywords    = $category['seo_keywords'] ?: $category['title'];
        $title       = $category['seo_title'] ?: $category['title'].' | '.$this->system['seo_title'];
        $this->setSeo($title, $keywords, $description);
        $listSort = ['a.sort' => 'desc'];

        // 自定义分页驱动
        app('think\App')->bind(Paginator::class, DxtcPageA::class);

        $items = DownloadModel::getList($category['id'], $category['number'], '', [], 1, $listSort, false);
        $items->each(function ($item) {
            $item->size_text = sizeToStr($item->size);
        });
        $this->data['items']      = $items;
        $this->data['category']   = $category;
        $this->data['categoryId'] = $category['id'];
        $this->data['bodyClass']  = 'main';

        return $this->view();
    }

    public function file()
    {
        $id = input('id');
        if (!$file = DownloadModel::getById($id)) {
            return $this->error('文件不存在');
        }

        if (!file_exists(public_path().$file['file'])) {
            return $this->error('文件不存在');
        }
        return download(public_path().$file['file'], $file['title'].'.'.$file['suffix']);
    }

}