<?php
/**
 * 账号中心
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author zhaoh <zhao@qq.com>
 */

namespace Shop\Controller;
use Think\Controller;
class AccountController extends BaseController {
	public function _initialize()
    {
        parent::_initialize();
		$shops_info=session('shops_info');
        if(empty($shops_info['id'])) $this->error('身份过期，请重新登录',U('Shop/Register/shop_login'));
        $map=array();
        $map['id']=$shops_info['shop_id'];
        $shop_info=M("Shops")->where($map)->field(true)->find();
        $this->assign("shop_info",$shop_info);
        $this->mendian();

        // 权限判断 1117 ggw
        	$model='';
        	switch (ACTION_NAME) {
        		case 'account_index':
        			$model='account';
        			break;
        		case 'recharge':
        			$model='money';
        			break;
        		case 'accountlog':
        			$model='money';
        			break;	
        		case 'guide':
        			$model='guide';
        			break;
        		case 'setting':
        			$model='shop';
        			break;
        	}
        	if($model){
        		$suc=D('Shops')->shop_option(MID,$model);
        		if(!$suc){$this->error('该店铺没有此权限，请联系管理员授权！');die;}
        	}

    }
	/**
	 * 店铺日志
	 */
    public function index(){
		$post=I('param.');
		$tabid=$post['tabid'];
		if(empty($tabid)){
			$this->get_action_arr();
			$list=D('Account')->action_list($post);
			$this->assign($list);$this->assign($post);
		}
		$tabid=$tabid?$tabid:'index';
        $this->display($tabid);
    }
	/**
	 * 店铺日志
	 */
	public function actionlog(){
		$post=I('param.');
		$tabid=$post['tabid'];
		if(empty($tabid)){
			$this->get_action_arr();
			$list=D('Account')->action_list($post);
			$this->assign($list);$this->assign($post);
		}
		$tabid=$tabid?$tabid:'actionlog';
        $this->display($tabid);
    }
	/**
	 * 门店子账号
	 */
	public function account_index(){
		if(MID){

			$postdata=I('param.');
			$this->assign($postdata);
			$tabid=$postdata['tabid'];
			if(empty($tabid)){
				$auth_code = 'employee_list';
		        $ret=D('Shop/Shops')->shop_account_option($auth_code);
		        if($ret['status']!=1) {$this->error($ret['msg']);}
				if($postdata['keyword'])$where['id|name|login_name|mobile']=array('like','%'.$postdata['keyword'].'%');
				$where['shop_id'] = MID;
				$where['pid'] = array('neq',0);
				if($postdata['print']=='print') $list['list']=M('ShopsAccount')->where($where)->field(true)->select();
				else $list=page_list('ShopsAccount',$where);
				foreach($list['list'] as $k=>$v){
					$list['list'][$k]['role_id'] = idtoname($v['id'],'ShopsRoleAccount','role_id','account_id',false);
				}
				if($postdata['print']=='print'){$this->export_account_index($list['list']);}
				$this->assign($list);
			}elseif($tabid=='add_account'){
				$auth_code = 'employee_add';
		        $ret=D('Shop/Shops')->shop_account_option($auth_code);
		        if($ret['status']!=1) {$this->error($ret['msg']);}
				$login_name = shop_account_sn();
				$this->assign('login_name', $login_name);
				
				$this->role_list();
			}elseif($tabid=='edit_account'){
				$auth_code = 'employee_edit';
		        $ret=D('Shop/Shops')->shop_account_option($auth_code);
		        if($ret['status']!=1) {$this->error($ret['msg']);}
				$id = $postdata['id'];
				if($id){
					$map['id'] = $id;
					$map['shop_id'] = MID;
					$info=M('ShopsAccount')->where($map)->field(true)->find();
					$this->assign($info);
					$this->assign($id);
					$role_id = idtoname($id,'ShopsRoleAccount','role_id','account_id',false);
					
					$this->role_list($role_id);
					$tabid='add_account';
					$this->assign('menu_tab','');
				}
			}
		}
		$tabid=$tabid?$tabid:'account_index';
        $this->display($tabid);
    }
    public function export_account_index($list){
    	 $title = array('序号', '员工', '工号',  '角色','手机号', '注册时间');
        $data = array();
        foreach ($list as $k => $v) {
            $data[$k][] = $v['id'];
            $data[$k][] = $v['name'];
            $data[$k][] = $v['login_name'];
            $data[$k][] = idtoname($v['role_id'],'ShopsRole','title');
            $data[$k][] = $v['mobile'];
            $data[$k][] = time_format($v['updatetime']);
        }
        export_xls($title, $data, 'utf8');
        unset($title, $data);
        exit;


    }
	
