<?php
/**
 * 供货商营销
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author zhaoh <zhao@qq.com>
 */

namespace Supplier\Controller;
use Think\Controller;
class PromotController extends BaseController {
	//限时促销
    public function index(){
		$postdata=I('param.');
		$tabid=$postdata['tabid'];
        /**权限开始**/
        $power=array();
        $pmap['id']=25;
        $powerinfo=M('ProjectLabel')->where($pmap)->find();
        $this->assign('powerinfo',$powerinfo);
        $where['shop_id']=MID;
        $where['label_id']=25;
        $where['publish_wait']=array('in','1,3,5');
        $power['count']=M('ProjectLabelLink')->where($where)->count();
        unset($where['publish_wait']);
        $power['publish_wait']=M('ProjectLabelLink')->where($where)->find();
        $this->assign('power',$power);
        /**权限结束**/
        if(empty($tabid)){
			$list=D('Shop/Promot')->sale_list();
			$this->assign($list);
		}elseif($tabid=='add_sale'){
			$act_list=$this->get_promot_sale();
			$this->assign("act_list",$act_list);
			if($postdata['id']){
				$act_info = M('PromotAct')->field(true)->find($postdata['id']);
				$this->assign($act_info);
				$map['promote_id']=$postdata['id'];
				$list=M('Goods')->where($map)->field('id,goods_name,shop_price,promote_price')->select();
				$this->assign("list",$list);
				$this->assign($postdata);
			}
		}
        $this->assign('menu_tab','');
		$tabid=$tabid?$tabid:'index';
        $this->display($tabid);
    }
	//获取平台可用的限时促销
	public function get_promot_sale(){
		$map['status']=1;
		$map['is_limit_time']=1;
		$map['end_time']=array('gt',NOW_TIME);
		$info=M('PromotAct')->where($map)->field('id,act_name')->select();
		return $info;
	}
	//获取限时促销信息
	public function get_promot_info(){
		$act_id=I('param.act_id');
		$map['id']=$act_id;
		$info=M('PromotAct')->where($map)->field('start_time,end_time')->find();
		$data['start_time']=time_format($info['start_time']);
		$data['end_time']=time_format($info['end_time']);
		$this->ajaxReturn($data);
	}
	
	//搜索商品
	public function ajaxgetgoods(){
        $result=array();
		if(!MID){$this->ajaxReturn($result);}
		$keyword=I('keyword');
		$is_pt=I('is_pt');
		if(is_numeric($keyword)){
            $map['id|goods_name']=array(intval($keyword),array('like', '%' . $keyword . '%'), '_multi' => true);
        }else if(!empty($keyword)) {
            $map['goods_sn|goods_name'] = array('like', '%' . (string)$keyword . '%');
        }
        $map['is_delete']=0;
        $map['publish_wait']=1;
		$map['shop_id']=MID;
		if($is_pt==1){
			$map['pt_id']=0;
		}
		$list_goods=M("Goods")->field('goods_name,id,shop_price')->where($map)->select();
		$data_goods="<option value=''>请选择商品</option>";
		foreach($list_goods as $val){
			$data_goods.='<option data="'.$val['shop_price'].'" value="'.$val['id'].'">'.$val['goods_name'].'</option>';
		}
		$result['list']=$data_goods;
		$this->ajaxReturn($result);
	}
	//添加,修改限时促销
	public function insert_sale(){
		$post=I('param.');
		$result=D('Shop/Promot')->add_update($post);
		$this->ajaxReturn($result);exit;
	}
	//删除限时促销
    public function del_sale(){
		$return=array('status'=>0,'info'=>'');
		$postdata=I('param.');
		$id=I('check_id');
		if(!empty($id) && is_array($id)){
			foreach($id as $k=>$v){
				$result=check_delete($v,8);
				if(!$result['status'])unset($id[$k]);
			}
			$postdata['check_id']=$id;
			if(empty($id)){$return['info']='请先清除活动下商品';$this->ajaxReturn($return);exit;}
		}elseif(!empty($id)){
			$result=check_delete($id,8);
			if(!$result['status']){$return['info']='请先清除活动下商品';$this->ajaxReturn($return);exit;}
		}
		$return=D('Promot')->del_promot($postdata);
		if($return['status']){$return['url']=U('Promot/index');}
        $this->ajaxReturn($return);
    }
	
	
	//优惠活动
	public function promot(){
		$postdata=I('param.');
		$tabid=$postdata['tabid'];
        /**权限开始**/
        $power=array();
        $pmap['id']=26;
        $powerinfo=M('ProjectLabel')->where($pmap)->find();
        $this->assign('powerinfo',$powerinfo);
        $where['shop_id']=MID;
        $where['label_id']=26;
        $where['publish_wait']=array('in','1,3,5');
        $power['count']=M('ProjectLabelLink')->where($where)->count();
        unset($where['publish_wait']);
        $power['publish_wait']=M('ProjectLabelLink')->where($where)->find();
        $this->assign('power',$power);
        /**权限结束**/
        if(empty($tabid)){
			$list=D('Promot')->promot_list();
			$this->assign($list);
		}elseif($tabid=='edit_promot'){
			$id=$postdata['id'];
			if(!$id){
				$this->redirect('Promot/promot');
			}else{
				$promot_info=D('Promot')->promot_info($id);
				$this->getcateTree($promot_info['style_ext_id']);
				$this->assign($promot_info);
				$this -> assign('range_list',$promot_info['rang_list']);
			}
		}elseif($tabid=='add_promot'){
			$this->getcateTree();
		}
        $this->assign('menu_tab','');
		$tabid=$tabid?$tabid:'promot';
        $this->display($tabid);
	}
	//添加活动
	public function insert_promot(){
		$post=I('param.');
		$return=D('Promot')->add_promot($post);
		if($return['status']){$return['url']=U('Promot/promot');}
		$this->ajaxReturn($return);
	}
	//编辑活动
	public function update_promot(){
		$post=I('param.');
		$return=D('Promot')->edit_promot($post);
		if($return['status']){$return['url']=U('Promot/promot');}
		$this->ajaxReturn($return);
	}
	//删除优惠活动
    public function del_promot(){
		$postdata=I('param.');
		$return=D('Promot')->del_promot($postdata);
		if($return['status']){$return['url']=U('Promot/promot');}
        $this->ajaxReturn($return);
    }
	
