<?php
/**
 * 仓库角色管理
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
 
namespace Admin\Controller;
class ShopsRoleController extends BaseController{
	
	public function _initialize(){
        parent::_initialize();
    }
    
	/**
     * 角色列表
     */
	public function index(){
		$list = $this->lists('ShopsRole');
        $this->assign('list', $list);
		$this->display();
	}
	/**
     * 角色添加
     */
	public function add(){
		if (IS_POST) {
            $model = M("ShopsRole");
            $postdata = I('post.');
            $this->check_staff_post($postdata, 0);

            $postdata = $this->format_post($postdata);
            $model->create($postdata);
            $result = $model->add();
			$url = U(CONTROLLER_NAME . '/index');
            if ($result) {$site_info=session("site_info");
                $shop_nav_list = require_once ROOT_PATH."/Public/data/shop_nav_config7.php";
                foreach($shop_nav_list as $key => $vo){
                    foreach($vo['son'] as $k => $v){
                        $data=array();
                        if($v['module']=='Pad'){
                            $data['role_id']=$result;
                            $data['module']=$v['module'];
                            $data['action']=$v['action'];
                            //print_r($data);exit;
                            M('ShopsRoleAuth')->add($data);
                        }
                    }
                }
                //print_r($shop_nav_list);exit;
                $this->success(L('DO_OK'),$url);
            } else {
                $this->error(L('DO_ERROR'));
            }
            unset($postdata);
        } else {
			$this->display('edit');
        }
	}
	/**
     * 角色修改
     */
	public function edit(){
        $model = M("ShopsRole");
		$id = I('id');
		if (IS_POST) {
            $postdata = I('post.');

            $this->check_staff_post($postdata, $id);
			
            $postdata = $this->format_post($postdata);
            $data = $model->create($postdata);
			
			if (false === $data) {
                $this->error($model->getError());
            }
			$map['id'] = $id;
            $result = $model->save($data);
			
			$url = U(CONTROLLER_NAME . '/index');
            if ($result) {
                $this->success(L('DO_OK'),$url);
            } else {
                $this->error(L('DO_ERROR'));
            }
            unset($data);
        } else {
			 if (isset($id)) {
                $id = isset($id) && intval($id) ? intval($id) : $this->error('参数错误');
            }
            if (!$id) $this->error('参数错误');
            $info = $model->field(true)->find($id);
			
            $this->assign($info);
            $this->assign('id', $id);
            $this->display();
        }
	}
	/**
     * 格式化提交的数据
     * @param array $postdata
     * @return array
     */
	public function format_post($postdata = array()){
        $postdata['updatetime'] = NOW_TIME;
        return $postdata;
    }
	/**
     * 检查提交的数据是否合法
     * @param array $postdata
     * @param $id 仓库id
     */
    public function check_staff_post($postdata = array(), $id = 0){
        if (empty($postdata)) $this->error("非法数据");
        if ($postdata['title'] == '') $this->error("仓库名称不得为空");
    }
	
	public function _before_delete(){
		$model = CONTROLLER_NAME;
		$id=I('id');
		if(isset($id)&&is_array($id)){
			foreach($id as $k=>$v){
				$result=check_delete($v,7,$model);
				if(!$result['status'])unset($id[$k]);
			}
			if(empty($id)){$this->error($result['info']);exit;}
		}else{
			$result=check_delete($id,7,$model);
			if(!$result['status']){$this->error($result['info']);exit;}
		}
		$this->id=$id;
	}
	/* 设置管理员权限规则 */
    public function shopsrule(){
		$model = M('ShopsRoleAuth');
		$id = I('id');
		if(!$id){
			$this->error('参数错误');
		}
		if(IS_POST){
			$map['role_id'] = $id;
			$id_count = $model->where($map)->count('id');
			if($id_count){
				$model->where($map)->delete();
			}
			
			$postdata = I('post.');
			foreach($postdata as $key=>$value){
				$module = $key;
				foreach($value as $k=>$v){
                    if(str_exists($v,'allrule')){
                        $data['action'] = $v;
                        $data['role_id'] = intval($id);
                        $data['module'] = $module;
                        $result = $model->add($data);
                        break;
                    }else{
                        $data['action'] = $v;
                        $data['role_id'] = intval($id);
                        $data['module'] = $module;
                        $result = $model->add($data);
                    }
				}
			}
			
			$url = U(CONTROLLER_NAME . '/index');
			if ($result !== false) {
				$this->success(L('DO_OK'),$url);
			} else {
				$this->error(L('DO_ERROR'));
			}
		}else{
			if (isset($id)) {
                $id = isset($id) && intval($id) ? intval($id) : $this->error('参数错误');
            }
            $map=$resultdata=array();
            $map['role_id'] = $id;
            $resultdata= $model->where($map)->getField('action',true);
            $site_info=session("site_info");
			$shop_nav_list = require_once ROOT_PATH."/Public/data/shop_nav_config7.php";
			$map=$auth_model=array();
            $map['site_id']=C('appid');
            $map['end_time']=array("gt",NOW_TIME);
            $map['status']=1;
            $site_app=M("SiteApp")->where($map)->getField("app_mark",true);
            if($site_app){
                foreach($site_app as $key=>$val){
                    $auth_model[$key]=strtolower($val);
                }
            }
            foreach($shop_nav_list as $key=>$val){
                if(strstr($key,'main')){
                    $main_code=explode('-',$key);
                    $rule_code=$main_code['1'];
                    if(!in_array($rule_code,$auth_model)){
                        unset($shop_nav_list[$key]);
                    }
                }
            }
            $this->assign('shop_nav_list',$shop_nav_list);
            $this->assign('resultdata',$resultdata);
			$this->display();
		}
		
		
    }

    /*获取级数*/
    private function get_level($id, $array = array(), $i = 0){
        if ($id == '0') return $i;
        if ($array[$id]['pid'] == 0) return $i;
        else {
            ++$i;
            return $this->get_level($array[$id]['pid'], $array, $i);
        }
    }

    private function setGroupRulebyid($id){
        if (!$id) return false;
        $AdminRule = M("AuthRule");
        $AdminGrouprule = M('AuthGroup');
        $groupValue = $AdminGrouprule->where('id=' . $id . ' and status=1')->field('id,rules')->find();
        $ruleData = $AdminRule->where("id IN(" . $groupValue['rules'] . ")  AND status=1")->order('sort,id desc')->getField('id,name,title,show_status,type,condition,pid,sort');
        F("admin_rule_" . $id, $ruleData);
        unset($ruleData);
        return true;
    }


    // 商家中心权限开始
    public function shops_center_rule(){
        $menu_array=$this->menu();
        
        //得到完整数组兼容新店
        $key_arr=[];
        foreach ($menu_array as $k=>$v) {
            $key_arr[$v['model']]=1;
        }
        unset($key_arr['is_share_user']);unset($key_arr['is_share_money']);unset($key_arr['is_hide_phone']);

        $shop_center=M('Shops')->where('status = 1')->field('id,name,is_share_user,is_hide_phone,is_share_money,shop_center_rule')->select();
        // 获取仓库权限
        $shop_list=array();
        foreach($shop_center as $k=>$v){
            $s_c_r=[];
            if($v['shop_center_rule']== null){
                $s_c_r=$key_arr;
            }else{
                $s_c_r=json_decode($v['shop_center_rule'],true);
            }
            $shop_list[$v['id']]=$s_c_r;
             $shop_list[$v['id']]['id']=$v['id'];
            $shop_list[$v['id']]['is_share_user']=$v['is_share_user']; 
            $shop_list[$v['id']]['is_hide_phone']=$v['is_hide_phone']; 
            $shop_list[$v['id']]['is_share_money']=$v['is_share_money']; 
            $shop_list[$v['id']]['name']=$v['name'];
           
        }
       
        $this->assign('shop_nav_list',$menu_array);
        $this->assign('shop_list',$shop_list);
        $this->display();
    }
    /**
    *   
    *部分是专用字段存储，使用前unset($str['is_share_user']);unset($str['is_share_money']);unset($str['is_hide_phone']);
    */
    private function menu(){
        $return=D('Shop/Shops')->shop_option();
        return $return;

    }
    /**
    *   商家中心权限提交
    *  （注意清除特殊字段）
    */
    public function submit(){
        $post=I('param.');
        unset($post['__hash__']);

        //得到完整数组
        $menu=$this->menu();
        $key_arr=[];
        foreach ($menu as $k=>$v) {
            $key_arr[$v['model']]=0;
        }
        $shop_ids=M('Shops')->where('status=1')->getField('id',true);
        foreach ($post as $key => $val) {
            $shop_id=$key;
            // 完整数组赋值
            $str=array_replace_recursive($key_arr,$val);
            $is_share_user=$str['is_share_user'];unset($str['is_share_user']);
            $is_share_money=$str['is_share_money'];unset($str['is_share_money']);
            $is_hide_phone=$str['is_hide_phone'];unset($str['is_hide_phone']);
            $data['is_share_user']=$is_share_user;
            $data['is_share_money']=$is_share_money;
            $data['is_hide_phone']=$is_hide_phone;
            $str_last=json_encode($str);
            $data['shop_center_rule']=$str_last;
        // echo   M('Shops')->where('id = '.$shop_id)->fetchSql(true)->save($data);
           M('Shops')->where('id = '.$shop_id)->save($data);

        }

        // 没传shop_id的直接付0 避免都是 0 1时选了 0
        $have_shop_ids=array_keys($post);
        $diff_ids=array_diff($shop_ids,$have_shop_ids);
        $diff_ids=implode(',', $diff_ids);//得到啥权限都没有的id
        if($diff_ids){
           $d_map['id']=array('in',$diff_ids);
           $n_str=$key_arr;
           unset($n_str['is_share_user']);unset($n_str['is_share_money']);unset($n_str['is_hide_phone']);
            $data['shop_center_rule']=json_encode($n_str);
            $data['is_share_user']=0;
            $data['is_share_money']=0;
            $data['is_hide_phone']=0;
        // echo M('Shops')->where($d_map)->fetchSql(true)->save($data);
            M('Shops')->where($d_map)->save($data); 

        }
       $this->success(L('DO_OK'));
    }

    // 商家中心权限结束

}
?>