	public function role_list($role_id = 0){
		$r_where = array();
		$r_where['status'] = 1;
		$role_list = M("ShopsRole")->where($r_where)->field('id,title')->select();
		foreach($role_list as $k => $v){
			if($role_id == $v['id']){
				$role_li.="<option selected='selected' value='".$v['id']."'>".$v['title']."</option>";
			}else{
				$role_li.="<option value='".$v['id']."'>".$v['title']."</option>";
			}
		}
		$this->assign('role_li', $role_li);
	}
	
	//编辑员工信息和添加
	public function sub_account(){
		$shops_info = session('shops_info');
		$p_map['id'] = $shops_info['id'];
		$pid_info = M('ShopsAccount')->where($p_map)->find();
		if($pid_info['pid'] == 0){
			$pid = $pid_info['id'];
		}else{
			$pid = $pid_info['pid'];
		}
		$shop_id = $pid_info['shop_id'];
		$uid = $pid_info['uid'];
		
		$postdata = I('param.');
		$id = $postdata['id'];
		if($id){
			$map['id'] = $id;
			$count = M('ShopsAccount')->where($map)->find();
			$auth_code = 'employee_edit';
		    $ret=D('Shop/Shops')->shop_account_option($auth_code);
	        if($ret['status']!=1) {$this->error($ret['msg']);}
		}else{
			$auth_code = 'employee_add';
	        $ret=D('Shop/Shops')->shop_account_option($auth_code);
	        if($ret['status']!=1) {$this->error($ret['msg']);}
		}
		if($count){
			//判断密码是否修改
			if ($postdata['password']) {
				if ($postdata['password'] != $postdata['password_true']) {
					$this->error('两次输入的密码不相同');
				}
				$postdata['salt'] = randStr();
				$postdata['password'] = creatpwd($postdata['password'], 'HANCHAO'.$postdata['salt']);
			} else {
				unset($postdata['password']);
			}
		}else{
			$postdata['salt'] = randStr();
            $postdata['password'] = creatpwd($postdata['password'], 'HANCHAO'.$postdata['salt']);
		}
		//判断手机号和登录账号是否存在
		$this->sub_check($postdata['mobile'],$postdata['login_name'],$id);
		
		$postdata['updatetime'] = NOW_TIME;
		if($count){
			$ret = M('ShopsAccount')->where($map)->save($postdata);
			if ($ret) {
				$ra_where['account_id'] = $id;
				$num = M('ShopsRoleAccount')->where($ra_where)->count();
				$add_data = array();
				$add_data['role_id'] = $postdata['role_id'];
				if($num){
					M('ShopsRoleAccount')->where($ra_where)->save($add_data);
				}else{
					$add_data['account_id'] = $id;
					M('ShopsRoleAccount')->add($add_data);
				}
				$this->success('修改成功！',U('Account/account_index'));
			}else{
				$this->error('修改失败！',U('Account/account_index'));
			}
		}else{
			$postdata['shop_id'] = $shop_id;
			$postdata['pid'] = $pid;
			$postdata['uid'] = $uid;
			$result = M('ShopsAccount')->where($map)->add($postdata);
			if ($result) {
				$r_add_data['account_id'] = $result;
				$r_add_data['role_id'] = $postdata['role_id'];
				$return = M('ShopsRoleAccount')->add($r_add_data);
				if($return){
					$this->success('添加成功！',U('Account/account_index'));
				}else{
					$this->error('添加失败！',U('Account/account_index'));
				}
			}
		}
	}
	//判断手机号和登录账号是否存在
	public function sub_check($mobile = 0,$login_name = 0,$id = 0){
		//判断手机号是否存在
		if ($mobile) {
			$where = array();
			if($id){$where['id'] = array('neq',$id);}
			$where['mobile'] = $mobile;
			$is_mobile = M('ShopsAccount')->where($where)->count();
			if($is_mobile){
				$this->error('该手机号已存在');
			}
		}
		//判断登录账号是否存在
		if ($login_name) {
			$where = array();
			if($id){$where['id'] = array('neq',$id);}
			$where['login_name'] = $login_name;
			$is_login_name = M('ShopsAccount')->where($where)->count();
			if($is_login_name){
				$this->error('该登陆账号已存在');
			}
		}
	}
	
