<?php
declare (strict_types = 1);
namespace app\model\system;

use app\Request;
use library\basic\BaseModel;
use library\services\UtilService;
use library\utils\Arr;
use think\db\exception\DbException;
use think\Model;

/**
 * @mixin \think\Model
 */
class NewsCate extends BaseModel
{

    private $_data;
    
    /**
     * 获取分类数据
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getArCate($show =  0){
        $cateData = $this->when(!empty($show), function ($query){
            $query->where('is_show',1);
        })->order("seq","desc")->select();
        $data = [];
        foreach ($cateData as $item) {
            $data[] = $item->getData();
        }
        $menuAr = Arr::getTree($data);
        return $menuAr;
    }
    
    /**
     * 保存分类
     * @param $post
     * @return bool
     */
    public function cateSave($post){
        if(!empty($post['id'])) {
            $this->where('id',$post['id'])->save($post);
            return true;
        } else {
            unset($post['id']);
            $bool = $this->insert($post);
            return $bool;
        }
    }
    
    /**
     * 删除分类
     * @param $id
     */
    public function cateDel($id){
        $this->where('pid',$id)->delete();
        $this->where('id',$id)->delete();
        return true;
    }
    
    /**
     * 设置显示状态
     * @param $id
     * @param $status
     */
    public function cateShowSet($id,$status) {
       self::beginTrans();
       try{
         $this->where('id', $id)->save(['is_show'=>$status]);
         $this->where('pid',$id)->save(['is_show'=>$status]);
         self::commitTrans();
         return true;
       }catch (DbException $db) {
           self::rollbackTrans();
           return false;
       }
    }
}