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

namespace app\admin\controller\course;

use app\admin\controller\AdminBase;
use app\model\CourseCategory as CourseCate;
use think\App;
use think\facade\Db;
use think\facade\Validate;
use think\facade\Env;

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

    protected $coursecategory;

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

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

        if ($do == 'json') {
            $list = $this->coursecategory->where('is_del', 0)->append(['thumbpath'])->select()->toArray();
            return $this->returnMsg($list);
        }
        return $this->fetch('', '', false);
    }

    //快速编辑
    public function editup()
    {
        $post = input();
        $this->coursecategory->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->coursecategory->update($post, ['id' => $post['id']]);
                } else {
                    unset($post['id']);
                    $post['createtime'] = time();
                    $msg = '添加成功';
                    $this->coursecategory->save($post);
                }
            } catch (\Exception $e) {
                return $this->returnMsg($e->getMessage(), 0);
            }
            return $this->returnMsg($msg, 1);
        }
        $data = Db::name('course_category')->where('id',$post['id'])->find();

        $categorydata = $this->coursecategory->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->coursecategory->where("id IN(" . $ids . ")")->update(['is_del' => 1])) {
            return $this->returnMsg("删除成功", 1);
        } else {
            return $this->returnMsg("删除失败");
        }
    }


}