	//代金券
	public function bonus(){
		$postdata=I('param.');
		$tabid=$postdata['tabid'];
        /**权限开始**/
        $power=array();
        $pmap['id']=27;
        $powerinfo=M('ProjectLabel')->where($pmap)->find();
        $this->assign('powerinfo',$powerinfo);
        $where['shop_id']=MID;
        $where['label_id']=27;
        $where['publish_wait']=array('in','1,3,5');
        $power['count']=M('ProjectLabelLink')->where($where)->count();
        unset($where['publish_wait']);
        $power['publish_wait']=M('ProjectLabelLink')->where($where)->find();
        $this->assign('power',$power);
        /**权限结束**/
        if(empty($tabid)){
			$list=D('Promot')->bonus_list();
			$this->assign($list);
		}elseif($tabid=='edit_bonus'){
			$id=$postdata['id'];
			if(!$id){
				$this->redirect('Promot/bonus');
			}else{
				$info=M('Bonu')->where('id='.$id)->field(true)->find();
				$this->get_promot_list();
				$this->assign($info);
			}
		}elseif($tabid=='add_bonus'){
			$this->get_promot_list();
		}
        $this->assign('menu_tab','');
		$tabid=$tabid?$tabid:'bonus';
        $this->display($tabid);
	}
	//添加代金券
	public function insert_bonus(){
		$post=I('param.');
		$return=D('Promot')->add_bonus($post);
		if($return['status']){$return['url']=U('Promot/bonus');}
		$this->ajaxReturn($return);
	}
	//修改代金券
	public function update_bonus(){
		$post=I('param.');
		$return=D('Promot')->edit_bonus($post);
		if($return['status']){$return['url']=U('Promot/bonus');}
		$this->ajaxReturn($return);
	}
	//删除代金券
    public function del_bonus(){
		$postdata=I('param.');
		$return=D('Promot')->del_bonus($postdata);
		if($return['status']){$return['url']=U('Promot/bonus');}
        $this->ajaxReturn($return);
    }
	
	
	//推荐展位
	public function extend(){
		$tabid=$postdata['tabid'];
		if(empty($tabid)){
			$all_order=D('Common/Shops')->shop_all_order($postdata);
			$this->assign($all_order);
		}
		$tabid=$tabid?$tabid:'extend';
        $this->display($tabid);
	}
	
