<?php

/**

 * @Copyright (C) 2016 汉潮 All rights reserved.

 * @License http://www.hanchao9999.com

 * @Author xiaogg <xiaogg@sina.cn>

 */

namespace Shop\Controller;

use Common\Controller\HanchaoController;

class BaseController extends HanchaoController{

	public function _initialize(){

		parent::_initialize ();

        if(!checksiteauth('MenDian')){ exit;}

		$shops_info=$this->shops_info=session('shops_info');

		define('MID',$shops_info['shop_id']);

		$this->assign('MID',MID);

        if(!$shops_info['shop_type'])$shops_info['shop_type']=idtoname(MID,'Shops','shop_type');

		define('STYPE',$shops_info['shop_type']);

		$this->assign('STYPE',STYPE);

        $this->assign('shops_info',$shops_info);

        

        $this->index_nav_list=require_once ROOT_PATH."/Public/data/shop_nav_data.php";

        if(empty($index_nav_list))$index_nav_list = $this->index_nav_list;

        // print_r($index_nav_list);echo "<br>";exit();

		//验证店铺功能权限

		$shops_open_card=D('Shops')->option(1,STYPE);

		if($shops_open_card == 0){unset($index_nav_list['MemberCard']['son']['open_card']);}

		$shops_fill_card=D('Shops')->option(2,STYPE);

		if($shops_fill_card == 0){unset($index_nav_list['MemberCard']['son']['fill_card']);}

		$shops_member_recharge=D('Shops')->option(3,STYPE);

		if($shops_member_recharge == 0){unset($index_nav_list['MemberCard']['son']['member_recharge']);}

		$shops_service=D('Shops')->option(4,STYPE);

		if($shops_service == 0){unset($index_nav_list['Service']['son']['service_add']);}

		$shops_package=D('Shops')->option(5,STYPE);

		if($shops_package == 0){unset($index_nav_list['Service']['son']['package_add']);}

		$shops_package_send=D('Shops')->option(6,STYPE);

		if($shops_package_send == 0){unset($index_nav_list['Service']['son']['package_send']);}

		// 1117 ggw start

        $shop_center_rule=D('Shops')->shop_option(MID);

        

        

        

		$notauthmodule=array("Register","Oauth","Cashier");

        if( !MID && !in_array(CONTROLLER_NAME,$notauthmodule)){// 还没登录 跳转到登录页面

			cookie('shop_forward',U('Shop/'.CONTROLLER_NAME.'/'.ACTION_NAME));

            if(CONTROLLER_NAME=='Cashier'){

                if(ACTION_NAME!='login')$this->redirect('Shop/Cashier/login');

            }else{

                $this->redirect('Shop/Register/shop_login');

            }

            // 基本

            if($shop_center_rule && !$shop_center_rule['shop_controller']){

               $return=D("Common/ShopLogin")->logout();

               $this->error('该店铺权限不足',$return['url']);

            }

		}

        if($shop_center_rule){

            // 员工

            if(!$shop_center_rule['account']){

               unset($index_nav_list['Account']['son']['account_index']); 

            }

            // 资金

            if(!$shop_center_rule['money']){

                unset($index_nav_list['Account']['son']['recharge']);

                unset($index_nav_list['Account']['son']['accountlog']);



            }

            // 商品

            if(!$shop_center_rule['goods']){

                unset($index_nav_list['Goods']);

                unset($index_nav_list['Service']); 

            }

            // 导购设置

            if(!$shop_center_rule['guide']){

                unset($index_nav_list['Account']['son']['guide']); 

            }

            // 配送设置

            if(!$shop_center_rule['ship']){

                unset($index_nav_list['Account']['son']['setting']); 

            }

            // 营销

            if(!$shop_center_rule['promot']){

                unset($index_nav_list['Promot']); 

            }

        }

        // 117  ggw end

        if(STYPE != 2){unset($index_nav_list['Account']['son']['recharge']);}

        session("shops_account_nav_list",$index_nav_list);

        $menu_moudle=CONTROLLER_NAME;

        $menu_action=ACTION_NAME;

        $menu_tab=I('param.tabid');

        $menu_param=I('param.');

        // $tplseo_title=$index_nav_list[$menu_moudle]['son'][$menu_action]['name'].'_'.$index_nav_list[$menu_moudle]['name'];

        $tplseo_title=$index_nav_list[$menu_moudle]['name']; //jxr

        $tplseo_keywords=$shops_info['name'].','.C('WEB_SITE_TITLE');

        $tplseo_description=$shops_info['name'].','.C('WEB_SITE_TITLE');

        $this->assign('tplseo_title',$tplseo_title.'_'.$shops_info['name'].'_'.C('WEB_SITE_TITLE'));

        $this->assign('tplseo_keywords',$tplseo_keywords);

        $this->assign('tplseo_description',$tplseo_description);

		$this->assign('menu_moudle',$menu_moudle);

		$this->assign('menu_action',$menu_action);

		$this->assign('menu_tab',$menu_tab);

		$this->assign('menu_param',$menu_param);

		$this->assign('index_nav_list',$index_nav_list);

    }

