<?php
/**
 * ===========================================================================
 * Veitool 快捷开发框架系统
 * Author: Niaho 26843818@qq.com
 * Copyright (c)2019-2025 www.veitool.com All rights reserved.
 * Licensed: 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
 * ---------------------------------------------------------------------------
 */

namespace app\admin\controller;


use app\model\ArticleCategoryModel;
use think\App;
use think\facade\Db;
use think\facade\Validate;
use think\facade\Env;

/**
 * 后台主控制器
 */
class ArticleCategory extends AdminBase
{

    protected $articlecategory;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->articlecategory = new ArticleCategoryModel();
    }

    //分类列表
    public function index(string $do = '')
    {


        if ($do == 'json') {
            $list = $this->articlecategory->list();
            return $this->returnMsg('', 0, $list);
        }
        return $this->fetch('', '', false);
    }

    //快速编辑
    public function editup()
    {
        $post = input();
        $this->articlecategory->update([$post['af'] => $post['av']], [['id', '=', $post['id']]]);
        return $this->returnMsg('修改成功');
    }

    //编辑新增分类
    public function edit()
    {
        $post = input();
        if ($this->request->isPost()) {

            $validate = Validate::rule([
                'title'  => 'require'
            ])->message([
                'title.require' => '分类名称不能为空',
            ]);

            if(!$validate->check($post)) {
                return $this->returnMsg($validate->getError(), 0);
            }

            try {
                $post['createtime'] = time();
                if ($post['id'] > 0) {
                    $msg = '更新成功';
                    $this->articlecategory->update($post, ['id' => $post['id']]);
                } else {
                    unset($post['id']);
                    $msg = '添加成功';
                    $this->articlecategory->save($post);
                }
            } catch (\Exception $e) {
                return $this->returnMsg($e->getMessage(), 0);
            }
            return $this->returnMsg($msg, 1);
        }
        $data = Db::name('article_category')->where('id',$post['id'])->find();

        $categorydata = $this->articlecategory->catetree(isset($data['pid']) ? $data['pid'] : 0);

        $this->assign('categorydata', $categorydata);
        $this->assign('data', $data);
        return $this->fetch('', '', false);
    }

    public function del()
    {
        $post = input();
        $ids = is_array($post['id']) ? implode(',', $post['id']) : $post['id'];
        if ($this->articlecategory->where("id IN(" . $ids . ")")->update(['is_del' => 1])) {
            return $this->returnMsg("删除成功", 1);
        } else {
            return $this->returnMsg("删除失败");
        }
    }


}