Apigroup.php 11.4 KB
<?php

namespace app\admin\controller\cloudapi;

use app\common\controller\Backend;
use fast\Tree;
use think\Collection;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 云API 接口分组管理
 *
 * @icon fa fa-circle-o
 */
class Apigroup extends Backend
{
    
    /**
     * Apigroup模型对象
     * @var \app\admin\model\cloudapi\Apigroup
     */
    protected $model = null;
    protected $modelValidate = true;
    protected $selectpageFields = ['id','pid','parent_name','group_name','relation_ids','full_name','level','weigh'];
    protected $groupList = [];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\cloudapi\Apigroup;

        $this->groupList = $this->model->order('weigh DESC,id ASC')->select();
        $treeArray = Tree::instance()->init(collection($this->groupList)->toArray())->getTreeArray(0);
        $this->groupList = Tree::instance()->getTreeList($treeArray,'group_name');
        $groupdata = [0 => __('None')];
        foreach ($this->groupList as $k => &$v) {
            $groupdata[$v['id']] = $v['group_name'];
            unset($v['spacer']);
        }
        unset($v);
        $this->view->assign('groupdata', $groupdata);
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            if (empty($this->groupList)){
                $total = 0;
                $treeList = [];
            }else{
                $total = count($this->groupList);
                $treeList = $this->groupList;
            }

            $result = array("total" => $total, "rows" => $treeList);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    //验证是否唯一
                    $find = $this->model->where(['pid' => intval($params['pid']), 'group_name' => $params['group_name']])->find();
                    if (!empty($find)){
                        throw new Exception('该分组名称已存在');
                    }

                    $result = $this->model->allowField(true)->save($params);

                    if ($result === false){
                        throw new Exception('添加分组失败');
                    }

                    if ($this->model->pid > 0){
                        $parent = \app\admin\model\cloudapi\Apigroup::get($this->model->pid);
                        $this->model->level = $parent['level'] + 1;
                        $this->model->relation_ids = $parent['relation_ids'] . $this->model->id . ',';
                        $this->model->parent_name = $parent['group_name'];
                        $this->model->full_name = $parent['group_name'] . ' > ' . $this->model->group_name;
                    }else{
                        $this->model->level = 1;
                        $this->model->relation_ids = ',' . $this->model->id . ',';
                        $this->model->parent_name = '-';
                        $this->model->full_name = $this->model->group_name;
                    }

                    $result = $this->model->save();

                    if ($result === false){
                        throw new Exception('添加分组失败');
                    }

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    //验证是否唯一
                    $find = $this->model->where(['id' => ['neq', $row['id']],'pid' => intval($params['pid']), 'group_name' => $params['group_name']])->find();
                    if (!empty($find)){
                        throw new Exception('该分组名称已存在');
                    }

                    $result = $row->allowField(true)->save($params);

                    if ($result === false){
                        throw new Exception('添加分组失败');
                    }

                    if ($row->pid > 0){
                        $parent = \app\admin\model\cloudapi\Apigroup::get($row->pid);
                        $row->level = $parent['level'] + 1;
                        $row->relation_ids = $parent['relation_ids'] . $row->id . ',';
                        $row->parent_name = $parent['group_name'];
                        $row->full_name = $parent['group_name'] . ' > ' . $row->group_name;
                    }else{
                        $row->level = 1;
                        $row->relation_ids = ',' . $row->id . ',';
                        $row->parent_name = '-';
                        $row->full_name = $row->group_name;
                    }

                    $result = $row->save();

                    if ($result === false){
                        throw new Exception('添加分组失败');
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    //删除用户分组权限group_ids和api权限api_ids对应数据
                    $apiUserModel = new \app\admin\model\cloudapi\User();
                    //整理API分组数据和API数据
                    $apiIds = Db::name('cloudapi_api')->where(['group_id' => $v['id']])->column('id');
                    $oldApiUsers = $apiUserModel->field('id,api_ids,group_ids')->where("FIND_IN_SET({$v['id']},group_ids)")->select();
                    if (!empty($oldApiUsers)){
                        foreach ($oldApiUsers as $oldApiUser){
                            $newData = [];
                            if (!empty($oldApiUser['api_ids']) && !empty($apiIds)){
                                $oldApiIds = explode(',', $oldApiUser['api_ids']);
                                $newApiIds = array_diff($oldApiIds, $apiIds);
                                $newData['api_ids'] = join(',', $newApiIds);
                            }
                            $oldGroupIds = explode(',', $oldApiUser['group_ids']);
                            $newGroupIds = array_diff($oldGroupIds, [$v['id']]);
                            $newData['group_ids'] = join(',', $newGroupIds);
                            $oldApiUser->save($newData);
                        }
                    }

                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}