<?php
/**
 * 仓库管理
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
 
namespace Admin\Controller;
class ShopsAccountController extends BaseController{
	public function _initialize(){
        parent::_initialize();
    }
    
	/**
	* 员工列表
	*/
	public function index(){
		$name = CONTROLLER_NAME;
		$postdata = I('param.');
		$role_id = $postdata['rank_id'];
		$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);
		$keyword = $postdata['keyword'];
		$map = array();
		if ($keyword) {
		$map['name'] = array('like', '%' . $keyword . '%');
		}
		if(!empty($role_id)){
			$map_role = array();
			$map_role['role_id'] = $role_id;
			$shops_role_account = M('ShopsRoleAccount')->where($map_role)->getField('account_id',true);
			$map['id'] = array('in',$shops_role_account);
		}
		if($postdata['data_from']){
			$map['updatetime'][] = array('egt',strtotime($postdata['data_from']));
		}
		if($postdata['data_to']){
			$map['updatetime'][] = array('elt',strtotime($postdata['data_to']));
		}
		
		//$map['pid'] = array('neq',0);
		$list = $this->lists($name, $map);
        $this->assign('list', $list);
		$this->assign($postdata);
		$this->display();
	}
	/**
     * 员工添加
     */
	public function add(){
		$login_name = shop_account_sn();
		$this->assign('login_name', $login_name);
		// print_r($login_name);exit;
		
		if (IS_POST) {
            $model = M("ShopsAccount");
            $postdata = I('post.');			
    		$s_where['shop_id'] = intval($postdata['shop_id']);
    		$s_info = $model->where($s_where)->field('uid,id')->find();

            $this->check_staff_post($postdata, 0);
			
			$postdata['salt'] = randStr();
            $postdata['password'] = creatpwd($postdata['password'], 'HANCHAO'.$postdata['salt']);
			
			$postdata['shop_id'] = intval($postdata['shop_id']);
			$postdata['uid'] = intval($s_info['uid']);
			$postdata['is_main'] = 0;
			$postdata['last_ip'] = 0;
			$postdata['login_count'] = 0;
			$postdata['updatetime'] = $postdata['last_login'] = NOW_TIME;
			$postdata['is_delete'] = 0;
			$postdata['pid'] = intval($s_info['id']);
			
            $postdata = $this->format_post($postdata);
            $model->create($postdata);
            $result = $model->add();
			$url = U(CONTROLLER_NAME . '/index');
            if ($result) {
				
				$add_data = array();
				$add_data['role_id'] = $postdata['role_id'];
				$add_data['account_id'] = $result;
				M('ShopsRoleAccount')->add($add_data);
				
                $this->success(L('DO_OK'),$url);
            } else {
                $this->error(L('DO_ERROR'));
            }
            unset($postdata);
        } else {
            $p_where = array();
    		$p_where['pid'] = 0;
    		$p_where['status'] = 1;
    		$pid_list = M("ShopsAccount")->where($p_where)->field('shop_id,name')->select();
    		foreach($pid_list as $k => $v){
    			$pid_li.="<option value='".$v['shop_id']."'>".$v['name']."</option>";
    		}
    		$this->assign('pid_li', $pid_li);
    		
    		$r_where = array();
    		$r_where['status'] = 1;
    		$role_list = M("ShopsRole")->where($r_where)->cache(true)->field('id,title')->select();
    		foreach($role_list as $k => $v){
    			$role_li.="<option value='".$v['id']."'>".$v['title']."</option>";
    		}
    		$this->assign('role_li', $role_li);
			$this->display('edit');
        }
	}
	/**
     * 员工修改
     */
	public function edit(){
        $model = M("ShopsAccount");
		$id = I('id');
		if (IS_POST) {
            $postdata = I('post.');

		$id_where['id'] = $id;
		$shop_id = $model->where($id_where)->getfield('shop_id');
			//判断绑定的仓库是否修改
			if($shop_id != $postdata['shop_id']){
				$s_where['shop_id'] = intval($postdata['shop_id']);
				$s_info = $model->where($s_where)->field('uid,id')->find();
				$postdata['shop_id'] = intval($postdata['shop_id']);
				$postdata['uid'] = intval($s_info['uid']);
				$postdata['pid'] = intval($s_info['id']);
			}else{
				unset($postdata['shop_id']);
				unset($postdata['uid']);
				unset($postdata['pid']);
			}
			//判断密码是否修改
			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']);
			}
			//判断手机号是否存在
			if ($postdata['mobile']) {
				$where['mobile'] = $postdata['mobile'];
				$where['id'] = array('neq',$id);
				$is_mobile = M('ShopsAccount')->where($where)->count();
				if($is_mobile){
					$this->error('该手机号已存在');
				}
			}
			//判断登录账号是否存在
			if ($postdata['login_name']) {
				$where['login_name'] = $postdata['login_name'];
				$where['id'] = array('neq',$id);
				$is_login_name = M('ShopsAccount')->where($where)->count();
				$return['status']=0;
				if($is_login_name){
					$this->error('该登陆账号已存在');
				}
			}
            $this->check_staff_post($postdata, $id);
			
			$postdata['updatetime'] = NOW_TIME;
			
            $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) {
				
				$ra_where['account_id'] = $id;
				$count = M('ShopsRoleAccount')->where($ra_where)->count();
				$add_data = array();
				$add_data['role_id'] = $postdata['role_id'];
				if($count){
					M('ShopsRoleAccount')->where($ra_where)->save($add_data);
				}else{
					$add_data['account_id'] = $id;
					M('ShopsRoleAccount')->add($add_data);
				}
				
                $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);
			$where=array();
			// $where['pid'] = 0;
			$where['status'] = 1;
			// $pid_list = M('ShopsAccount')->where($where)->field('shop_id,name')->select();
			$pid_list = M('Shops')->where($where)->field('id as shop_id,name')->select();
			foreach($pid_list as $k => $v){
				if($info['shop_id'] == $v['shop_id']){
					$pid_li.="<option selected='selected' value='".$v['shop_id']."'>".$v['name']."</option>";
				}else{
					$pid_li.="<option value='".$v['shop_id']."'>".$v['name']."</option>";
				}
			}
			$this->assign('pid_li', $pid_li);
			
			$role_id = idtoname($id,'ShopsRoleAccount','role_id','account_id',false);

			$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);
			
            $this->assign($info);
            $this->assign('id', $id);
            $this->display();
        }
	}
	/**
     * 格式化提交的数据
     * @param array $postdata
     * @return array
     */
	public function format_post($postdata = array()){
        $postdata['updatetime'] = $postdata['last_login'] = NOW_TIME;
        return $postdata;
    }
	/**
     * 检查提交的数据是否合法
     * @param array $postdata
     */
    public function check_staff_post($postdata = array()){
        if (empty($postdata)) $this->error("非法数据");
        if ($postdata['name'] == '') $this->error("员工名称不得为空");
        if ($postdata['login_name'] == '') $this->error("登陆账号不得为空");
        if ($postdata['mobile'] == '') $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 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 checklogin_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){
			$login_name = shop_account_sn();
			$return['data'] = "该登陆账号已存在";
			$return['login_name'] = $login_name;
			$this->ajaxReturn($return);
        }
    }
    /**
     * 导购员提成设置
     */
    public function guide(){
    	$post = I('post.');
    	if($post){
	    $temp['market_status'] = $post['market_status'];
	    $temp['market'] = $post['market'];
	    $temp['recharge'] = $post['recharge'];
	    $temp['set_meal'] = $post['set_meal'];
	    $temp['prepaid_card'] = $post['prepaid_card'];
	    $temp['market_way'] = $post['market_way'];
	    $temp['no_way'] = $post['no_way'];//无导购员提成设置
	    $temp['guoshu_rate'] = $post['guoshu_rate'];//会员归属导购员获取提成
	    $temp = serialize($temp);
	    $where['name'] = 'GUIDE';
	    $res = M('Config')->field('value')->where($where)->find();
	    $data['value'] = $temp;
	    if (empty($res)) {
	        $data['name'] = 'GUIDE';
	        $data['group'] = 0;
	        $data['title'] = '导购员提成设定';
	        $data['create_time'] = NOW_TIME;
	        $save = M('Config')->data($data)->add();
	    } else {
	        $save = M('Config')->data($data)->where($where)->save();
	    }
	    if (!empty($save) || $save == 0) {
	        $this->success('修改奖励成功',U('ShopsAccount/guide'));return;
	    } else {
	        $this->error('修改奖励失败',U('ShopsAccount/guide'));return;
	    }
    	}else{
	    $res = M('Config')->field('value')->where("name='GUIDE'")->find();
	    $val = unserialize($res['value']);
	    $this->assign($val);
    	}
    	$this->display();
    }

    /**
     * 导购明细
     */
    public function guide_detail($is_return=false){
        $postdata = I('param.');
        $map=array();
        $map['guide']=array('gt',0);
        $now_time=strtotime(date('Y-m-d',NOW_TIME));
        if($postdata['data_from'] || $postdata['data_to']){
            $date_from = strtotime($postdata['data_from']);
            if($date_from)$map['addtime'][] = array('egt',$date_from);
            $date_to = strtotime($postdata['data_to']);
            if($date_to){$date_to = $date_to+86399;$map['addtime'][] = array('lt',$date_to);}
            $postdata['dates']=0;
        }else{
	  if(in_array($postdata['dates'],array(1,2,7,30))){
	      $between=quick_time($postdata['dates']);
	      $map['addtime']=array('between',array($between[0],$between[1]));
	  }else{
	      $postdata['dates']=99;
	  }
        }
        if($postdata['in_online']==1){$map['in_online']=0; $map['source']=array('in','0,1');}
        elseif($postdata['in_online']==2){$map['_string']='in_online = 1 or source = 2 or source = 4';}
        else{$map['in_online']=0; $map['source']=array('in','0,1');}//xyy 19118
        if($postdata['status']==1){$map['status']=array('not in','3,7,4');}
        elseif($postdata['status']==2){$map['status']=3;}else{
	  $map['status']=array('not in','7,4');
        }
        if($postdata['type']==1){
	  $map['type']=array('not in','2,15');
        }elseif($postdata['type']==2){
	  $map['type']=2;
        }elseif($postdata['type']==15){
	  $map['type']=15;
        }
        $map['is_delete']=0;
        $map['pay_status']=3;
        if(!empty($postdata['sale_id'])) $map['guide']=$postdata['sale_id'];
        if(!empty($postdata['shop_id'])) $map['shop_id']=$postdata['shop_id'];
        $field='id,order_sn,in_online,goods_allmoney,shop_id,source,guide,sales_maid,addtime,status,sign_building,type';
        $list=$this->lists('OrderInfo',$map,'id desc','',$field);
        $list_e=M('OrderInfo')->where($map)->order('id desc')->field($field)->select();
        $data=array();
        $data['goods_allmoney']=M('OrderInfo')->where($map)->sum('goods_allmoney');
        $data['all_sale_maid']=M('OrderInfo')->where($map)->sum('sales_maid');
        $data['all_count']=M('OrderInfo')->where($map)->count();
        if(empty($data['all_sale_maid'])) $data['all_sale_maid']=0.00;
        if(empty($data['goods_allmoney'])) $data['goods_allmoney']=0.00;
        $map=array();
        $map['s.status']=1;
        $map['s.is_delete']=0;
        $map['a.role_id']=2;
        $sales_list=M('ShopsRoleAccount')->alias('a')->where($map)->join('LEFT JOIN __SHOPS_ACCOUNT__ s ON a.account_id=s.id')->field('s.id,s.name')->cache(true)->select();
        $sales_list=format_array2select($sales_list);
        $map=array();
        $map['status']=1;
        $shops_list=M('Shops')->where($map)->field('id,name')->order('name')->cache(true)->select();
        $shops_list=format_array2select($shops_list);
        if($is_return==false) {
            // $pay_type=array('1'=>'线上','2'=>'线下');
            $pay_type=array('1'=>'线上'); //xyy 19118
            $affif_status=array('1'=>'未分成','2'=>'已分成');
            $daogou_status=array('1'=>'商品购买','2'=>'充值','15'=>'礼品卡');
            $this->assign('pay_type',$pay_type);
            $this->assign('affif_status',$affif_status);
            $this->assign('daogou_status',$daogou_status);
            $this->assign('sales_list', $sales_list);
            $this->assign('shops_list',$shops_list);
            $this->assign('list', $list);
            $this->assign('data', $data);
            $this->assign($postdata);
            $this->display();
        }else{
            $return=array('data'=>$data,'list'=>$list_e);
            return $return;
        }
    }

    /**
     * 导购明细导出
     */
    public function export_pur(){
        $guide_list=$this->guide_detail(true);
        $title = array('序号', '订单号', '订单总金额','导购员名称','消费仓库','提成金额','收银员','下单方式','导购类型','状态','变更时间');
        $data = array();
        foreach ($guide_list['list'] as $k => $v) {
            $data[$k][] = $v['id'];
            $data[$k][] = format_xml_num($v['order_sn']);
            $data[$k][] = $v['goods_allmoney'];
            $data[$k][] = idtoname($v['guide'],'ShopsAccount','name','id',false);
            $data[$k][] = idtoname($v['shop_id'],'Shops','name','id',false);
            $data[$k][] = $v['sales_maid'];
            $data[$k][] = $v['sign_building'];
            if($v['in_online']==0 && ($v['source']==0 || $v['source']==1))$data[$k][] = '线上';
            elseif($v['in_online']==1 || $v['source']==2 || $v['source']==4)$data[$k][] = '线下';
            if($v['type']==2) $data[$k][] = '充值';
			elseif($v['type']==15) $data[$k][] = '礼品卡';
            else $data[$k][] = '商品购买';
            if($v['status']==3) $data[$k][] = '已分成';
            else $data[$k][] = '未分成';
            $data[$k][] = time_format($v['addtime']);
        }
        $data[]=array(
            '总计：',
            '--',
            $guide_list['data']['goods_allmoney'],
            '--',
            '--',
            $guide_list['data']['all_sale_maid'],
            '--',
            '--',
            '--',
            '共计'.$guide_list['data']['all_count'].'条',
        );
        export_csv('导购员明细.csv',$title,$data);
        unset($title, $data);
        exit;
    }

}
?>