	/**
     * 验证手机号是否存在
     */
    public function checkmobile(){
        $where['mobile'] = I('phone');
        $where['id'] = array('neq',I('id'));
        $is_mobile = M('ShopsAccount')->where($where)->count();
        $return['status']=0;
        if($is_mobile){
			$return['data'] = "该手机号已存在";
			$this->ajaxReturn($return);
        }
    }
	/**
     * 验证登陆账号是否存在
     */
    public function accountlogin_name(){
        $where['login_name'] = I('login_name');
        $where['id'] = array('neq',I('id'));
        $is_login_name = M('ShopsAccount')->where($where)->count();
        $return['status']=0;
        if($is_login_name){
			$return['data'] = "该登陆账号已存在";
			$this->ajaxReturn($return);
        }
    }
	//删除员工
	public function delete_account(){
		$auth_code = 'employee_del';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);}
		$return['status'] = 0;
		$id = I('param.id');
		if($id){
			$map['id'] = $id;
			$map['shop_id'] = MID;
			$num=M('ShopsAccount')->where($map)->count();
			if($num){
				$ret=M('ShopsAccount')->where($map)->delete();
				if($ret){
					$return['status'] = 1;
					$return['info'] = '删除成功！';
				}else{
					$return['info'] = '删除失败！';
				}
			}
		}
		$this->ajaxReturn($return);	
	}
	/**
	 * 消费记录
	 */
	public function accountlog(){
		$post=I('param.');
		$tabid=$post['tabid'];
		if($post['print']=='print'){$this->export_account($post);}
		if(empty($tabid)){
			//变更类型
			$type_status=array();
			$type_status[1]='余额';
			$type_status[2]='未结算';
			$type_status[3]='待结算';
			$type_status[4]='冻结';
			$type_status[6]='销售总额';
			$type_status[7]='总积分';
			$list=D('Account')->account_list($post);
			//店铺资金
			$map['id']=MID;
			$shopinfo=M('Shops')->where($map)->field('total_revenues,freeze_price,shop_type')->find();
			$this->assign($list);$this->assign($post);
			$this->assign('type_status',$type_status);
			$this->assign('shopinfo',$shopinfo);
		}
		$tabid=$tabid?$tabid:'accountlog';
        $this->display($tabid);
    }
    /**
    *导出
    */
     public function export_account($post){
     	$map['shop_id']=MID;
		if(!empty($post['time_form'])){$map['change_time'][]=array('egt',strtotime($post['time_form']));}
		if(!empty($post['time_to'])){$map['change_time'][]=array('elt',strtotime($post['time_to']));}
		if(!empty($post['order_sn'])){$map['order_id']=idtoname($post['order_sn'],'OrderInfo','id','order_sn');}
		if(!empty($post['type'])){$map['type']=$post['type'];}
		$list=M('ShopbalanceLog')->where($map)->field(true)->order('id desc')->select();
		 $title = array('序号', '订单号', '变更数量', '变更描述','变更类型','变更时间');
        $data = array();
        foreach ($list as $k => $v) {
            $data[$k][] = $v['id'];
            $data[$k][] = "'".idtoname($v['order_id'],'OrderInfo','order_sn');
            $data[$k][] = ($v['change_type']==0?'+':'-').$v['change_num'];
            $data[$k][] = $v['change_desc'];
            $data[$k][] = $v['type']==1?'余额': $v['type']==2?'未结算': $v['type']==3?'待结算': $v['type']==4?'冻结': $v['type']==6?'销售总额':'';
            $data[$k][] = date('Y-m-d H:i:s',$v['change_time']);

        }
        export_xls($title, $data, 'utf8');
        unset($title, $data);
        exit;

     }
	public function get_action_arr(){
		$map['status']=1;
		$map['type']=3;
		$actionarr=M('Action')->where($map)->field('id,title')->select();
		foreach($actionarr as $k=>$v){
			$arr[$v['id']]=$v['title'];
		}
		$this->assign('actionarr',$arr);
	}
	
    /**
     *修改门店信息，登录密码，支付密码
     */
    // public function updateinfo(){
    //     if (IS_POST) {
    //         $postdata = I('param.');
    //         $shops_call = M('Shops')->where('id='.$postdata['id'])->getField('shops_call');
    //         if(!empty($postdata['shops_call']) && $postdata['shops_call']!=$shops_call){
    //         	$result = callee_notify($postdata['shops_call'],1);
    //         	if($result['result']==1100 && $result['Result']==1){
	   //          	$res = callee_notify($postdata['shops_call'],2);
	   //          	if(!($result['result']==1100 && $result['Result']==1)){
	   //         			$return['msg']='呼叫中心电话绑定失败，请联系管理员';
				// 		$this->ajaxReturn($return);
	   //         		}
	   //         	}else{
	   //         		$return['msg']='呼叫中心电话绑定失败，请联系管理员';
				// 	$this->ajaxReturn($return);
				// }
    //         }
    //         $postdata['pc'] = 'pc';
    //         $data = D('Common/Shops')->shop_infor($postdata);
    //         $this->ajaxReturn($data);
    //     }
    // }
    public function updateinfo(){
    	$auth_code = 'shopssetting_set';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->ajaxReturn($ret);exit;}
        if (IS_POST) {
            $postdata = I('param.');
			$shops_info=session('shops_info');
			$appid = C('appid');
			// 1105新加 之前修改密码没流程
			if($postdata['infos']=='pwd'||$postdata['infos']=='paypwd'){ 
				$data = D('Common/Shops')->shop_infor($postdata);
				$this->ajaxReturn($data);
			}
			
			if(!$postdata['business_hours_start']){
				$postdata['business_hours_start'] = '0:00';
			}
			if(!$postdata['business_hours_end']){
				$postdata['business_hours_end'] = '23:00';
			}

            $postdata['pc'] = 'pc';
			// echo "<pre>";print_r($postdata);exit;
			$map = array();$map['shop_id'] = MID;$map['pid'] = 0;
			$postdata['sid'] = M('ShopsAccount')->where($map)->getField('id');
			$postdata['shop_id'] = MID;
			
			$result=D('App/Shops')->edit_shops($postdata);
			$data['status']=$result['status'];
			$data['msg']=$result['msg'];
            $this->ajaxReturn($data);
        }
    }
	/**
	 * 充值提现 非加盟店不可进入
	 *1106将get_money变为get_money_new
	 */
    public function recharge(){
    	// 判断是否加盟店
    	$shop_info=session('shops_info');
    	$shop_type=M('Shops')->where('id ='.$shop_info['shop_id'])->getField('shop_type');
    	if($shop_type!=2){$this->error('店铺类型错误！');die;}
    	//判断结束
		$post=I('param.');
		$tabid=$post['tabid']='get_money_new';//完成充值时删掉最后=
		if(empty($tabid)){//充值
			
		}elseif($tabid=='get_money_new'){//提现
			$return=D('Shops')->option(10,STYPE);
			if($return == 0){
				// $this->error('你还没添提现的权限，请联系管理员！');
				// $tabid = 'recharge';
			}
			$payfree = C('SHOP_TIXIAN_FREE');
			if ($payfree < 1) {
				$num = $payfree * 100;
				$this->assign('num', $num);
			}
			$shops_info=M('Shops')->where('id='.MID)->field(true)->find();
			$this->assign('shops_info', $shops_info);
			// $this->getmemberbank();
			$this->getmemberbank_new();

		}
        $tabid=$tabid?$tabid:'recharge';
        $this->display($tabid);
    }
    /*
	*获取提现银行 会员提现方式剔除余额即可
    */
     private function getmemberbank_new(){
     	$banks=array_unique(explode(',',C('MEMBER_BANK')));
		foreach($banks as $key=>$v){
			if($key ==1){continue;}	;//剔除余额
			$banksarr[$key+1]=$v;
		}
		$this->assign('banks',$banksarr);
     }
   
	/**
	 * 充值操作
	 */
    public function go_recharge(){
        $postdata = I('post.');
        $result = D('Common/Withdrawals')->recharge($postdata);
        if ($result['status']) {
            $result['url'] = U('Home/Pay/go_buy', array('id' => $result['log_id']));
        }
        $this->ajaxReturn($result);
    }
	/**
	 * 提现操作
	 */
    public function go_withdrawals(){
        $postdata = I('post.');
        $result = D('Common/Withdrawals')->shop_get_money($postdata);
        if ($result['status'] == 1) {$result['url'] = U('Account/accountlog');}
        $this->ajaxReturn($result);
    }
	/**
	 * 添加提现银行
	 */
    public function add_bank(){
        $postdata = I('post.');
        $result = D('Common/Withdrawals')->add_bank($postdata);
        if ($result['status']) $result['url'] = U('Account/recharge',array('tabid'=>'get_money'));
        $this->ajaxReturn($result);
    }
	/**
	 * 提现银行信息
	 */
    private function getmemberbank(){
        $map['uid'] = MID;
        $map['status'] = 1;
		$map['type'] = 1;
        $bank_info = M('MemberBank')->where($map)->field('name,bankname,bankcode')->find();
		
        if ($bank_info['bankcode']) {
            $length = strlen($bank_info['bankcode']);
            if (str_exists('@', $bank_info['bankcode'])) {
                $bankcodearr = explode('@', $bank_info['bankcode']);
                $bank_info['bankcode'] = substr($bankcodearr[0], 0, (strlen($bankcodearr[0]) - 4)) . '****@' . $bankcodearr[1];
            } else {
                $bank_info['bankcode'] = substr($bank_info['bankcode'], 0, ($length - 4)) . '****';
            }
        }
        $this->assign('bank_info', $bank_info);
        $banks = array_unique(explode(',', C('MEMBER_BANK')));
        foreach ($banks as $v) {
            $banksarr[$v] = $v;
        }
        $this->assign('banks', $banksarr);
    }
    /**
      *修改支付密码页面
      */
    public function security(){
    	$shop_info=session('shops_info');
	    if($shop_info['first_shop_id'] && $shop_info['first_shop_id']!==$shop_info['shop_id']){
	    	$this->error('请登录本门店管理帐号后修改密码！');
	    	unset($tabid);
	    }
    	$shop_id = MID;
        if($shop_id){
            $shop_info = M('Shops')->where('id ='.$shop_id)->field(true)->find();
            $this->assign($shop_info);
        }
        $this->assign('tplseo_title', '支付密码' . '_' . C('WEB_SITE_TITLE'));
        $this->assign('page_title', '支付密码');
        $this->display();
    }
  //   public function shops_setting(){
  //   	$postdata=I('param.');
		// $tabid=$postdata['tabid'];
  //       if(empty($tabid)){
	 //    	$info = M('Shops')->field(true)->find(MID);
	 //    	$this->assign($info);
	 //    }elseif($tabid=='modify_psw'){
	 //    }elseif($tabid=='print_template'){
		// 	$id=I('param.id');
		// 	$print_template=idtoname($id,'Shops','print_template');
		// 	$this->assign('print_template',$print_template);
		// 	$this->assign('id',$id);
		// }
		// $this->assign('menu_tab','');
	 //    $tabid=$tabid?$tabid:'shops_setting';
  //   	$this->display($tabid);
  //   }
    public function shops_setting(){
    	$postdata=I('param.');
		$tabid=$postdata['tabid'];
        $this->assign('title_ass','个人中心');
        $shop_info=session('shops_info');
	    if($tabid=='modify_psw'){
	    	if($shop_info['first_shop_id'] && $shop_info['first_shop_id']!==$shop_info['shop_id']){
	    		$this->error('请登录本门店管理帐号后修改密码！');
	    		unset($tabid);
	    	}
			$auth_code = 'shopssetting_pwd';
	        $ret=D('Shop/Shops')->shop_account_option($auth_code);
	        if($ret['status']!=1) {$this->error($ret['msg']);}
	    }else{
	    	$auth_code = 'shopssetting_set';
	        $ret=D('Shop/Shops')->shop_account_option($auth_code);
	        if($ret['status']!=1) {$this->error($ret['msg']);}
	    }
        if(empty($tabid)){
	    	$info = M('Shops')->field(true)->find(MID);
	    	$this->assign($info);
	    }elseif($tabid=='modify_psw'){

	    }elseif($tabid=='about_us'){
	    }elseif($tabid=='print_template'){
			$id=I('param.id');
			$print_template=idtoname($id,'Shops','print_template');
			$this->assign('print_template',$print_template);
			$this->assign('id',$id);
		}
		// $this->assign('menu_tab','');
	    $tabid=$tabid?$tabid:'shops_setting';
    	$this->display($tabid);
    }
    public function wx_code(){
    	$this->display();
    }
	/**
     * 验证登陆账号是否存在
     */
    public function checklogin_name(){
		$return['status']=1;
        $post = I('post.');
        $where['shop_id'] = array('neq',MID);
        $where['login_name'] = $post['login_name'];
		
        $is_login_name = M('ShopsAccount')->where($where)->count();
		
		$s_where['id'] = array('neq',MID);
        $s_where['login_name'] = $post['login_name'];
		
        $is_login_name_s = M('Shops')->where($s_where)->count();
        $return['status']=0;
        if($is_login_name && $is_login_name_s){
			$return['data'] = "该登陆账号已存在";
			$this->ajaxReturn($return);
        }
    }
	/**
     * 验证手机号是否存在
     */
    public function check_phone(){
		$return['status']=1;
        $post = I('post.');
        $where['shop_id'] = array('neq',MID);
        $where['mobile'] = $post['phone'];
        $is_login_name = M('ShopsAccount')->where($where)->count();
		
		$s_where['id'] = array('neq',MID);
        $s_where['contacts_phone'] = $post['phone'];
        $is_login_name_s = M('Shops')->where($s_where)->count();
        
        if($is_login_name && $is_login_name_s){
			$return['status']=0;
			$return['data'] = "该手机号已存在";
			$this->ajaxReturn($return);
        }
    }
    /**
     * 通话记录
     */
    public function call_info(){
    	$this->display();
    }
	/**
     * 外卖打印打印模板
     */
    public function print_template(){
        $id=I('param.id');
        $print_template=idtoname($id,'Shops','print_template','id',false);
        $this->assign('print_template',$print_template);
        $this->assign('id',$id);
        $this->display();
    }
    //保存外卖模板
    public function save_printtemplate(){
        $id=I('param.id');
        $data['print_template']=I('param.print_template');
        $map['id']=$id;
        if(empty($data['print_template'])){
            $this->error("模板内容不能为空！");
        }
        $count = M('Shops')->where($map)->save($data);
        if($count>0){
            $this->success("保存成功",U('shop/account/shops_setting'),3);
        }else{
            $this->error("保存失败");
        }
    }
    //默认外卖打印模板
    public function default_template(){
       // $print_template=C('PRINT_TEMPLATE');
        $return=array('status'=>0,'info'=>'');
        if(empty($print_template)){$return['info']='未设置默认模板';$this->ajaxReturn($return);}
        $return['status']=1;
        $return['info']=htmlspecialchars_decode($print_template);
        $this->ajaxReturn($return);
    }
	/**
     * 外卖门店列表
     */
    public function setting(){
    	$tabid=I('tabid');
        $shops_info=session('shops_info');
		$shop_id = $shops_info['shop_id'];
		if(empty($shop_id)){$this->error('参数错误！');}
		if($this->shops_info['pid'] != 0){
			// $this->error('您对此没有权限，请更换有权限的账户登录！');//112 注释
		}
		if($tabid=='kd_edit'){
			$auth_code = 'shipfel_kd';
	        $ret=D('Shop/Shops')->shop_account_option($auth_code);
	        if($ret['status']!=1) {$this->error($ret['msg']);exit;}
	        $this->get_shipping_fee($shop_id);
	        $this->assign('shop_id', $shop_id);
	        $this->display($tabid);
    	}else{
			$auth_code = 'shipfel_set';
	        $ret=D('Shop/Shops')->shop_account_option($auth_code);
	        if($ret['status']!=1) {$this->error($ret['msg']);exit;}
			$s_map = array();
			$s_map['shop_id'] = $shop_id;
			$s_map['pid'] = 0;
			$s_info=M('ShopsAccount')->where($s_map)->field('id,description')->find();
			$this->assign($s_info);
			$this->get_shipping_info($shop_id);
			$this->get_bagging_info($shop_id);
			
	        $this->display();
	    }
    }
    // 获取快递设置
    public function get_shipping_fee($shop_id){
		$map = array();
		$map['shop_id'] = $shop_id;
		// $map['id'] = 1;
		$info = M('ShippingFee')->where($map)->field(true)->select();
		$new_arr = array();
		foreach($info as $k => $v){
			if (empty($v)) $v['type'] = 1;
			$v['areas'] = unserialize($v['configure']);
			$v['region'] = explode(',', $v['area_region']);
			unset($v['configure'],$v['area_region']);
			$new_arr[] = $v;
		}
		$this->assign('type', $new_arr[0]['areas']['type']);
		$this->assign('money', $new_arr[0]['areas']['money']);
		$this->assign('len',count($new_arr));
		$this->assign('new_arr',$new_arr);
		$this->assign('shop_id', $shop_id);
	}
	
    /**
     * 获取运费设置
     * @param $shop_id  门店id，使用方法前先判断好权限
     */
    private function get_shipping_info($shop_id){
        $where=array();
		$where['shop_id']=$shop_id;
        $ShopsDelivery=M('ShopsDelivery')->where($where)->field('start_price,scale,delivery_price')->select();
        if (!empty($ShopsDelivery)) {
            foreach ($ShopsDelivery as $v) {
                // $moreimgarr['start_price'][] = $v['start_price'];
                $moreimgarr['scale'][] = $v['scale'];
                $moreimgarr['delivery_price'][] = $v['delivery_price'];
            }
            $shipping_price = $ShopsDelivery[0]['start_price'];
            $moreshipstr = implode('', $moreimgarr['start_price']) . implode('', $moreimgarr['scale']) . implode('', $moreimgarr['delivery_price']);
        }
        $this->assign('shipping_price', $shipping_price);
        $this->assign('shops_delivery', $ShopsDelivery);
        $this->assign('moreshipstr', md5($moreshipstr));
    }

    /**
     * 获取包装费
     * @param $shop_id 门店id，使用方法前先判断好权限
     */
    private function get_bagging_info($shop_id){
        // $where=array();$where['shop_id']=$shop_id;
        // $ShopsPackage=M('ShopsPackage')->where($where)->field('package_price,package_start_price,to_time')->find();
        // $this->assign($ShopsPackage);
         $where = $map = array();
		$where['shop_id']=$shop_id;
		$map['id']=$shop_id;
		$info = M('Shops')->where($map)->field('business_week_start,business_week_end,business_hours_start,business_hours_end')->find();
        $ShopsPackage = M('ShopsPackage')->where($where)->field(true)->find();
		if($ShopsPackage['to_time'] > 60){
			$ShopsPackage['time_type'] = 2;
			$ShopsPackage['to_time'] = sprintf("%.1f",$ShopsPackage['to_time']/60);
		}
		// $long_time_arr = array('0'=>'当天下单','1'=>'1','2'=>'2','3'=>'3','4'=>'4','5'=>'5','6'=>'6','7'=>'7','8'=>'8','9'=>'9','10'=>'10','11'=>'11','12'=>'12','13'=>'13','14'=>'14','15'=>'15','16'=>'16','17'=>'17','18'=>'18','19'=>'19','20'=>'20','21'=>'21','22'=>'22','23'=>'23','24'=>'24','25'=>'25','26'=>'26','27'=>'27','28'=>'28','29'=>'29','30'=>'30');
		$long_time_arr = array('0'=>'当天下单','1'=>'1','2'=>'2','3'=>'3','4'=>'4','5'=>'5','6'=>'6','7'=>'7','8'=>'8','9'=>'9','10'=>'10','20'=>'20','30'=>'30');
        $this->assign('long_time_arr',$long_time_arr);
        $this->assign($ShopsPackage);
        $this->assign($info);
    }
	/**
     * 更新门店信息
     */
    public function update_setting(){
		$shops_info=session('shops_info');
		$shop_id = $shops_info['shop_id'];
		
		$name = 'ShopsAccount';
        $model = D('Shop/ShopsAccount');
        $postdata = I('post.');	
        foreach($postdata['start_price'] as $k => $v){
			$postdata['start_price'][$k] = $postdata['shipping_price'];
		}
		unset($postdata['shipping_price']);
        $data = M($name)->create($postdata);

        $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/setting');
		$id = array_unique((array)I('id', 0));
        $id = is_array($id) ? implode(',', $id) : $id;
		
        if(empty($shop_id)){
			$this->error('参数错误！');
		}
        if($shops_info['pid'] != 0){
            // $this->error('您对此没有权限，请更换有权限的账户登录！');
        }
        
		$where = 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);
        if (M($name)->where($where)->save($data) !== false) {
            $postdata['shop_id'] = $shop_id;
            $model->update_shipping_info($postdata);//更新配送信息
            // $model->update_bagging_info($postdata);//更新包装费信息
            $model->change_update_bagging_info($postdata);//更新包装费信息
            unset($data, $postdata);
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
    }
    /**
    *更新快递费
    */
    public function sub_edit(){
        $post = I('post.');
        if ($post) {
            if(empty($post['regions'])){
                $this->error("配送区域不得为空");
            }else{
				$map = array();
				$map['shop_id'] = $post['shop_id'];
				 $shops_info=session('shops_info');
				$shop_id = $shops_info['shop_id'];
				if($post['shop_id']!=$shop_id){$this->error("参数错误！");}
				M('ShippingFee')->where($map)->delete();
			}
			foreach($post['regions'] as $k => $v){
				$info_ship['type'] = $post['type'];
				$info_ship['money'] = $post['money'];
				$info_ship['first_weight'] = $post['first_weight'][$k];
				$info_ship['first_weight_money'] = $post['first_weight_money'][$k];
				$info_ship['x_weight'] = $post['x_weight'][$k];
				$info_ship['x_weight_money'] = $post['x_weight_money'][$k];
				$regions = implode(',', $post['regions'][$k]);
				$data['configure'] = serialize($info_ship);
				$data['area_region'] = $regions;
				$data['shop_id'] = $post['shop_id'];
				$info = M('ShippingFee')->add($data);
			}
            if ($info) {
                $url = U(CONTROLLER_NAME . '/setting',array('tabid'=>'kd_edit'));
                $this->success(L('DO_OK'), $url);
            } else {
                $this->error(L('DO_ERROR'));
            }
        }
    }
    /**
    *导购员提成
    */
    public function guide(){
    	$auth_code = 'guide_set';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);exit;}

    	$shops_info=session('shops_info');
		$shop_id = $shops_info['shop_id'];
		$guide=M('Shops')->where('id='.$shop_id)->getField('guide');
        if(empty($guide))$guide=C('GUIDE');
		if($guide){
			$guide=unserialize($guide);
			$this->assign($guide);
		}
    	$this->display();
    }
    /**
    *编辑导购员提成
    */
    public function update_guide(){
    	$auth_code = 'guide_set';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);exit;}
    	$shops_info=session('shops_info');
		$shop_id = $shops_info['shop_id'];
		$postdata=I('post.');
		$guide=$save=array();
		if($postdata['market_way'])$guide['market_way']=$postdata['market_way'];
		if($postdata['market_status'])$guide['market_status']=$postdata['market_status'];
		if($postdata['market'])$guide['market']=$postdata['market'];
		if($postdata['recharge'])$guide['recharge']=$postdata['recharge'];
		if($postdata['prepaid_card'])$guide['prepaid_card']=$postdata['prepaid_card'];
		if($postdata['no_way'])$guide['no_way']=$postdata['no_way'];
		if($postdata['guoshu_rate'])$guide['guoshu_rate']=$postdata['guoshu_rate'];
		$guide['update_time']=NOW_TIME;		
		if($guide){$save['guide']=serialize($guide);$save['id']=$shop_id;}
		if($save)$res=M('Shops')->where('id='.$shop_id)->save($save);
		if($res) $this->success('操作成功！');
		else $this->error('操作失败！');
    }

   /**
    *生成银联永久二维码
    */
    public function get_chinaums_img(){
    	$is_check=I('is_check',0,'intval');
        $download=I('download',0,'intval');
        $shop_id=MID;//shop_id 商户id 支付订单以counterNo原路返回 
        $docheck=$is_check?0:1;
        $return=deccacode($shop_id,$docheck);
        if(empty($return['status'])){
            $this->error($return['msg']);return;
        }
        if($download==1){
            //获取要下载的文件名
            $filename = $return['url'];
            header('Content-Disposition:attachment;filename=' . basename($filename));
            header('Content-Length:' . filesize($filename));
            readfile($filename);//读取文件并写入到输出缓冲
            return;
        }
        $this->assign($return);
        $this->display();
    }
	 /**
	 * 切换门店  shopsAccount表 is_main !=0 shops表 pid门店id
	 */
    public function shop_list_arr(){
		$shop_info=session('shops_info');
		$shop_id=$shop_info['first_shop_id']?$shop_info['first_shop_id']:$shop_info['shop_id'];//有first_shop_id即首次登陆账号
		$p_map['status']=1;
		$p_map['pid']=$shop_id;
		$pid=M('Shops')->where($p_map)->getfield('id',true);
		if($pid){
			if($shop_info['first_shop_id'])$pid[]=$shop_info['first_shop_id'];
	        $map=array('status'=>1,'id'=>array(array('in',$pid),array('neq',$shop_info['shop_id']),'and'));
	        $shop_list = M('Shops')->where($map)->field('id,name')->select();
			$this->assign('shop_list',$shop_list);
	    }   
		$this->display();
    }
    public function shops_change(){
    	$se=session('shops_info');
    	$return=array();
		$postdata = I('param.');
		if(empty($postdata)){
			$return['status'] = 3;
			$return['msg']='参数不能为空';
			$this->ajaxReturn($return);
		}
		$map=array();
		$map['id'] = $postdata['shop_id'];
		$map['status']=1;
		$suc=M('Shops')->where($map)->getfield('pid');
		if($se['first_shop_id']==$postdata['shop_id']||(($suc==$se['first_shop_id']||$suc==$se['shop_id'])&& $suc) ){
			$return['status'] = 1;
			$return['msg']='切换成功';
			session('shops_info',null);
			if(!$se['first_shop_id'])$se['first_shop_id']=$se['shop_id'];//初次登录的帐号，首次切换存储
			$se['shop_id']=$postdata['shop_id'];
			// $se['salt']=idtoname($postdata['shop_id'],'Shops','salt');
			session('shops_info',$se);
		}else{
			$return['status'] = 3;
			$return['msg']='门店错误或门店已禁止登陆!';
		}
    	$this->ajaxReturn($return);



    }

}
?>