<?php

namespace app\adminapi\model;

use app\common\model\BaseModel;
use fast\Tree;
use think\Cache;
use think\Model;

class AuthRule extends BaseModel
{
    protected $name = 'api_auth_rule';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 数据自动完成字段
    protected $insert = ['py', 'pinyin'];
    protected $update = ['py', 'pinyin'];
    // 拼音对象
    protected static $pinyin = null;

    protected static function init()
    {
        self::$pinyin = new \Overtrue\Pinyin\Pinyin('Overtrue\Pinyin\MemoryFileDictLoader');

        self::beforeWrite(function ($row) {
            if (isset($_POST['row']) && is_array($_POST['row']) && isset($_POST['row']['condition'])) {
                $originRow = $_POST['row'];
                $row['condition'] = $originRow['condition'] ?? '';
            }
        });
        self::afterWrite(function ($row) {
            Cache::rm('__menu__');
        });
    }

    public function getTitleAttr($value, $data)
    {
        return __($value);
    }

    public function getMenutypeList()
    {
        return ['addtabs' => __('Addtabs'), 'dialog' => __('Dialog'), 'ajax' => __('Ajax'), 'blank' => __('Blank')];
    }

    public function setPyAttr($value, $data)
    {
        if (isset($data['title']) && $data['title']) {
            return self::$pinyin->abbr(__($data['title']));
        }
        return '';
    }

    public function setPinyinAttr($value, $data)
    {
        if (isset($data['title']) && $data['title']) {
            return self::$pinyin->permalink(__($data['title']), '');
        }
        return '';
    }



    /**
     * 获取会员组别规则列表
     * @return array|bool|\PDOStatement|string|\think\Collection
     */
    public function getRuleList($admin_id,$where=[],$full = false)
    {
        $group_ids = AuthGroupAccess::where("uid",$admin_id)->column("group_id");
        if(!$group_ids && !$full) return [];
        $groups = AuthGroup::where('id', 'in', $group_ids)->select();
        if (!$groups && !$full ) {
            return [];
        }
        $rules = [];
        foreach ($groups as $group){
            $rules = array_merge($rules, explode(',', $group->rules));
        }
        //包含*全查，否则按值查
        if ($full || in_array('*', $rules)) {
            return AuthRule::where($where)->where('status', 'normal')->order('weigh desc,id desc')->select();
        }
        return AuthRule::where($where)->where('status', 'normal')->where('id', 'in', $rules)->order('weigh desc,id desc')->select();
    }


    //得到菜单列表
    public function getMenulist($admin_id,$where= ["ismenu"=>1],$is_tree=false,$full = false,$id_name='id',$pid_name='pid',$child_name='children')
    {
        $menu = $this->getRuleList($admin_id,$where,$full);
        if(!$is_tree){
            return $menu;
        }
        // 生成菜单的树状结构 id  pid ,pid=0为顶级菜单
        $menulist = [];
        foreach ($menu as $k => $v) {
            $v = $v->toArray();
            $v[$id_name] = $v['id'];
            $v[$pid_name] = $v['pid'];
            $menulist[$v[$id_name]] = $v;
        }
        $tree = [];

        foreach ($menulist as $k => $v) {
            if (isset($menulist[$v[$pid_name]])) {
                $menulist[$v[$pid_name]][$child_name][] = &$menulist[$v[$id_name]];
            } else {
                $tree[] = &$menulist[$v[$id_name]];
            }
        }
        return $tree;


    }


    public function authCheck($admin_id,$auth_name)
    {
        $group_ids = AuthGroupAccess::where("uid",$admin_id)->column("group_id");
        if(!$group_ids) return null;
        $groups = AuthGroup::where('id', 'in', $group_ids)->select();
        if (!$groups) {
            return null;
        }
        $rules = [];
        foreach ($groups as $group){
            $rules = array_merge($rules, explode(',', $group->rules));
        }
        //包含*全查，否则按值查
        if (in_array('*', $rules)) {
            return AuthRule::where('status', 'normal')->where( 'name|rule_name',$auth_name)->find() ;
        }
        return AuthRule::where('status', 'normal')->where( 'name|rule_name',$auth_name)->where('id', 'in', $rules)->find();

    }

    public function getAllRules($admin_id)
    {
        $group_ids = AuthGroupAccess::where("uid",$admin_id)->column("group_id");
        if(!$group_ids) return null;
        $groups = AuthGroup::where('id', 'in', $group_ids)->select();
        if (!$groups) {
            return null;
        }
        $rules = [];
        foreach ($groups as $group){
            $rules = array_merge($rules, explode(',', $group->rules));
        }
        //包含*全查，否则按值查
        if (in_array('*', $rules)) {
            return AuthRule::where('status', 'normal')->field("name,rule_name,ismenu")->select() ;
        }
        return AuthRule::where('status', 'normal')->where('id', 'in', $rules)->field("name,rule_name,ismenu")->select();


    }