	private function check_auth(){

        //获取权限进行判断

		$result=$this->check_module_auth(CONTROLLER_NAME,ACTION_NAME);

        if(!$result){

            $this->error("没有操作该模块的权限，请更换有权限的账户登录!");exit;

        }

    }

    private function check_module_auth($module,$action){

        //获取权限进行判断

        // $shops_account_auth = $this->get_shops_account_auth(false);

        // $checkstr = $module.'_'.$action;

        // return !in_array($checkstr, $shops_account_auth)?false:true;

        return true;

    }

    public function get_shops_account_auth($cache=true){

        $shops_info=session('shops_info');

        $shops_account_auth = session("shops_account_auth");

		

		if($cache && $shops_account_auth){

			$shops_account_auth = unserialize(base64_decode($shops_account_auth));

		}else{

			

            $index_nav_list = $this->index_nav_list;

            if($shops_info['pid'] == 0){

                session("shops_account_nav_list",$index_nav_list);

            }else{

                $sr_where['account_id'] = $shops_info['id'];

                $shops_account_auth = $resultdata = array();

                // $result = M('ShopsAccountAuth')->where($where)->field('module,action')->select();

				$role_id = M('ShopsRoleAccount')->where($sr_where)->getfield('role_id');

				if($role_id){

					$ra_where['role_id'] = $role_id;

					$result = M('ShopsRoleAuth')->where($ra_where)->field('module,action')->select();

				}

                foreach($result as $k=>$v){

                    $resultdata[$v['module']][] = $v['action'];

                }

                $resultdata['modules'] = array_keys($resultdata);

                foreach($index_nav_list as $k=>$v){

                    if(in_array($k,$resultdata['modules'])){

                        foreach($v['son'] as $key=>$val){

                            if($key=='allrules')array_push($shops_account_auth,$k.'_'.ACTION_NAME);

                            if(!in_array($key,$resultdata[$k])){

                                unset($index_nav_list[$k]['son'][$key]);

                            }else{

                                array_push($shops_account_auth,$k.'_'.$key);

                            }

                        }

                    }else{

                        unset($index_nav_list[$k]);

                    }

                }

				

            }

            $shops_account_auth_encode = count($shops_account_auth)>0 ?base64_encode(serialize($shops_account_auth)):'';

            session("shops_account_nav_list",$index_nav_list);

            session("shops_account_auth",$shops_account_auth_encode);

        }

        return $shops_account_auth;

    }

    public function add() {//公共添加

        $model = D (CONTROLLER_NAME);$pk=ucfirst($model->getPk ());$id = intval(I($model->getPk ()));

        if($id){$do='getBy'.$pk;$vo = $model->$do ( $id );$this->assign ( 'info', $vo );}

        $this->display ('edit');

    }

    public function insert() {//公共插入

        $model = D (CONTROLLER_NAME);

        //echo $model;exit;

        if (false === $model->create ()) {$this->error ( $model->getError () );}

        $id = $model->add();

        if ($id !==false) {

            if(in_array(CONTROLLER_NAME,$this->cache_model)){savecache(CONTROLLER_NAME);}

            if($_POST['isajax'])$this->assign('dialog','1');

            $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(CONTROLLER_NAME.'/index');

            $this->assign ( 'jumpUrl',$jumpUrl );

            $this->success (L('ADD_OK'));

        } else {$this->error (L('ADD_ERROR').': '.$model->getDbError());}

    }

    public function edit() {//公共编辑

        $model = D (CONTROLLER_NAME);

        $pk=ucfirst($model->getPk ());

        $id = intval(I($model->getPk ()));

        // if(empty($id))   $this->error(L('do_empty'));

        $do='getBy'.$pk;

        $vo = $model->field(true)->$do ($id);

        $this->assign ($vo);

        $this->assign ('info',$vo);

        $this->display ();

    }

    /**

     * 对数据表中的单行或多行记录执行修改 GET参数id为数字或逗号分隔的数字

     *

     * @param string $model 模型名称,供M函数使用的参数

     * @param array  $data  修改的数据

     * @param array  $where 查询时的where()方法的参数

     * @param array  $msg   执行正确和错误的消息 array('success'=>'','error'=>'', 'url'=>'','ajax'=>false)

     *                     url为跳转页面,ajax是否ajax方式(数字则为倒数计时秒数)

     */

