<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2022/11/25
 * Time: 15:10
 */


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\ArticleCate as cateModel;
use app\common\model\Attachment as attachmentModel;
use app\common\model\Catalog as cataLogModel;
use app\common\model\Templet as templetModel;
use app\common\service\CmsService;
use file\FileHelper;
use think\Db;
use think\Exception;
use think\Log;
use think\Session;

class Article extends Permissions
{
    public function index()
    {
        $cateModel = new cateModel();
        $catalogModel = new cataLogModel();
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $where = [];
            if (isset($post['id']) and !empty($post['id'])) {
                $where['id'] = $post['id'];
            }
            if (isset($post['keywords']) and !empty($post['keywords'])) {
                $where['title'] = ['like', '%' . $post['keywords'] . '%'];
            }
            if (isset($post['article_cate_id']) and $post['article_cate_id'] != 0) {
                if ($post['article_cate_id'] == -1) {
                    $where['article_cate_id'] = 0;
                } else {
                    $where['article_cate_id'] = ['in', $cateModel->getChildsIdByPid($post['article_cate_id'])];
                }
            }
            if (isset($post['catalog_id']) and $post['catalog_id'] > 0) {
                $where['catalog_id'] = $post['catalog_id'];
            }
            if (isset($post['admin_id']) and $post['admin_id'] > 0) {
                $where['admin_id'] = $post['admin_id'];
            }
            if (isset($post['status']) and ($post['status'] == 1 or $post['status'] === '0')) {
                $where['status'] = $post['status'];
            }
            if (isset($post['istop_time']) and ($post['istop_time'] == 1 or $post['istop_time'] === '0')) {
                $where['istop_time'] = $post['istop_time'] == 1 ? ['<>', 0] : 0;
            }
            if (isset($post['create_time']) and !empty($post['create_time'])) {
                $timerang = explode(' - ', $post['create_time']);
                $min_time = strtotime($timerang[0]);
                $max_time = strtotime($timerang[1]);
                $where['create_time'] = [['>=', $min_time], ['<=', $max_time]];
            }

            $model = new articleModel();
            $count = $model->where($where)->count();
            $data = $model->where($where)->page($post['page']??0, $post['limit']??15)->order('create_time desc')->select();
            $cateIdAndName = $cateModel->column('title', 'id');
            $cateLogIdAndName = $catalogModel->column('title', 'id');
            $adminModel = new \app\admin\model\Admin();
            $adminIdAndName = $adminModel->column('nickname', 'id');

            foreach ($data as $key => $value) {
                $value['editor_name'] = $adminIdAndName[$value['edit_admin_id']]??"";
                $value['admin_name'] = $adminIdAndName[$value['admin_id']]??"";
                $value['article_cate'] = $cateIdAndName[$value['article_cate_id']]??"";
                $value['catalog'] = $cateLogIdAndName[$value['catalog_id']]??"";
                $value['thumb_url'] = geturl($value['thumb']);
                $data[$key] = $value;
            }
            return array('code' => 0, 'count' => $count, 'data' => $data);
        } else {
            //创建人
            $this->assign('admins', Db::name('admin')->select());
            //分类
            $this->assign('cates', $cateModel->treelist2());
            //栏目
            $this->assign('catalogs', $catalogModel->treelistForArticle());
            return $this->fetch();
        }
    }

    public function publish()
    {
        $id = $this->request->param('id', 0, 'intval');
        $model = new articleModel();
        $cateModel = new cateModel();
        $catalogModel = new cataLogModel();
        $web_config = Db::name('webconfig')->where('id', 1)->find();
        $post = $this->request->post();

        if ($this->request->isPost()) {
            $validate = new \think\Validate([
                ['title', 'require|max:50', '标题不能为空'],
//                ['article_cate_id', 'require', '请选择分类'],
//                ['content', 'require', '文章内容不能为空'],
                ['seo_title|SEO标题', 'max:50'],
                ['seo_keyword|SEO关键词', 'max:255'],
                ['seo_description|SEO描述', 'max:255'],
            ]);
            if (!$validate->check($post)) {
                $this->error('提交失败：' . $validate->getError());
            }
            if (!empty($post['article_cate_id']) && !empty($post['catalog_id'])) {
                $this->error('不能同时发布到,栏目和分类');
            }
            $post['uploadip'] = $this->request->ip();
        } else {
            $this->assign('web_config', $web_config);
            //分类
            $this->assign('cates', $cateModel->treelist2());
            //栏目
            $this->assign('catalogs', $catalogModel->treelistForArticle());
        }

        if ($id > 0) {
            $article = $model->where('id', $id)->find();
            if (empty($article)) {
                $this->error('id不正确');
            }
            if ($this->request->isPost()) {
                $post['edit_admin_id'] = Session::get(self::ADMIN_ID);
                if (false == $model->allowField(true)->save($post, ['id' => $id])) {
                    $this->error('修改失败');
                } else {
                    $this->success('修改成功');
                }
            } else {
                $this->assign('article', $article);
                $this->assign('thumb', $article->thumb);
                //切换编辑器
                $article_editor = $article->article_editor ?: $web_config['article_editor'];
                $this->switchEditor($article_editor, $id);
                return $this->fetch();
            }
        } else {
            //新增
            if ($this->request->isPost()) {
                $post['admin_id'] = Session::get(self::ADMIN_ID);
                $post['edit_admin_id'] = $post['admin_id'];
                if (false == $model->allowField(true)->save($post)) {
                    $this->error('添加失败');
                } else {
                    $this->success('添加成功', 'index');
                }
            } else {
                //随机获取封面图
                $attachment = new attachmentModel();
                $imgid = $attachment->where(['use' => ['like', '%article%'], 'fileext' => ['in', ['jpg', 'png', 'gif']], 'status' => attachmentModel::STATUS_OPEN])->orderRaw('rand()')->limit(1)->value('id');
                $this->assign('thumb', $imgid);
                //切换编辑器
                $article_editor = $web_config['article_editor'];
                $this->switchEditor($article_editor, 0);
                return $this->fetch();
            }
        }
    }

    private function switchEditor($article_editor, $id = 0)
    {
        if ($this->request->has('switchEditor')) {
            $switchEditor = $this->request->param("switchEditor");
            $editors = ["wangEditor", "tinymce", "ueditor", "markdown"];
            $index = array_search($switchEditor, $editors);//获取索引
            $next = ($index == count($editors) - 1) ? 0 : $index + 1;
            $article_editor = $editors[$next];
        }
        $this->assign('article_editor', $article_editor);
        $this->assign('switch_editor_url', "/admin/article/publish?switchEditor={$article_editor}&id={$id}");
    }

    private function deleteFile($id)
    {
        try {
            //先删除html文件
            $article = articleModel::get($id);
            if ($article->catalog_id) {
                $catalog = $article->catalog;
                $filepath = $article->getRulePath($catalog->getRealPath(), $catalog->article_rule);
                if (file_exists($filepath)) {
                    unlink($filepath);//删除
                }
            } else {
                $catalogs = $article->catalogs();
                foreach ($catalogs as $catalog) {
                    $filepath = $article->getRulePath($catalog->getRealPath(), $catalog->article_rule);
                    if (file_exists($filepath)) {
                        unlink($filepath);//删除
                    }
                }
            }
        } catch (Exception $e) {
        }
    }

    public function delete()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->param('id', 0, 'intval');
            $this->deleteFile($id);
            if (false == Db::name('article')->where('id', $id)->delete()) {
                $this->error('删除失败');
            } else {
                $this->success('删除成功', 'index');
            }
        }
    }

    public function deletes()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $ids = $post['ids'];
            foreach ($ids as $id) {
                $this->deleteFile($id);
            }
            $model = new articleModel();
            if ($model->where('id', 'in', $ids)->delete()) {
                Log::log("批量删除文章：" . implode(',', $ids));
                $this->success('删除成功');
            }
        }
    }

    public function istop_time()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $status = $post['status'] == 1 ? time() : 0;
            if (false == Db::name('article')->where('id', $post['id'])->update(['istop_time' => $status])) {
                $this->error('设置失败');
            } else {
                $this->success('设置成功', 'index');
            }
        }
    }

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

    /**
     * 预览
     * @return mixed
     */
    public function perview()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id) {
            $article = articleModel::get($id);
            return (new CmsService())->perviewArticle($article);
        }
        $this->error('预览失败:id is null');
    }

    /**
     * 重新生成html
     */
    public function createFile()
    {
        $post = $this->request->param();
        $ids = $post['ids'];
        if ($ids) {
            $articles = (new articleModel())->where('id', 'in', $ids)->select();
            if (empty($articles)) {
                $this->error('articles is null');
            }
            $service = new CmsService();
            foreach ($articles as $article) {
                try {
                    //全局对象
                    $this->assign([
                        'cataLogModel' => new cataLogModel(),
                        'articleCateModel' => new articleCateModel(),
                        'articleModel' => new articleModel()
                    ]);
                    /** @var articleModel $article */
                    /** @var cataLogModel $catalog */
                    if ($article->catalog_id) {
                        $catalog = $article->catalog;
                        $filepath = $article->getRulePath($catalog->getRealPath(), $catalog->article_rule);
                        $content = $this->fetch($catalog->getArticleTemplet()->getRealPath(), ['catalog' => $catalog, 'article' => $article, 'articleCate' => null]);
                        if (ifContain($filepath, templetModel::getRootDir())) {
                            $service->info("           ├─ 文章：" . $filepath);
                            FileHelper::save($filepath, $content);
                        }
                    } else {
                        $catalogs = $article->catalogs();
                        $cate = $article->cate;
                        foreach ($catalogs as $catalog) {
                            $filepath = $article->getRulePath($catalog->getRealPath(), $catalog->article_rule);
                            $content = $this->fetch($catalog->getArticleTemplet()->getRealPath(), ['catalog' => $catalog, 'article' => $article, 'articleCate' => $cate]);
                            if (ifContain($filepath, templetModel::getRootDir())) {
                                $service->info("           ├─ 文章：" . $filepath);
                                FileHelper::save($filepath, $content);
                            }
                        }
                    }
                } catch (\Exception $e) {
                    $this->error('生成失败:' . $e->getMessage());
                }
            }
            $this->success('执行成功');
        }
        $this->error('ids is null');
    }
}