	private function getcateTree($pid = '',$assign='') {
        //需要只显示该供货商申请成功的分类
        $cate_ids=idtoname(MID,'Shops','cate_ids');
        $cate_ids=explode(',',$cate_ids);
        $GoodsCategory = getcache('GoodsCategory');
        foreach($GoodsCategory as $ke=>$va){
            $show=0;
            $allprarent=explode(',',$va['allparent']);
            foreach($allprarent as $kk=>$vv){
                if(in_array($vv,$cate_ids)) $show=1;
            }
            if(!in_array($ke,$cate_ids) && empty($show)) unset($GoodsCategory[$ke]);
        }
		$Tree = new \Common\Vendor\Tree();
		$select_categorys='';
		$treemini=$Tree->treemini($GoodsCategory);
		$select_categorys.= $Tree->treeminioption($treemini,$pid);
		if($assign)return $select_categorys;
		else $this->assign('select_categorys',$select_categorys);
		$wh['status']=1;
		$brand=M('Brand')->where($wh)->field('id,brand_name')->select();
		$this->assign('brand_list',$brand);
		
	}
	private function get_promot_list() {
		$map['act_type']=array('in',array(1,2));
		$map['shop_id']=MID;
		$promot=M('PromotAct')->where($map)->field('id,act_name')->select();
		$this->assign('promot_list',$promot);
	}
    //线下发放处理
    public function send_oline(){
        $postdata = I('post.');
        $use_start_date = strtotime($postdata['use_start_date']);
        $use_end_date = strtotime($postdata['use_end_date']);
        $arr['type_name'] = $postdata['type_name'];
        $arr['type_money'] = $postdata['type_money'];
        $arr['min_goods_amount'] = $postdata['min_goods_amount'];
        $arr['use_start_date'] = $use_start_date;
        $arr['use_end_date'] = $use_end_date;
        $arr['shop_id']=MID;
        $bonus_sum = !empty($_POST['bonus_sum'])?$_POST['bonus_sum']:1;
        if(!$bonus_sum)$this->error('请添加数量！');
        if($bonus_sum>10)$this->error('请填写小于10的数量！');
        //随机生成红包序列号
        $info = M('member_bonus');
        $infos = $info->field(max('bonus_sn'))->find();
        $num = $infos[0];
        $num = $num ? floor($num / 10000) : 100000;
        for ($i = 0, $j = 0; $i < $bonus_sum; $i++){
            $arr['bonus_name'] = $postdata['type_name'];
            $bonus_sn = ($num + $i) . str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);
            $arr['bonus_type_id'] = 4;
            $arr['bonus_sn']=$bonus_sn;
            $arr['send_time']=NOW_TIME;
            $arr['money'] = $postdata['type_money'];
            $arr['min_goods_money'] = $postdata['min_goods_amount'];
            $arr['start_time'] = $use_start_date;
            $arr['end_time'] = $use_end_date;
            $sql = $info->add($arr);
        }
        if($sql!==false){
            $url = U('Promot/down_bonus');
            $this->success('发放成功！',$url);
        } else {
            $this->error('发放失败！');
        }
    }
    //线下红包
    public function down_bonus(){
        $where['bonus_type_id']=4;
        $where['shop_id']=MID;
        $info=page_list('MemberBonus',$where,$order,$field,$page_num,'',1);
        foreach($info['list'] as $k=>$v){
            if($v['order_id']){
                $order=M('OrderInfo')->where('id='.$v['order_id'])->field('order_sn')->find();
                $info['list'][$k]['order_sn']=$order['order_sn'];
            }else{
                $info['list'][$k]['order_sn']=0;
            }
        }
        $this->assign($info);
        $this->display();
    }
    //生成线下红包的页面
    public function down_index_add(){
        $bonu=M('Bonu')->where('id=4')->find();
        $this->getcateTree($bonu['cat_id']);
        $this->assign('edit',$bonu);
        $this->assign('menu_action','down_bonus');
        $this->assign('menu_tab','');
        $this->display();
    }
    //删除已发放的红包
    public function delete_user(){
        $para  = I('param.');
		if(empty($para['id'])){$this->error('请选择要删除的项！');}
        $where['id']=array('in',$para['id']);
        $deletes=M('MemberBonus')->where($where)->delete();
        if($deletes){
            $this->success('删除成功！');
        } else {
            $this->error('删除失败！');
        }
    }
    /**
     * 加入权限申请
     * @Author xiaol
     */
    public function apply_contract(){
        $return=$l_map=$m_map=$map=$data=array();$return['status']=0;
        $id=I('param.id');//label_id
        if(is_null($id)){
            $return['msg']='参数错误';
            $this->ajaxReturn($return);
        }
        $l_map['id']=$id;
        $deposit=M('ProjectLabel')->where($l_map)->getField('price');
        $data['publish_wait']=0;
        $data['apply_time']=NOW_TIME;
        $data['deposit']=$deposit;
        $data['label_id']=$id;
        $data['shop_id']=MID;
        $count=M('ProjectLabelLink')->data($data)->add();
        if($count>0){
            $return['status']=1;
        } else{
            $return['msg']='申请加入('.idtoname($id,'ProjectLabel','label_name').')权限失败，请稍候重试！';
        }
        $this->ajaxReturn($return);
    }

    /*拼团*/
    public function fight_group(){
    	$postdata=I('param.');
		$tabid=$postdata['tabid'];
    	if($tabid == 'add_fight_group'){
    		$this->display('Promot/add_fight_group');
    	}else if($tabid == 'edit_fight_group'){
    		$id=$postdata['id'];
			if(!$id){
				$this->redirect('Promot/fight_group');
			}else{
				$promot_info=D('Promot')->promot_info($id);
				$this->getcateTree($promot_info['style_ext_id']);
				$group_price = unserialize($promot_info['remarks']);
				$this->assign($promot_info);
				$this->assign('group_price',$group_price);
				$this->assign('range_list',$promot_info['rang_list']);
			}
    		$this->display('Promot/edit_fight_group');
    	}else if($tabid == 'select_all'){
    		$id=$postdata['id'];
			if(!$id){
				$this->redirect('Promot/fight_group');
			}else{
				//团长列表
				$map['pid'] = 0;
				$map['pt_id'] = $id;
				$map['pay_status'] = 3;
				$sum_num = idtoname($id,'PromotAct','group_number');
				$list = $this->lists('OrderInfo', $map, 'id desc');
				if(!empty($list)){
					foreach ($list as $key => $value) {
						$where['pid'] = $value['id'];
						$where['status'] = 2;
						$where['pay_status'] = 3;
						$where['confirm_time'] = array('neq',0);
						$count = M('OrderInfo')->where($where)->count();
						$list[$key]['number'] = $count;
					}
				}
				$this->assign('list',$list);
				$this->display('Promot/select_all');
			}
    	}else if($tabid == 'select_all_son'){
    		$id=$postdata['id'];
			if(!$id){
				$this->redirect('Promot/select_all_son');
			}else{
				$where['pid'] = $id;
				$where['status'] = 2;
				$where['pay_status'] = 3;
				$where['confirm_time'] = array('neq',0);
				$list = $this->lists('OrderInfo', $where, 'id desc');
				$this->assign('list',$list);
				$this->display('Promot/select_all_son');
			}
    	}else{
    		$map['is_pt'] = 1;
	        $map['is_limit_time'] = 0;
	        $map['is_group'] = 0;
	        $map['shop_id'] = MID;
	        $list = $this->lists('PromotAct', $map, 'id desc');
	        if(!empty($list)){
		        foreach ($list as $key => $value) {
		        	$list[$key]['goods_id'] = M('PromotExt')->where('act_id='.$value['id'])->getField('style_ext_id');
		        	$price = M('PromotExt')->where('act_id='.$value['id'])->getField('remarks');
		        	$list[$key]['group_price'] = unserialize($price);
		        }
	        }
	        $this->assign('list', $list);
    		$this->display();	
    	}
    	
    }
    /*添加*/
    public function add_fight_group(){
  		$post=I('param.');
  		if(empty($post)){
  			$this->error('请录入正确的活动信息');
  		}
		$return=D('Promot')->add_promot($post);
		if($return['status']){$return['url']=U('Promot/fight_group');}
		$this->ajaxReturn($return);
    }

    /*编辑*/
    public function edit_fight_group(){
    	$post=I('param.');
		$return=D('Promot')->edit_promot($post);
		if($return['status']){$return['url']=U('Promot/fight_group');}
		$this->ajaxReturn($return);
    }

    public function del_fight_group(){
    	$postdata=I('param.');
		$return=D('Promot')->del_promot($postdata);
		if($return['status']){$return['url']=U('Promot/fight_group');}
        $this->ajaxReturn($return);
    }

    public function del_team(){
    	$postdata=I('param.');
    	$shop_info=session('shop_info');
		$shop_id=$shop_info['id'];
		if(!$shop_id){$return['info']='登录信息错误';return $return;}
		
		$ids=$postdata['check_id'];
		if(!$ids){$return['info']='请选择要删除的选项';return $return;}

    	$map['id']=array('in',$ids);
		$res=M('OrderInfo')->where($map)->delete();
		if($res){
			if(is_array($ids)){
				foreach($ids as $k=>$v){action_log('shop_del_promot', 'Shop', $v, $shop_id);}
			}else{
				action_log('shop_del_promot', 'Shop', $ids, $shop_id);
			}
		}
    }

}
?>