    public function update ( $model='' ,$data='', $where='1' , $msg='' ){

        if(!$model)$model=CONTROLLER_NAME;

        if(!$data)$data=D($model)->create();

        $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME.'/index');

        $id    = array_unique((array)I('id',0));

        $id    = is_array($id) ? implode(',',$id) : $id;

        $where = $where=='1'?array('id' => array('in', $id )):array_merge( array('id' => array('in', $id )),(array)$where);

        $msg   = array_merge( array('success'=>L('EDIT_OK'), 'error'=>L('EDIT_ERROR'), 'url'=>$jumpUrl ,'ajax'=>IS_AJAX) , (array)$msg );

        $res=D($model)->where($where)->save($data);

        if( $res!==false ) {

            if(in_array(CONTROLLER_NAME,$this->cache_model)){savecache(CONTROLLER_NAME);}

            $this->success($msg['success'],$msg['url'],$msg['ajax']);

        }else{$this->error($msg['error'],$msg['url'],$msg['ajax']);}

    }

    public function view() {//公共查看

        $model = D (CONTROLLER_NAME);

        $pk=ucfirst($model->getPk ());

        $id = intval(I($model->getPk ()));

        if(empty($id))$this->error(L('PARAM_ERROR'));

        $do='getBy'.$pk;

        if(!empty($request))$this->assign ('views',serialize($request));

        $vo = $model->field(true)->$do($id);

        $this->assign($vo);

        $this->display ();

    }

    public function index() {//公共首页

        $map=I('param.');

        if(!empty($param_map))$map=empty($map)?$param_map:array_merge($map,$param_map);

        if(!empty($map['keyword'])){

            $keyword_fields=I('keyword_fields','name');

            if(str_exists($keyword_fields,',')){

                $map[$keyword_fields]=array('like','%'.$map['keyword'].'%');

            }else{

                $field_arr=explode(',',$keyword_fields);$where=array();

                foreach($field_arr as $v){

                    $where[$v]  = array('like', '%'.$map['keyword'].'%');

                }

                if($where){

                    $where['_logic'] = 'or';

                    $map['_complex'] = $where;

                }

            }unset($map['keyword'],$map['keyword_fields']);

        }

        $list = $this->lists(CONTROLLER_NAME,$map);

        $this->assign('list', $list);

        $this->display();

    }

    public function delete(){//公共删除

        $mod=D(CONTROLLER_NAME);

        $id=I('id');

        if (isset($id) && is_array($id)) {

            $ids = implode(',', $id);

            $result=$mod->delete($ids);

        } else {

            $id = intval($id);

            $result=$mod->delete($id);

        }

        if($result!==false){

            if(in_array(CONTROLLER_NAME,$this->cache_model)){savecache(CONTROLLER_NAME);}

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

        }else{$this->error(L('DO_ERROR'));}

    }

    public function status(){//公共状态

        $mod = D(CONTROLLER_NAME);

        $id     = intval(I('id'));

        $type	= I('type');

        $values = $mod->where('id='.$id)->field($type)->find();

        $data[$type]=($values[$type]+1)%2;

        $res=$mod->where('id='.$id)->save($data);

        if(in_array(CONTROLLER_NAME,$this->cache_model)){savecache(CONTROLLER_NAME);}

        $this->ajaxReturn($data[$type]);

    }

    public function sort(){//公共排序

        $model = D (CONTROLLER_NAME);$pk = $model->getPk ();

        $sorts = I('param.sort');

        $id     = intval(I('id'));

        if(!is_array($sorts) && isset($id))$sorts = array($id=>$sorts);

        if(empty($sorts))   $this->error(L('PARAM_ERROR'));

        foreach ($sorts as $id=>$sort){

            $result=$model->save(array($pk=>$id,'sort'=>intval($sort)));

        }

        if(in_array(CONTROLLER_NAME,$this->cache_model)) savecache(CONTROLLER_NAME);

        $jumpUrl = I('forward')?I('forward'):U(CONTROLLER_NAME.'/index');

        $this->assign("jumpUrl",$jumpUrl);

        if($result!==false){

            $this->success(L('EDIT_OK'));

        }else{$this->error(L('EDIT_ERROR'));}

    }

	public function mendian(){

        $mendain_info = M('Shops')->where('id ='.MID)->find();

		// $url = U('mobile/shop/mendian_index',array('id'=>$mendain_info['id']),true,true);

        $url = U('mobile/index/index','',true,true);

        $wximg_url = U('Home/qrcode/index',array('data'=>urlencode($url)));

		$mendain_info['url_img'] = $wximg_url;

        $this->assign('mendain_info',$mendain_info);

	}

}

?>