<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2019/12/5
 * Time: 17:44
 */

namespace app\admin\controller;

use app\admin\controller\base\Permissions;
use app\common\model\Article as articleModel;
use app\common\model\ArticleCate as articleCateModel;
use app\common\model\Catalog as cataLogModel;
use app\common\model\Templet as templetModel;
use app\common\service\CmsService;
use file\PathHelper;
use paginate\Bootstrap;
use think\Db;

class Catalog extends Permissions
{
    /**
     * index2 使用新的树形表格组件
     * @return array|mixed
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $model = new cataLogModel();
            $data = $model->order('pid,sort desc,id asc')->select();
            foreach ($data as $k => $v) {
                /**@var cataLogModel $v */
                $v['type_text'] = $v->type_text;
                $v['article_count'] = $v->article_count ?: '';
                $v['tpath'] = $v->tpath();
                $data[$k] = $v;
            }
            return array('code' => 0, 'count' => count($data), 'data' => $data, "tip" => "操作成功!");
        } else {
            return $this->fetch();
        }
    }


    public function publish()
    {
        $id = $this->request->param('id', 0, 'intval');
        $post = $this->request->post();
        $model = new cataLogModel();

        if ($this->request->isPost()) {
            $validate = new \think\Validate([
                ['title|栏目名称', 'require'],
                ['catalog_templet|栏目模板', 'requireIf:type,0|requireIf:type,1'],
                ['article_templet|文章模板', 'requireIf:type,1'],
                ['path|栏目路径', 'requireIf:type,0|requireIf:type,1'],
                ['article_rule|文章路径', 'requireIf:type,1'],
                ['articlelist_rule|列表页路径', 'requireIf:type,1'],
            ]);
            if (!$validate->check($post)) {
                $this->error('提交失败:' . $validate->getError());
            }
            $post['path'] = trim($post['path']);
            $post['path'] = empty($post['path']) ? "" : appendStartDS(trim($post['path']), '/');
            $post['catalog_templet'] = trim($post['catalog_templet']);
            $post['article_templet'] = trim($post['article_templet']);
            $post['article_rule'] = trim($post['article_rule']);
            $post['articlelist_rule'] = trim($post['articlelist_rule']);
            $post['articlelist_rows'] = empty($post['articlelist_rows']) ? 10 : $post['articlelist_rows'];
        } else {
            $pid = $this->request->param('pid', 0, 'intval');
            $this->assign('pid', $pid);
            $this->assign("templets", templetModel::getTemplets());
            $this->assign('cates', $model->treelistForCatalog());
            $this->assign('types', cataLogModel::TYPES);
        }

        if ($id > 0) {
            //修改
            $item = $model->where('id', $id)->find();
            if (empty($item)) {
                $this->error('id不存在');
            }
            if ($this->request->isPost()) {
                if ($id == $post['pid']) {
                    $this->error('上级节点不能选自己');
                }
                //更新tree_path
                $post = $this->updatePath($post, $id);
                if (false == $model->allowField(true)->save($post, ['id' => $id])) {
                    $this->error('修改失败');
                } else {
                    $this->success('修改成功', 'index');
                }
            } else {
                $this->assign('item', $item);
                return $this->fetch();
            }
        } else {
            //新增
            if ($this->request->isPost()) {
                $post['status'] = $model::STATUS_OPEN;
                if (false == $model->allowField(true)->save($post)) {
                    $this->error('添加失败');
                } else {
                    $cate = $model;
                    //更新tree_path
                    $post = $this->updatePath($post, $model->id);
                    if (false == $cate->save(['tree_path' => $post['tree_path']])) {
                        $this->error('更新tree_path失败');
                    }
                    $this->success('添加成功', 'index');
                }
            } else {
                return $this->fetch();
            }
        }
    }

    /**
     * 更新tree_path
     * @param $post
     * @param $id
     * @return mixed
     */
    private function updatePath($post, $id)
    {
        if ($post['pid']) {
            $pdoc = (new cataLogModel())->find($post['pid']);
            if (!$pdoc) {
                $this->error('该上级节点不存在,请重新选择');
            }
            $post['tree_path'] = $pdoc->tree_path . '-' . $id;
        } else {
            $post['tree_path'] = $id;
        }
        return $post;
    }

    /**
     * 删除
     */
    public function delete()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->param('id', 0, 'intval');
            $exits = cataLogModel::get(['pid' => $id]);
            if ($exits) {
                $this->error('请先删除子节点');
            }
            if (false == Db::name('catalog')->where('id', $id)->delete()) {
                $this->error('删除失败');
            } else {
                $this->success('删除成功', 'index');
            }
        }
    }

    /**
     * 审核
     */
    public function status()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (false == Db::name('catalog')->where('id', $post['id'])->update(['status' => $post['status']])) {
                $this->error('设置失败');
            } else {
                $this->success('设置成功', 'index');
            }
        }
    }

    /**
     * 排序
     */
    public function sort()
    {
        if ($this->request->isPost() && $this->request->has('ids')) {
            $post = $this->request->post();
            $i = 0;
            foreach ($post['ids'] as $k => $id) {
                $sort = Db::name('catalog')->where('id', $id)->value('sort');
                $newsort = $post['sorts'][$k]??$sort;
                if ($sort != $newsort) {
                    if (false == Db::name('catalog')->where('id', $id)->update(['sort' => $newsort])) {
                        $this->error('更新失败');
                    } else {
                        $i++;
                    }
                }
            }
            if (empty($i)) {
                $this->error('没有更新排序', 'index');
            }
            $this->success('成功更新' . $i . '个排序', 'index');
        } else {
            $this->error('无数据更新', 'index');
        }
    }

    /**
     * 更新所有节点tree_path
     * admin/catalog/updateTreePath
     */
    public function updateTreePath()
    {
        (new cataLogModel())->updateTreePath();
        return $this->success();
    }

    //预览
    public function perview()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id) {
            /** @var cataLogModel $catalog */
            $catalog = (new cataLogModel())->where('id', $id)->find();
            try {
                $cate = $catalog->getFirstArticleCate();
            } catch (\Exception $e) {
                $cate = null;
            }
            return (new CmsService())->perviewCatalog($catalog, $cate);
        }
        $this->error('预览失败:id is null');
    }


    /**
     * @param $where array
     * @param $catalog cataLogModel
     * @param $tid int
     * @param $cate articleCateModel
     */
    private function exportArticle($where, $catalog, $tid, $cate)
    {
        $replace = CmsService::getArticleReplace();
        $service = new CmsService();
        $articleModel = new articleModel();
        $catalogPath = $catalog->getRealPath();
        $total = $articleModel->where($where)->where($catalog->articlelist_where)->count();
        $listRows = $catalog->articlelist_rows??10;//分页
        $orderby = $catalog->articlelist_sort??'create_time desc';//排序

        if ($total) {
            $lastPage = (int)ceil($total / $listRows);
            //分页
            for ($page = 1; $page <= $lastPage; $page++) {

                $articleCatePath = articleCateModel::getRulePath($catalogPath, $catalog->articlelist_rule, $catalog->id, $tid, $page);
                $articleList = $articleModel->where($where)->where($catalog->articlelist_where)->page($page, $listRows)->order($orderby)->select();
                $prefix = isset($replace['_ROOT_']) ? $replace['_ROOT_'] : '_ROOT_';
                $paginate = new Bootstrap($articleList, $listRows, $page, $total, false, ["path" => $prefix . CmsService::getPaginatePath($catalog, $tid)]);

                $service->info("       ├─ 列表页:" . $articleCatePath);
                $content = $this->fetch($catalog->getCatalogTemplet()->getRealPath(), ['catalog' => $catalog, 'articleCate' => $cate, 'paginate' => $paginate], $replace);
                $service->createFile($articleCatePath, $content);

                foreach ($articleList as $article) {
                    /**@var articleModel $article */
                    $articlePath = $article->getRulePath($catalogPath, $catalog->article_rule);
                    $content = $this->fetch($catalog->getArticleTemplet()->getRealPath(), ['catalog' => $catalog, 'article' => $article, 'articleCate' => $cate], $replace);
                    $service->info("           ├─ 文章:" . $articlePath);
                    $service->createFile($articlePath, $content);
                }
            }
        }

        $articleCatePath = articleCateModel::getRulePath($catalogPath, $catalog->articlelist_rule, $catalog->id, $tid);
        $content = file_exists($articleCatePath) ? $this->fetch($articleCatePath, [], $replace) : CmsService::errorHtml($articleCatePath);
        $dir = PathHelper::getDir($articleCatePath);
        $service->info("       ├─ 列表默认页:" . $dir . DS . "index.html");
        $service->createFile($dir . DS . "index.html", $content);
    }

    /**
     * 生成文章列表&文章页
     * @param $catalog cataLogModel
     * @param $cate
     */
    private function exportArticleList($catalog, $cate)
    {
        $where = [
            'article_cate_id' => $cate->id,
            'status' => articleModel::STATUS_OPEN,
        ];
        $this->exportArticle($where, $catalog, $cate->id, $cate);
    }


    /**
     * 生成栏目文章页
     * @param $catalog cataLogModel
     */
    private function exportCatalogArticle($catalog)
    {
        $where = [
            'catalog_id' => $catalog->id,
            'status' => articleModel::STATUS_OPEN,
        ];
        $this->exportArticle($where, $catalog, 0, null);
    }


    /**
     * 生成静态文件
     */
    public function exportHtml()
    {
        if (!$this->request->isAjax() && !$this->request->isCli()) {
            return;
        }

        if ($this->request->isCli()) {
            $ids = (new cataLogModel())->column('id');
        } else {
            $post = $this->request->param();
            if (!isset($post['ids']) || empty($post['ids'])) {
                $this->error('请选择栏目');
            }
            $ids = $post['ids'];
        }

        clear_temp_cache();//预览模式和生成模式切换时会缓存

        //全局对象
        $cataLogModel = new cataLogModel();
        $articleModel = new articleModel();
        $articleCateModel = new articleCateModel();
        $service = new CmsService();
        $this->assign([
            'cataLogModel' => $cataLogModel,
            'articleCateModel' => $articleCateModel,
            'articleModel' => $articleModel,
        ]);

        $catalogs = $cataLogModel->where(['id' => ['in', $ids], 'status' => cataLogModel::STATUS_OPEN])->order('sort asc')->select();
        $replace = CmsService::getArticleReplace();

        try {
            /**@var cataLogModel $catalog */
            foreach ($catalogs as $catalog) {

                $service->info("栏目:" . $catalog->title);
                if ($catalog->type == cataLogModel::TYPE_DIRECTORY) {
                    $service->info("  ├─ 类型:目录");
                    continue;
                }

                $catalogPath = $catalog->getRealPath();

                if ($catalog->type == cataLogModel::TYPE_CATALOG) {
                    $service->info("  ├─ 类型:栏目页:" . $catalogPath);
                    $content = $this->fetch($catalog->getCatalogTemplet()->getRealPath(), ['catalog' => $catalog], $replace);
                    $service->createFile($catalogPath, $content);
                } else {
                    $articleCates = $catalog->articleCates;
                    if (count($articleCates) > 0) {
                        $service->info("  ├─ 类型:文章列表+分类");
                        foreach ($articleCates as $cate) {
                            $service->info("    ├─ 分类:" . $cate->title);
                            $this->exportArticleList($catalog, $cate);
                        }
                        $service->info("      ├─ 栏目默认页:" . $catalogPath);
                        $articleCatePath = articleCateModel::getRulePath($catalogPath, $catalog->articlelist_rule, $catalog->id, $articleCates[0]->id);
                        $content = file_exists($articleCatePath) ? $this->fetch($articleCatePath, [], $replace) : CmsService::errorHtml($articleCatePath);
                        $service->createFile($catalogPath, $content);
                    } else {
                        $service->info("  ├─ 类型:文章列表+栏目");
                        if ($catalog->article_count > 0) {
                            $this->exportCatalogArticle($catalog);
                        } else {
                            $service->info("      ├─ 栏目默认页:" . $catalogPath);
                            $content = $this->fetch($catalog->getCatalogTemplet()->getRealPath(), ['catalog' => $catalog], $replace);
                            $service->createFile($catalogPath, $content);
                        }
                    }
                }
            }

            if (!$this->request->has('delete')) {
                $service->copyUploads();
            }

        } catch (\Exception $e) {
            CmsService::errorlog($e);
            if ($this->request->isCli()) {
                return $service->info('执行失败 ' . $e->getMessage());
            } else {
                $this->error('执行失败 ' . $e->getMessage());
            }
        }

        if ($this->request->isCli()) {
            $service->info('执行成功');
        } else {
            $this->success('执行成功', 'index');
        }
    }
}