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

namespace app\admin\controller\project;

use app\admin\controller\AdminBase;
use app\model\ProjectCategory as ProjectCategoryModel;
use think\App;
use think\facade\Db;
use think\facade\Validate;
use think\facade\Env;

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

    protected $projectcategory;

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

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

        if ($do == 'json') {
            $list = $this->projectcategory->select()->append(['thumbpath'])->toArray();

            return $this->returnMsg($list);
        }
        return $this->fetch('', '', false);
    }

    //快速编辑
    public function editup()
    {
        $post = input();
        $this->projectcategory->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 {

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

        $categorydata = $this->projectcategory->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->projectcategory->destroy([$ids])) {
            return $this->returnMsg("删除成功", 1);
        } else {
            return $this->returnMsg("删除失败");
        }
    }


}