    /** 通用新增(后台api版本)
     * @param $params
     * @param $trans
     * @return $this
     * @throws \Exception
     */
    public function add($params,$trans=false){

        if (empty($params)) {
            throw new \Exception(__('Parameter %s can not be empty', ''));
        }

//        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
//            $params[$this->dataLimitField] = $this->auth->id;
//        }
//判断逻辑
        if($trans){
            self::beginTrans();
        }
        $res = true;
        try{

            //这里需要针对name做唯一验证
            $name = self::where("name", $params['name'])->find();
            if ($name) {
                throw new \Exception(__('路由名称已存在'));
            }
            if (!empty($params['rule_name'])) {
                $rule_name = self::where("rule_name", $params['rule_name'])->find();
                if ($rule_name) {
                    throw new \Exception(__('路由权限已存在'));
                }
            }
            if (!empty($params['url'])) {
                $rule_name = self::where("url", $params['url'])->find();
                if ($rule_name) {
                    throw new \Exception(__('路由路径已存在'));
                }
            }


            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->validateFailException()->validate($validate);
            }
            if (!$params['ismenu'] && !$params['pid']) {
                throw new \Exception(__('The non-menu rule must have parent'));
            }


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

            if($trans){
                self::commitTrans();
            }
        }catch (\Exception $e){
            if($trans){
                self::rollbackTrans();
            }
            throw new \Exception($e->getMessage().$e->getFile().$e->getLine());
        }
        return $this;
    }





     /** 通用编辑(后台api版本)
     * @param $params
     * @param $trans
     * @return $this
     * @throws \Exception
     */
    public function edit($id,$params,$trans=false){

        $row = $this->get($id);
        if (!$row) {
            throw new \Exception(__('No Results were found'));
        }

//        $adminIds = $this->getDataLimitAdminIds();
//        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
//            throw new \Exception(__('You have no permission'));
//        }


        if (!$params['ismenu'] && !$params['pid']) {
            throw new \Exception(__('The non-menu rule must have parent'));
        }
        if ($params['pid'] == $row['id']) {
            throw new \Exception(__('Can not change the parent to self'));
        }
        if ($params['pid'] != $row['pid']) {
            $childrenIds = Tree::instance()->init(collection(\app\admin\model\api\AuthRule::select())->toArray())->getChildrenIds($row['id']);
            if (in_array($params['pid'], $childrenIds)) {
                throw new \Exception(__('Can not change the parent to child'));
            }
        }

//这里需要针对name做唯一验证
        $name = self::where("id","<>", $id)->where("name", $params['name'])->find();
        if ($name) {
            throw new \Exception(__('路由名称已存在'));
        }
        if (!empty($params['rule_name']) && $params['rule_name'] != $row['rule_name']) {
            $rule_name = self::where("id","<>", $id)->where("rule_name", $params['rule_name'])->find();
            if ($rule_name) {
                throw new \Exception(__('路由权限已存在'));
            }
        }
        if (!empty($params['url'])&& $params['url'] != $row['url']) {
            $rule_name = self::where("id","<>", $id)->where("url", $params['url'])->find();
            if ($rule_name) {
                throw new \Exception(__('路由路径已存在'));
            }
        }


        if (empty($params)) {
            throw new \Exception(__('Parameter %s can not be empty', ''));
        }
//判断逻辑
        if($trans){
            self::beginTrans();
        }
        $res = true;
        try{

            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);

            if($trans){
                self::commitTrans();
            }
        }catch (\Exception $e){
            if($trans){
                self::rollbackTrans();
            }
            throw new \Exception($e->getMessage().$e->getFile().$e->getLine());
        }
        return $row;
    }




    /** 通用详情(后台api版本)
     * @param $params
     * @param $trans
     * @return $this
     * @throws \Exception
     */
    public function detail($id,$show_field=[],$except_field=[]){
        $row = $this->get($id);
        if (!$row) {
            throw new \Exception(__('No Results were found'));
        }
        if($show_field){
            $row->visible($show_field);
        }
        if($except_field){
            $row->hidden($except_field);
        }
        return $row;
    }




        /** 通用删除(后台api版本)
     * @param $params
     * @param $trans
     * @return $this
     * @throws \Exception
     */
    public function del($ids = null,$trans=false){
        if (empty($ids)) {
            throw new \Exception(__('Parameter %s can not be empty', 'ids'));
        }
//判断逻辑

//        $pk = $this->getPk();
//        $adminIds = $this->getDataLimitAdminIds();
//        if (is_array($adminIds)) {
//            $this->where($this->dataLimitField, 'in', $adminIds);
//        }
        if($trans){
            self::beginTrans();
        }
        $res = true;
        try{

            $delIds = [];
            if(is_string($ids))$ids = explode(',', $ids);

            //如果有子节点，全部删除
            //用遍历形式模拟递归得到所有子节点id

            foreach ($ids as $id){
                $childrenIds = Tree::instance()->init(collection(\app\adminapi\model\AuthRule::select())->toArray())->getChildrenIds($id,true);
                $delIds = array_merge($delIds,$childrenIds);
            }

//            var_dump($delIds);die;


            $count = $this->where('id', 'in', $delIds)->delete();
            if ($count) {
                Cache::rm('__menu__');
            }



//            foreach ($list as $item) {
//                $count += $item->delete();
//            }

            if($trans){
                self::commitTrans();
            }
        }catch (\Exception $e){
            if($trans){
                self::rollbackTrans();
            }
            throw new \Exception($e->getMessage().$e->getFile().$e->getLine());
        }
        return $count;
    }



}
