<?php
// +----------------------------------------------------------------------
// |微信自定义菜单管理
// +----------------------------------------------------------------------
// | ThinkOAO （Online And Offline）
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.thinkoao.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xiaogg <xiaogg@sina.cn>
// +----------------------------------------------------------------------
namespace Admin\Controller;
class WxMenuController extends BaseController{
    public function _initialize() {
        parent::_initialize ();
    }
    public function _before_index(){        
      /*  $big_menu = array('添加菜单' => U('add'),'生成微信自定义菜单'=>U('updatemenu'));
        $this->assign('big_menu', $big_menu);*/
        $this->getNodeTree('','');
    }
    public function _before_add(){
        $status['status'] = 1;
        $this->assign($status);       
        $this->getNodeTree(1);
    }
    public function _before_edit(){
        $id = I('param.id');
        $map = array();
        $map['id'] = $id;
        $data = M('WxMenu')->where($map)->field(true)->find();
        if($data['keyword']){
            $data['status'] = 1;
        }else{
            $data['status'] = 2;
        }
        $this->assign($data);
        $this->getNodeTree(1);
    }
    public function _before_insert(){        
        $wxmenu=$this->getNodeTree(1);
        if(count($wxmenu[1])>=3 && $_POST['pid']==0){
            $this->error('一级菜单最多只能添加三个!');exit;
        }
    }
    public function insert(){
        $data=I('param.');
        if($data['status'] == 1){
            $data['url_navtype'] = '';
            $data['url_modulename'] = '';
            $data['url_param'] = '';
            $data['url'] = '';
            $data['sort'] = '';
        }elseif($data['status'] == 2){
            $data['keyword'] = '';
        }
        $model = D (CONTROLLER_NAME);
        $modelcreate=$model->create ();
        $modelcreate['url']=return_urlrules($data['url']);
        $id = $model->add($modelcreate);
        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 _before_update(){        
        $wxmenu=$this->getNodeTree(1);
        if(count($wxmenu[1])>=3 && $_POST['pid']==0 && $_POST['oldpid']!=$_POST['pid']){
            $this->error('一级菜单最多只能添加三个!');
        }
    }
    public function update (){//公共编辑
        $postdata=I('param.');
        $model=CONTROLLER_NAME;
        $data=D($model)->create();
        $data['url']=return_urlrules($postdata['url']);
        $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME.'/index');
        $id    = array_unique((array)I('id',0));
        $id    = is_array($id) ? implode(',',$id) : $id;
        if(empty($id))   $this->error(L('do_empty'));
        $where['id'] = str_exists($id,',')?array('in', $id):$id;
        $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 updatemenu(){
        if(C('BOUND_STATUS')!=2){
    		$appid = C('WX_APPID');
    		$appsecret = C('WX_APPSECRET');
            if(empty($appid) || empty($appsecret))$this->error('请填写APPID和APPSECRET后再更新菜单!');
        }
        $wxmenu=$this->getNodeTree('','');
        foreach($wxmenu[1] as $k=> $v){
            $menu[$k]['name']=$v['name'];
            if($wxmenu[2][$v['id']]){
                foreach($wxmenu[2][$v['id']] as $key=>$val){
                    if(!empty($val['url']))$val['url']=geturl($val['url'],array('URL_MODEL'=>2),true,true);
                    $menu[$k]['sub_button'][$key]['name']=$val['name'];
                    if(!empty($val['url'])){
                        $menu[$k]['sub_button'][$key]['type']='view';
                        $menu[$k]['sub_button'][$key]['url']=$val['url'];
                    }elseif(str_exists($val['keyword'],'wx') && strlen($val['keyword'])>=18){//小程序
                        $menu[$k]['sub_button'][$key]['type']='miniprogram';
                        $menu[$k]['sub_button'][$key]['url']='http://mp.weixin.qq.com';
                        $menu[$k]['sub_button'][$key]['appid']=$val['keyword'];
                        $menu[$k]['sub_button'][$key]['pagepath']='pages/index/index';      
                    }else{
                        $menu[$k]['sub_button'][$key]['type']='click';
                        $menu[$k]['sub_button'][$key]['key']=$val['keyword'];
                    }
                }
            }else{
                if(!empty($v['url']))$v['url']=geturl($v['url'],array('URL_MODEL'=>2),true,true);
                if(!empty($v['url'])){
                    $menu[$k]['type']='view';
                    $menu[$k]['url']=$v['url'];
                }else{
                    $menu[$k]['type']='click';
                    $menu[$k]['key']=$v['keyword'];
                }
            }
        }
        $menulist['button']=$menu;
        $weixin = new \Common\Vendor\WeixinChat;
        $result=json_decode($weixin->setMenu($this->json_encode_cn($menulist)),true);
        if($result['errcode']==0){
            $this->success('更新成功');
        }else{            
            $this->error('更新失败!错误信息为:'.$result['errmsg']);
        }
    }
	private function json_encode_cn($data) {
		$data = json_encode ( $data );
        $str= preg_replace ( "/\\\u([0-9a-f]{4})/ie", "iconv('UCS-2BE', 'UTF-8', pack('H*', '$1'));", $data );
        $str =str_replace('&amp;','&',$str);
		return $str;
	}
    /* 得到节点树 */
	private function getNodeTree($type='',$field='id,name',$uid = '') {
	   //支付方式
       if(!$field)$field=true;
       $wxmenu[1]=M('WxMenu')->where(array('pid'=>'0'))->field($field)->order('sort,id desc')->select();
       if(!$type){        
       foreach($wxmenu[1] as $v){
           $wxmenu[2][$v['id']]=M('WxMenu')->where(array('pid'=>$v['id']))->field($field)->order('sort,id desc')->select();
       }$wxmenu[2]=array_filter($wxmenu[2]);
       $this->assign('wxmenu2',$wxmenu[2]);
       }
       $this->assign('wxmenu1',$wxmenu[1]);       
       return $wxmenu;
	}
}