<?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\ArticleCate as cateModel;
use app\common\model\Catalog as cataLogModel;
use app\common\service\CmsService;
use think\Db;

class Articlecate extends Permissions
{
    public function index()
    {
        if ($this->request->isAjax()) {
            $data = (new cateModel())->order('sort desc')->select();
            foreach ($data as $k => $v) {
                /**@var cateModel $v */
                $v['catalog'] = $v->getCatalogValues();
                $v['article_count'] = $v->article_count ?: '';
                try {
                    $v['uri'] = $v->getUri();
                } catch (\Exception $e) {
                    $v['uri'] = '';
                }
                $data[$k] = $v;
            }
            return $data;
        } else {
            return $this->fetch();
        }
    }

    public function publish()
    {
        $id = $this->request->param('id', 0, 'intval');
        $model = new cateModel();
        $post = $this->request->post();
        if ($this->request->isPost()) {
            $validate = new \think\Validate([
                ['title|分类名称', 'require'],
                ['pid', 'require', '请选择上级分类'],
            ]);
            if (!$validate->check($post)) {
                $this->error('提交失败:' . $validate->getError());
            }
        } else {
            //栏目
            $cataLogModel = new cataLogModel();
            $catalogs = $cataLogModel->where('type', cataLogModel::TYPE_ARTICLE_LIST)->select();
            $this->assign('catalogs', $catalogs);
            //分类
            $catelist = $model->order('sort desc')->select();
            $cates = $model->treelist($catelist);
            $this->assign('cates', $cates);
        }

        if ($id > 0) {
            //修改
            $cate = $model->where('id', $id)->find();
            if (empty($cate)) {
                $this->error('id不正确');
            }
            if ($this->request->isPost()) {
                if ($id == $post['pid']) {
                    $this->error('上级节点不能选自己');
                }
                //保存中间表
                $res1 = $this->updateCatalog($post, $cate);
                //更新tree_path
                $post = $this->updatePath($post, $id);
                if (!$res1 && false == $cate->allowField(true)->save($post)) {
                    $this->error('修改失败');
                } else {
                    $this->success('修改成功', 'index');
                }
            } else {
                $this->assign('cate', $cate);
                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->updateCatalog($post, $cate);
                    $this->success('添加成功', 'index');
                }
            } else {
                $pid = $this->request->param('pid', null, 'intval');
                if (!empty($pid)) {
                    $this->assign('pid', $pid);
                }
                return $this->fetch();
            }
        }
    }

    /**
     * 保存中间表
     * @param $post
     * @param $cate cateModel
     * @return bool [是否有修改]
     */
    private function updateCatalog($post, $cate)
    {
        if (isset($post['catalog_ids'])) {
            $catalog_ids = explode(',', $post['catalog_ids']);
            $old_catalog_ids = $cate->getCatalogValues('id');
            if ($old_catalog_ids == $post['catalog_ids']) {
                return false;
            }
            foreach ($cate->catalogs as $catalog) {
                if (!in_array($catalog->id, $catalog_ids)) {
                    $cate->catalogs()->detach($catalog->id);// 删除中间表数据
                }
            }
            if (false == $cate->catalogs()->attach($catalog_ids)) {//插入数据
                $this->error('保存中间表失败');
            }
            return true;
        }
        return false;
    }

    /**
     * 更新tree_path
     * @param $post
     * @param $id
     * @return mixed
     */
    private function updatePath($post, $id)
    {
        if ($post['pid']) {
            $pdoc = (new cateModel())->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->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            if (Db::name('article_cate')->where('pid', $id)->count() == 0) {
                if (false == Db::name('article_cate')->where('id', $id)->delete()) {
                    $this->error('删除失败');
                } else {
                    $this->success('删除成功', 'index');
                }
            } else {
                $this->error('请先删除子节点');
            }
        }
    }

    /**
     * 审核
     */
    public function status()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (false == Db::name('article_cate')->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('article_cate')->where('id', $id)->value('sort');
                $newsort = $post['sorts'][$k]??$sort;
                if ($sort != $newsort) {
                    if (false == Db::name('article_cate')->where('id', $id)->update(['sort' => $newsort])) {
                        $this->error('更新失败');
                    } else {
                        $i++;
                    }
                }
            }
            $this->success('成功更新' . $i . '个数据', 'index');
        } else {
            $this->error('无数据更新', 'index');
        }
    }

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

    //预览
    public function perview()
    {
        $id = $this->request->param('id', 0, 'intval');
        if ($id) {
            $articleCate = (new cateModel())->where('id', $id)->find();
            return (new CmsService())->perviewArticleCate($articleCate);
        }
        $this->error('预览失败:id is null');
    }
}