<?php
// +----------------------------------------------------------------------
// | 系统配置控制器
// +----------------------------------------------------------------------
// | ThinkOAO （Online And Offline）
// +----------------------------------------------------------------------
// | Copyright (c) 2016 http://www.hanchao9999.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: xiaogg <xiaogg@sina.cn>
// +----------------------------------------------------------------------
namespace Admin\Controller;
class ConfigUappController extends BaseController {

	public function _initialize() {
		parent::_initialize();
		$this->model = D('Config');
        $this->name='Dragedit';
        $this->currentid = intval(I('id'));
        $this->codelist = array(
            array('code'=>'red','value'=>'rgb(201, 24, 27)'),
            array('code'=>'yellow','value'=>'rgb(255, 147, 0)'),
            array('code'=>'green','value'=>'rgb(9, 187, 7)'),
            array('code'=>'blue','value'=>'rgb(74, 144, 226)'),
        );
        $is_auth=check_use_auth("WEBSHOP");
        if($is_auth['status']==0){
            $this->error('该版本没有此权限',$is_auth['url']);return;
        }
	}
	//添加新设置
	public function add() {
	   if(IS_POST){
            $data = $this->model->create();
            if($data){
                if($this->model->add()){
                    S('DB_CONFIG_DATA',null);
                    $this->success('新增成功', U('index'));
                } else {
                    $this->error('新增失败');
                }
            } else {
                $this->error($this->model->getError());
            }
        } else {
            $grouplist=strtoarray(C('CONFIG_GROUP_LIST'));
            $grouplist[0]='隐藏';
            $this->assign('TYPE_LIST',strtoarray(C('CONFIG_TYPE_LIST')));
            $this->assign('GROUP_LIST',$grouplist);
            $this->assign('info',null);           
            $this->display('edit');
        }
	}
    //添加修改模板
    public function edit(){
        if(IS_POST){
            $param = I('post.');
            $data['name'] = $param['name'];
            $data['thumb_img'] = $param['thumb_img'];
            $data['code'] = $param['code'];
            $data['is_wxsmall'] = 2;
            $data['update_time'] = NOW_TIME;
            if($this->currentid>0){
                $map['id'] = $this->currentid;
                $result = M('Dragedit')->where($map)->save($data);
            }else{
                $data['add_time'] = NOW_TIME;
                $result = M('Dragedit')->add($data);
            }
            if($result !==false){
                $this->success('保存成功',geturl('ConfigUapp/index'));
            }else{
                $this->error('保存失败');
            }
        }else{
            $list = array();
            if($this->currentid>0){
                $map['id'] = $this->currentid;
                $info = M('Dragedit')->where($map)->field('id,name,thumb_img,code')->find();
            }
            $this->assign('codelist', $this->codelist);
            $this->assign('info', $info);
            $this->display();
        }
    }
    //设置默认模板
    public function setting(){
        if($this->currentid<1)$this->error('参数错误');
        $map['id'] = array('gt',0);
        $map['is_wxsmall'] = 2;
        M($this->name)->where($map)->setField('is_default',0);
        $map['id'] = $this->currentid;
        $result = M($this->name)->where($map)->setField('is_default',1);
        if($result !==false){
            $this->success('设置成功');
        }else{
            $this->error('设置失败');
        }
    }
    /**
     * 编辑内容页
     */
    public function vindex(){
        if($this->currentid<1)$this->error('参数错误');
        $urlrules = geturlrules(3);
        $add = array('id'=>'url','name'=>'自定义URL');
        array_unshift($urlrules, $add);
        foreach($urlrules as $key=>$val){
            if($val['id']==26){
                unset($urlrules[$key]);
            }
        }
        //获取筛选条件
        $HCorderlist = D('Common/Dragedit')->getorderlist();
        if($this->currentid>0){
            $map['id'] = $this->currentid;
            $content = M($this->name)->where($map)->getField('value');
            if($content){
                $this->assign('HCinitlist', $content);
            }else{
                $this->assign('HCinitlist', json_encode(array()));
            }
        }
        $this->assign('jumpUrl', geturl('Mobile/Index/index',array('id'=>$this->currentid,'key'=>base64_encode(C('HANCHAO_KEY').$this->currentid)),true,true));
        $this->assign('HCorderlist', json_encode($HCorderlist));
        $this->assign('urlrules', json_encode($urlrules));
        $this->display();
    }
    public function list_index(){
        if(!checksiteauth('WaiMai')){ exit;}
        $module='Mobile';
        $indexlist=getmodtpl('shops_index_','Takeout','',$module);
        $list = array();
        foreach($indexlist as $k=>$v){
            unset($list[0]);
            $list[$k]['id'] = strstr($v,'.',true);
            $list[$k]['thumb_img'] = APP_PATH.$module.'/View/'.get_default_theme($module).'/'.$pathdir.'Takeout'.'/'.str_replace('shops_index_',"",strstr($v,'.',true)).'.jpg';
            $list[$k]['name'] = str_replace('shops_index_',"",strstr($v,'.',true)).'模板';
        }
        $this->assign('list',$list);
        $list_tpl = C('LIST_TPL_APP');
        if(empty($list_tpl)) $list_tpl = "shop_index_list";
        $this->assign('tplimg',APP_PATH.$module.'/View/'.get_default_theme($module).'/'.$pathdir.'Takeout'.'/'.str_replace('shops_index_',"",$list_tpl).'.jpg');
        $list_tpll = str_replace('shops_index_',"",$list_tpl).'模板';
        if($list_tpl =="shop_index_list") $list_tpll='默认模板';
        $this->assign('list_tpl',$list_tpl);
        $this->assign('list_tpll',$list_tpll);
        $jumpurl = geturl('Mobile/takeout/shops_index',array('id'=>1),true,true);$jumpurl=str_replace('index.php?s=/','',$jumpurl);
        $this->assign('jumpqrcode',geturl('Home/Qrcode/index',array('data'=>urlencode($jumpurl))));
        $this->assign('jumpurl', $jumpurl);
        $postdata=I('get.');
        if($postdata) $config['LIST_TPL_APP']= $postdata['id'];
        if ($config && is_array($config)) {
                $vi=array();
                $this->model = D('Config');
                foreach ($config as $name => $value) {
                    $map = array('name' => $name);
                    if(is_array($value)){
                        foreach($value as $key=>$val){
                            $vi[]=implode(":",$val);
                        }$value = implode(",",$vi);
                     }
                     $this->model->where($map)->setField('value', $value);
                }
            S('DB_CONFIG_DATA', null);
            $this->success('应用成功', U('list_index'));exit;
        }
        $this->display();
    }
    public function tab_color(){
        $code=I('code');
        $return = array('status'=>0,'msg'=>'切换失败');
        if(!empty($code)){
            $map['name']='TEMPLATE_APP_THEME_COLOR';
            $result=M('config')->where($map)->setField('value',$code);
            if($result !==false){
                $return['status'] = 1;
                $return['msg'] = '切换成功';
            }
        }
        $this->ajaxReturn($return);
    }
    /**
     * 批量保存配置
     */
    public function save($config){
        if($config && is_array($config)){
            foreach ($config as $name => $value) {
                $map = array('name' => $name);
                $this->model->where($map)->setField('value', $value);
            }
        }
        if($config['MEMBER_UC'] && $config['MEMBER_UCONFIG']){//更新ucenter配置
        $con = "<?php\n".$config['MEMBER_UCONFIG'].";\n?>";
        oaofile(APP_PATH.'Member/Conf/uc.php', $con);
        }
        S('DB_CONFIG_DATA',null);
        $this->success('保存成功！');
    }
	public function index() {
        $map=array();
        $map['is_wxsmall']=2;
        $list = M('Dragedit')->where($map)->field(true)->select();
        $default = array();
        foreach($list as $k=>$v){
            if($v['is_default']==1){
                $default = $v;break;
            }
        }
        $jumpurl = geturl('Mobile/Index/index',array(),true,true);$jumpurl=str_replace('index.php?s=/','',$jumpurl);
        $jumpurl=str_replace('index/index.html','',$jumpurl);
       // var_dump($default);
        $this->assign('default', $default);
        $this->assign('jumpqrcode',geturl('Home/Qrcode/index',array('data'=>urlencode($jumpurl))));
        $this->assign('jumpurl', $jumpurl);
        $this->assign('list', $list);
        $this->assign('currentcode', idtoname('TEMPLATE_APP_THEME_COLOR','Config','value','name',false));
        $this->assign('codelist', $this->codelist);
        //判断权限
        $waimai_auth=checksiteauth('WaiMai');
        $this->assign('waimai_auth',$waimai_auth);
        $this->display();

	}
    // 获取某个标签的配置参数
    public function group() {
        $grouplist   =   strtoarray(C('CONFIG_GROUP_MOBILE_LIST'));
        $list   =   $this->model->where(array('status'=>1))->field('id,name,title,group,extra,value,remark,type')->order('sort')->select();
        if($list) {
            $this->assign('list',$list);
        }$this->assign('grouplist',$grouplist);
        if(I('is_content'))$this->assign('is_content',I('is_content'));
        $this->display();
    }
    // 微信绑定
	public function wx_bound(){	  
	   if(C('BOUND_STATUS')==1){
	       $this->redirect('group',array('is_content'=>7));return;
	   }
        $wx = new \Common\Vendor\Weixinopen;
        $res = $wx->wxconfig(C('appid'));
		$data = array();
		$is_author = 0;//是否已经授权(0:否,1:是)		
		if(!empty($res)){
			$is_author = 1;		
			$result=$wx->get_authorizer_info();
			
			$func_info = $result['authorization_info']['func_info'];
			$info_arr = array();
			if($func_info){
				foreach($func_info as $val){
					foreach($val['funcscope_category'] as $k => $v){
						$info_arr[] = $v;
					}
				}
			}
			// 授权方认证类型，-1代表未认证，0代表微信认证，1代表新浪微博认证，2代表腾讯微博认证，3代表已资质认证通过但还未通过名称认证，4代表已资质认证通过、还未通过名称认证，但通过了新浪微博认证，5代表已资质认证通过、还未通过名称认证，但通过了腾讯微博认证
			$data['nick_name'] = $result['authorizer_info']['nick_name'];
			$data['service_type_info'] = $result['authorizer_info']['service_type_info'];
			// $data['qrcode_url'] = $result['authorizer_info']['qrcode_url'];
			// if($result['authorizer_info']['qrcode_url']){
				// print_r($result['authorizer_info']['qrcode_url']);exit;
				// $this->save_pic($result['authorizer_info']['qrcode_url']);
			// }
			$data['qrcode_url'] =$result['authorizer_info']['qrcode_url'];
            /*if(C('WEIXIN_PUBLIC_NUMBER_URL') != $data['qrcode_url']){
                $map = $save = array();
                $map['name'] = 'WEIXIN_PUBLIC_NUMBER_URL';
                $save['value'] = $data['qrcode_url'];
                M('Config')->where($map)->save($save);
            }*/
			$data['business_arr'] = $result['authorizer_info']['business_info'];
			$data['info_arr'] = $info_arr;


			$type = 0;
			if($data['service_type_info']['id'] == 2){
				if($result['authorizer_info']['verify_type_info']['id'] == -1){
					$type = 3;
				}else{
					$type = 4;
				}
			}else{
				if($result['authorizer_info']['verify_type_info']['id'] == -1){
					$type = 1;
				}else{
					$type = 2;
				}
			}
            //绑定开放平台
            $open_openid=C("OPEN_APPID");
            $appid=C('appid');
            if($open_openid){
                $authorizer_appid=$res['authorizer_info']['authorizer_appid'];
                $this->bind_openid($authorizer_appid,$open_openid,0);
            }else{
                $wx->open_bind_wxall($appid);
            }
			if(C('WX_TYPE') != $type){
				$map = $save = array();
				$map['name'] = 'WX_TYPE';
				$save['value'] = $type;
				M('Config')->where($map)->save($save);
			}
		}
		$data['is_author'] = $is_author;
		// echo "<pre>";print_r($data);exit;
		$this->assign($data);
		$this->display();
	}
    public function save_pic($qrcode_url){
		$appid = C('appid');
		$image=array(
			'name'=>"qrcodeurl_".$appid.".png",
			'type'=>'image/png',
			'tmp_name'=>$qrcode_url,
			'error'=>'0',
			'size'=>filesize($qrcode_url),
			'oss'=>1
		);
		echo "<pre>";print_r($image);
		$res=uploadimg($image);
		print_r($res);exit;
		
	}
    public function wx_small_bound(){
        
        $morecode=I('morecode');
        $this->assign('morecode',$morecode);
        $wx = new \Common\Vendor\Weixinopen;
        $siteid=C('appid');
        $cachename_moresmall='config_moresmall.php';
        $config_morelist=$wx->wxcache($cachename_moresmall);
        $appid=$config_morelist[$siteid.'_'.$morecode];
        if(empty($appid)){$is_author = 0;}
        if($appid) {
            $res = $wx->wxconfig($appid, '', 1);
            $data = array();
            $is_author = 0;//是否已经授权(0:否,1:是)
            if (!empty($res)) {
                $is_author = 1;
                $result = $wx->get_authorizer_info($appid);
                $func_info = $result['authorization_info']['func_info'];
                $info_arr = array();
                if ($func_info) {
                    foreach ($func_info as $val) {
                        foreach ($val['funcscope_category'] as $k => $v) {
                            $info_arr[] = $v;
                        }
                    }
                }
                // 授权方认证类型，-1代表未认证，0代表微信认证，1代表新浪微博认证，2代表腾讯微博认证，3代表已资质认证通过但还未通过名称认证，4代表已资质认证通过、还未通过名称认证，但通过了新浪微博认证，5代表已资质认证通过、还未通过名称认证，但通过了腾讯微博认证
                $data['nick_name'] = $result['authorizer_info']['nick_name'];
                $data['service_type_info'] = $result['authorizer_info']['service_type_info'];
                // $data['qrcode_url'] = $result['authorizer_info']['qrcode_url'];
                // if($result['authorizer_info']['qrcode_url']){
                // print_r($result['authorizer_info']['qrcode_url']);exit;
                // $this->save_pic($result['authorizer_info']['qrcode_url']);
                // }
                $data['qrcode_url'] = $result['authorizer_info']['qrcode_url'];
                $data['business_arr'] = $result['authorizer_info']['business_info'];
                $data['info_arr'] = $info_arr;


                $type = 0;
                if ($data['service_type_info']['id'] == 2) {
                    if ($result['authorizer_info']['verify_type_info']['id'] == -1) {
                        $type = 3;
                    } else {
                        $type = 4;
                    }
                } else {
                    if ($result['authorizer_info']['verify_type_info']['id'] == -1) {
                        $type = 1;
                    } else {
                        $type = 2;
                    }
                }
                if (C('WX_TYPE') != $type) {
                    $map = $save = array();
                    $map['name'] = 'WX_TYPE';
                    $save['value'] = $type;
                    M('Config')->where($map)->save($save);
                }
                //绑定开放平台
                $open_openid = C("OPEN_APPID");
                $wxinfo = $wx->wxconfig($appid, '', 1);
                $authorizer_appid = $wxinfo['authorization_info']['authorizer_appid'];
                if ($open_openid) {
                    $this->bind_openid($authorizer_appid, $open_openid, 1);
                } else {
                    $appid = C('appid');
                    $wx->open_bind_wxall($appid);
                }
            }
        }
        $data['is_author'] = $is_author;
        // echo "<pre>";print_r($data);exit;
        $this->assign($data);
        $this->display();
    }
    /**绑定开放 平台
     * @param $appid
     * @param $openid
     */
    public function bind_openid($appid,$openid,$type){
        $siteid=C('APPID');
        $wx = new \Common\Vendor\Weixinopen;
        $old= $wx->wxconfig($appid,'',$type);
        if($old['authorization_info']['wx_open_appid'])return true;
        if(empty($old['authorization_info']['wx_open_appid'])){
            $res=$wx->open_bind($appid,$type,$openid);
            if($res['errcode']==0){return true;
            }else{
                return false;
            }
        }
    }
}
?>