<?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 SystemMenu extends BaseModel
{

    private $_data;


    /**
     * 设置显示状态
     * @param $id
     * @param $status
     */
    public function setStatus($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;
       }

    }

    /**
     * 保存分类
     * @param $post
     * @return bool
     */
    public function saveMenu($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 delMenu($id){
        $this->where('pid',$id)->delete();
        $this->where('id',$id)->delete();
        return true;
    }


    /**
     * 获取admin端用户菜单
     * @param $roule_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getRoute($roule_id)
    {
        $rules = (new SystemRole())->getRoleId($roule_id);
        $menuAr = $this->getArMenu(1);
        //判断权限
        if($rules['is_system']) {
            $resultAr = Arr::toIviewUi($menuAr);
        }
        $resultAr = array_merge([[
            'header' => '0',
            'icon' => 'md-home',
            'is_header' => 0,
            'path' => '/system/index',
            'title' => '主页'
        ]],$resultAr);
        return $resultAr;
    }

    /**
     * 获取分类数据
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getArMenu($show =  0){
        $menus = $this->when(!empty($show), function ($query){
            $query->where('is_show',1);
        })->order("seq","desc")->select();
        $data = [];
        foreach ($menus as $item) {
            $data[] = $item->getData();
        }
        $menuAr = Arr::getTree($data);
        return $menuAr;
    }
}
