<?php
namespace app\admin\controller;

use app\admin\model\PermissionModel;
use app\admin\validate\PermissionValidate;
use think\Request;

/**
 * 权限控制器
 * 负责权限的增删改查
 * Class Permission
 * @package app\admin\controller
 */
class Permission extends Base
{
    /**
     * 权限列表页
     * @param PermissionModel $permission
     * @return mixed
     */
    public function index(PermissionModel $permission)
    {
        $data = $permission->getPermissionTreeAll();
        $this->assign('data', $data);
        return $this->fetch('index');
    }

    /**
     * 新增页面
     * @param PermissionModel $permission
     * @return mixed
     */
    public function create(PermissionModel $permission)
    {
        $data = $permission->getPermissionTreePart();
        $this->assign('data', $data);
        return $this->fetch('add');
    }

    /**
     * 权限保存与更新
     * @param Request $request
     * @param PermissionModel $permission
     * @param PermissionValidate $validate
     * @return array|\think\response\Json
     */
    public function store(Request $request, PermissionModel $permission, PermissionValidate $validate)
    {
        $data = $request->post();
        $id = $request->post('id');
        if (!$validate->check($data)) {
            return jsonErr($validate->getError());
        }

        if ($id) {
            $result = $permission->save($request->post(), ['id' => $id]);
        } else {
            $result = $permission->save($request->post());
        }

        if ($result) {
            return jsonSuc('添加数据成功');
        } else {
            return jsonErr('添加数据失败');
        }
    }

    public function edit($id, PermissionModel $permission)
    {
        $permissionData = $permission->find($id);

        $data = $permission->getPermissionTreePart();

        $this->assign('data', $data);
        $this->assign('permission', $permissionData);
        return $this->fetch('edit');
    }

    public function delete(Request $request, PermissionModel $permission)
    {
        $id = $request->post('id');

        if ($permission->delRowByIds($id)) {
            return jsonSuc('删除数据成功', $permission->getIds());
        } else {
            return jsonErr('删除数据失败');
        }
    }

         //状态修改
     public function status(Request $request){
         $id = $request->post('id');
         $permission= new PermissionModel;
         $status=$permission->getPermissionstatusById($id);
         if($status['status']==1){
          $status= $permission->setPermissionStatus($id,0);
          return jsonSuc('状态禁用成功');
         }else{
          $status= $permission->setPermissionStatus($id,1);
          return jsonSuc('状态开启成功');
         }
     }
}