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

namespace Supplier\Controller;
use Think\Controller;
class SuppliersController extends BaseController {
    public function _initialize()
    {
        parent::_initialize();
        $supplier_info=session('suppliers_info');
        if(empty($supplier_info['id']))$this->error('身份过期，请重新登录',U('Supplier/Register/sup_login'));
    }
    /**
     * 供货商设置
     * @Author xiaol
     */
    public function index(){
        $tabid=I('param.tabid');
        $map=array();
        if(!empty($tabid)){
            if($tabid=='shop_slide'){//幻灯片设置
                $map['id']=MID;
                $info=M('Suppliers')->field('id,slide')->where($map)->find();
                $is_update=(empty($info))?0:1;
                if(!empty($info['slide'])) {
                    $slide = $info['slide'];
                    $slide_en=md5($slide);
                    $this->assign('slide_en', $slide_en);
                    $slide = unserialize($slide);
                    $this->assign('slide', $slide);
                }
                $this->assign('is_update', $is_update);
            }elseif($tabid=='shop_setting'){//供货商设置
                $map['id']=MID;
                $info=M('Suppliers')->field(true)->where($map)->find();
                $this->assign($info);
                $this->assign('info',$info);
            }
            $this->display($tabid);
        } else{//供货商信息
            $map['id']=idtoname(MID,'Suppliers','uid');
            $info=M('Suppliers')->field(true)->where($map)->find();
            $info['cate_id']=explode(',',$info['cate_ids']);
            $this->assign($info);
            $gc_map=array();
            $gc_map['pid']=0;
            $gc_map['status']=1;
            $this->display();
        }
    }

    /**
     * 修改供货商信息
     * @Author xiaol
     */
    public function update_submit(){
		$map['id']=idtoname(MID,'Suppliers','id');
        $info=M('Suppliers')->field(true)->where($map)->find();
        $postdata=I('post.');
		if(empty($postdata['cate_ids']))$this->error('请填写经营品类！');
        if($info['publish_wait']==0)$this->error('请耐心等待审核！');
        $map['id']=$postdata['id'];
        $map['shops_id']=MID;
        $postdata['postion']=$postdata['province'].','.$postdata['city_id'].','.$postdata['district'].','.$postdata['town'].','.$postdata['community'];
        $postdata['point']=$postdata['x'].','.$postdata['y'];
		$postdata['publish_wait']=0;
		$postdata['updatetime']=NOW_TIME;
		$postdata['licence_start']=strtotime($postdata['licence_start']);
		$postdata['licence_end']=strtotime($postdata['licence_end']);
        $count=M('Suppliers')->where($map)->save($postdata);
        if($count){
			$this->success('修改成功，等待审核！');exit;
		}else{ 
			$this->error('修改失败，请稍候再试！');exit;
		}
    }
    /**
     * 设置供货商
     * @Author xiaol
     */
    public function update_setting(){
        $postdata=I('post.');
		$postdata['custom_page']=$postdata['custom_page'];
        if(empty($postdata['is_update'])){
            $postdata['id']=MID;
            $count=M('Suppliers')->data($postdata)->add();
        }else{
            $map['id']=MID;
            $count=M('Suppliers')->where($map)->save($postdata);
        }
        if($count>0)$this->success('编辑成功');
        else $this->error('编辑失败');
    }
    /**
     * 幻灯片设置
     * @Author xiaol
     */
    public function add_slide(){
        $postdata=I('post.');
        $img=$postdata['img'];
        $desc=$postdata['desc'];
        $sort=$postdata['sort'];
		$type=$postdata['type'];
        asort($sort);//按值的从小到大排序
		asort($type);
        $slide=$data=$map=array();$i=0;
        foreach($sort as $k=>$v){
            $slide[$i]['img']=$img[$k];
            $slide[$i]['desc']=$desc[$k];
            $slide[$i]['sort']=$sort[$k];
			$slide[$i]['type']=$type[$k];
            $i++;
        }
        $slide_en=$postdata['slide_en'];
        $slide=serialize($slide);
        $slide_un=md5($slide);
        if($slide_en==$slide_un)$this->error('您没有做任何操作！');
        $data['slide']=$slide;
        if(empty($postdata['is_update'])){
            $data['id']=MID;
            $count=M('Suppliers')->data($data)->add();
        }else{
            $map['id']=MID;
            $count=M('Suppliers')->where($map)->save($data);
        }
        if($count>0)$this->success('编辑成功！');
        else $this->error('编辑失败！');
    }
    /**
      *获取当前供货商的导航列表
      */
    public function nav_list(){
        $tabid=I('param.tabid');
        $tablename='Nav';
        $map['shop_id']=MID;
        $map['device']=0;
        $map['navtype']=4;
        $data=D('Suppliers')->cat_nav_list($tablename,$map);
        $this->assign('nodeString', $data);
        if(!empty($tabid)) $this->display($tabid);
        else $this->display();
    }
    /**
      *当前供货商导航的编辑、添加、子菜单的添加
      */
    public function nav_add(){
        $id=I('id');
        if($id){
            $where['id']=$id;
            $info=M('Nav')->where($where)->field(true)->find();
            $this->assign($info);
            $this->getNodeTree($info['pid']);
        }else{
            $this->getNodeTree();
        }
        $this->display();
    }
    /**
      *供货商分类列表
      */
    public function cat_list(){
		$tabid=I('param.tabid');
        if(empty($tabid)) $tabid='goods';
		$shop_id=$this->shop_info['id'];
		if($tabid=='brand'){
			$map=array();
			$map['status']=1;
			$brand_cates=$this->lists('Brand',$map,'','',$field=true,$pagesize='10');
			$this->assign('brand_cat',$brand_cates);
		}elseif($tabid=='goods'){
			$map=array();
			$map['pid']=0;
			$goods_cates=$this->lists('PurchaseCategory',$map,'','',$field=true,$pagesize='10');
			$this->assign('goods_cat',$goods_cates);
		}else{
			$tablename='PurchaseCategory';
			$map['id']=MID;
			$data=D('Suppliers')->cat_nav_list($tablename,$map); 
			$this->assign('cateString', $data);
		}
        if(!empty($tabid)) $this->display($tabid);
        else $this->display();
    }
	public function brand_edit(){
		$map=array();
		$map['status']=1;
		$barandcategory=M('BrandCategory')->where($map)->field(true)->select();
		$option='';
		foreach($barandcategory as $k=>$v){
			$option.='<option value="'.$v['id'].'">'.$v['name'].'</option>';
		}
		$this->assign('option',$option);
		$this->display();
	}

    /**
      *供货商分类编辑、添加、子菜单的添加
      */
    public function cat_add(){
        $id=I('id');
        if(!empty($id)){
            $where['id']=$id;
            $where['shop_id']=$this->shop_info['id'];
            $info=M('ShopsCategory')->where($where)->field(true)->find();
            $this->assign($info);
            $this->getNodeTree($info['pid']);
        }else{
            $this->getNodeTree();
        }
        $this->display();
    }
    /**
      *执行导航、分类的添加、修改操作
      */
    public function cat_nav_add(){
        $postdata=I('param.');
        $data=D('Shops')->cat_nav_add($postdata);
        $this->ajaxReturn($data);
    }
    public function status(){
        $id     = intval(I('id'));
        $type   = I('type');
        $values = M('ShopsCategory')->where('id='.$id)->field($type)->find();
        $data[$type]=($values[$type]+1)%2;
        $res=M('ShopsCategory')->where('id='.$id)->save($data);
        if(in_array('ShopsCategory',$this->cache_model)){savecache('ShopsCategory');}
        $this->ajaxReturn($data[$type]);
    }
    /**
      *删除当前供货商分类
      */
    public function remove(){
        $id=I('id');
        $is_cat=I('is_cat');
        if(empty($id)) $this->error('参数错误！');
        $map['id']=$id;
        if($is_cat==1) {$res=M('ShopsCategory')->where('id='.$id)->delete(); savecache('ShopsCategory');}
        else { $res=M('Nav')->where('id='.$id)->delete(); savecache('Nav'); }
        if($res !== false) $this->success('删除成功！');
        else $this->error('删除失败！');
    }
    public function dynamic_list(){
        $this->assign('shop_id',$this->shop_info['id']);
        $tabid=I('param.tabid');
        $id=I('id');
        if(!empty($tabid)){
            if($id){
                $where['id']=$id;
                $where['shop_id']=$this->shop_info['id'];
                $info=M('ShopsArticle')->where($where)->field(true)->find();
                $this->assign($info);
            }
            $this->display($tabid);
        }else{
            $map['shop_id']=MID;
            $order='updatetime desc,id desc,sort desc';
            $field='id,title,content,shop_id,addtime,updatetime';
            $list=page_list('ShopsArticle',$map,$order,$field);
            $this->assign($list);
            $this->display();
        }
    }
    public function dynamic_add(){
        $postdata=I('post.');
        $data=D('Shops')->dynamic_add($postdata);
        if($data['status']==1) $this->success($data['msg'],$data['url']);
        else $this->error($data['msg']);
    }
    public function delete(){
        $id=I('id');
        if(empty($id)) $this->error('参数错误！');
        $res=M('ShopsArticle')->where('id='.$id)->delete();
        if($res !== false) $this->success('删除成功！');
        else $this->error('删除失败！');
    }
	
    /**
     * 供货商
     * @Author xiaol
     */
	public function suppliers(){
		$smap['status']=1;
		$smap['shop_id']=MID;
        $suppliers_info = page_list('Suppliers',$smap,$order,$field);
        $this->assign($suppliers_info);
        $this->display();
	}
    
    /**
     * 删除供货商
     * @Author xiaol
     */
    public function supplier_delete()
    {
        $postdata = I('post.');
        $id = I('get.id');
        if (empty($postdata['id']) && !empty($id)) $postdata['id'][] = $id;
        if (empty($postdata['id'])) {
            $this->error('参数错误');
        }
        foreach ($postdata['id'] as $key => $value) {
            $map['id'] = $value;
            $deletes = M('Suppliers')->where($map)->delete();
        }
        if ($deletes == 1) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }

	public function supplier_add(){
        $this->assign('menu_action','suppliers');
		$this->display('supplier_edit');
	}
    /**
     * 添加供货商
     * @Author xiaol
     */
    public function supplier_insert()
    {
        $model = D('Suppliers');
        if (false === $model->create()) {
            $this->error($model->getError());
        }
        $suppliers_id = $model->add();
        $postdata = I('post.');
        $arr['shop_id'] = MID;
        $arr['name'] = isset($postdata['name']) ? $postdata['name'] : '';
        $arr['suppliers_desc'] = isset($postdata['suppliers_desc']) ? $postdata['suppliers_desc'] : '';
        $arr['contact_name'] = isset($postdata['contact_name']) ? $postdata['contact_name'] : '';
        $arr['phone'] = isset($postdata['phone']) ? $postdata['phone'] : '';
        $arr['address'] = isset($postdata['address']) ? $postdata['address'] : '';
        $arr['status'] = isset($postdata['status']) ? $postdata['status'] : '';
        $arr['sort'] = isset($postdata['sort']) ? $postdata['sort'] : '';
        $map['id'] = $suppliers_id;
        M('Suppliers')->where($map)->save($arr);
		$url = U(CONTROLLER_NAME . '/suppliers');
        if ($suppliers_id !== false) {
            $this->success(L('ADD_OK'), $url);
        } else {
            $this->error(L('ADD_ERROR'), $url);
        }
    }

    /**
     * 修改信息供货商
     * @Author xiaol
     */
    public function supplier_update()
    {
        $id = I('post.id');
        $postdata = I('post.');
        $arr['name'] = $postdata['name'];
        $arr['suppliers_desc'] = $postdata['suppliers_desc'];
        $arr['contact_name'] = $postdata['contact_name'];
        $arr['phone'] = $postdata['phone'];
        $arr['address'] = $postdata['address'];
        $arr['status'] = $postdata['status'];
        $arr['sort'] = $postdata['sort'];
        $where_s['id'] = $id;
        $where_s['shop_id'] = MID;
        $info = M('Suppliers')->where($where_s)->save($arr);
		$url = U(CONTROLLER_NAME . '/suppliers');
        if ($info !== false) {
            $this->success(L('EDIT_OK'), $url);
        } else {
            $this->error(L('EDIT_ERROR'), $url);
        }
    }

    /**
     * 编辑供货商
     * @Author xiaol
     */
    public function supplier_edit()
    {
        $id = I('get.id');
        if (!$id) $this->error(L('PARAM_ERR'));
        $edit = M('Suppliers');
        $edits = $edit->field(true)->find($id);
        $this->assign('id', $id);
        $this->assign($edits);
        $this->assign('edit', $edits);
        $this->assign('menu_action','suppliers');
        $this->display();
    }
	
    /**
     * 消费者保障服务
     * @Author xiaol
     */
    public function shop_contract(){
        $where=array();
        $type = 1;
        $where['type']=$type;
        $lists = M('ProjectLabel')->field(true)->where($where)->select();
        foreach($lists as $k=>$v){
            $map=array();
            $map['shop_id']=MID;
            $map['label_id']=$v['id'];
            $publish_wait=M('ProjectLabelLink')->where($map)->getField('publish_wait');
            $lists[$k]['publish_wait']=$publish_wait;
            $lists[$k]['is_publish']=(is_null($publish_wait))?0:1;
        }
        $this->assign('lists', $lists);
        $this->display();
    }
    /**
     * 消费者保障服务--0加入,3退出
     * @Author xiaol
     */
    public function apply_contract(){
        $return=$l_map=$m_map=$map=$data=array();$return['status']=0;
        $id=I('param.id');//label_id
        $type=I('param.type');//申请类型（0加入,3退出）
        $method=I('param.method');//1已有加入过
        if(is_null($id) || is_null($type)){
            $return['msg']='参数错误';
            $this->ajaxReturn($return);
        }
        $deposit=M('ProjectLabel')->where($l_map)->getField('price');
        if($type==0) {
            $m_map['id'] = MID;
            $member_money = M('Shops')->where($m_map)->getField('total_revenues');
            if ($member_money < $deposit) {
                $return['msg'] = '您的资金不够申请该项服务';
                $this->ajaxReturn($return);
            }
            shop_balance_log(MID, 1 ,$deposit, '申请加入('.idtoname($id,'ProjectLabel','label_name').')消费者保障服务','total_revenues');
            shop_balance_log(MID, 0 ,$deposit, '申请加入('.idtoname($id,'ProjectLabel','label_name').')消费者保障服务','freeze_price');
        }
        $data['publish_wait']=$type;
        $data['apply_time']=NOW_TIME;
        $l_map['id']=$id;
        $data['deposit']=$deposit;
        if($method==1){
            $map['label_id']=$id;
            $map['shop_id']=MID;
            $count=M('ProjectLabelLink')->where($map)->save($data);
        } else{
            $data['label_id']=$id;
            $data['shop_id']=MID;
            $count=M('ProjectLabelLink')->data($data)->add();
        }
        if($count>0){
            $return['status']=1;
        } else{
            if($type==1)$return['msg']='申请加入失败';
            elseif($type==2)$return['msg']='申请退出失败';
        }
        $this->ajaxReturn($return);
    }
    //获取当前供货商的所有分类、导航
    private function getNodeTree($pid=''){
        //获取当前供货商的分类
        $map['shop_id']=MID;
        $map['status']=1;
        $list=M('ShopsCategory')->where($map)->field(true)->select();
        if (empty($pid)) $pid = I('pid');
        $Tree = new \Common\Vendor\Tree();
        $treemini = $Tree->treemini($list);
        $select_categorys .= $Tree->treeminioption($treemini, $pid);
        $this->assign('select_categorys',$select_categorys);
        //获取当前供货商的导航
        $map['navtype']=4;
        unset($map['status']);
        $nodeData = M('Nav')->where($map)->field(true)->order('sort')->select();
        if ($nodeData) {
            $Tree = new \Common\Vendor\Tree();
            foreach ($nodeData as &$values) {
                $values['selected'] = $values['id'] == $pid ? 'selected="selected"' : '';
            }
            $str = "<option value='\$id' \$selected>\$spacer \$name</option>";
            $Tree->init($nodeData);
            $parent_node = $Tree->get_tree(0, $str);
            $this->assign('parent_node', $parent_node);
        }
    }
    /**
     * 供货商概况
     */
    public function statistics(){
        //收藏供货商数
        $map['shop_id']=MID;
        $collect_shops=M('ShopsCollect')->where($map)->count();
        //收藏商品数
        $where['shop_id']=MID;
        $goods=M('Goods')->where($map)->field('id')->select();
        $collect_goods=0;
        foreach ($goods as $k => $val) {
            $g_map['goods_id']=$val['id'];
            $result=M('GoodsCollect')->where($g_map)->field('id')->count();
            $collect_goods+=$result;
        }
        //商品数量
        $goods_num=M('Goods')->where($map)->count();
        //近30天下单数
        $lastdate=strtotime(date('Y-m-d',strtotime("-30 day")));
        $today=strtotime(date('Y-m-d',NOW_TIME));
        $order_map['shop_id']=MID;
        $order_map['pay_time']=array('between',array($lastdate,$today));
        $order_count=M('OrderInfo')->where($order_map)->count();
        $order_money=M('OrderInfo')->where($order_map)->sum('goods_allmoney');
        $order_avg=M('OrderInfo')->where($order_map)->avg('goods_allmoney');
        //下单会员数
        $order_member=M('OrderInfo')->where($order_map)->count();
        //销售走势
        $this->sales_trend($this->shop_info['id']);
        $this->hotgoods($this->shop_info['id']);
        $this->assign('order_member',$order_member);
        $this->assign('order_money',$order_money);
        $this->assign('order_avg',$order_avg);
        $this->assign('order_count',$order_count);
        $this->assign('collect_shops',$collect_shops);
        $this->assign('collect_goods',$collect_goods);
        $this->assign('goods_num',$goods_num);
        $tabid=I('param.tabid');
        if(!empty($tabid)) $this->display($tabid);
        else $this->display();
    }
    //供货商走势折线图
    private function sales_trend($shop_id){
        $postdata=I('param.');
        $map['shop_id']=$shop_id;
         if(empty($postdata['date_to'])){
            $today=strtotime(date('Y-m-d',NOW_TIME));
            $postdata['date_to']=time_format($today,'Y-m-d');
        }
        if(empty($postdata['date_from']))$postdata['date_from']=time_format(strtotime(date('Y-m-d',strtotime("-6 month"))));
        $map['addtime'][]=array('EGT',strtotime($postdata['date_from']));
        $map['addtime'][]=array('elt',strtotime($postdata['date_to']));
        $order_money = M('OrderInfo')->where($map)->field("sum(order_amount) as l_money,DATE_FORMAT(FROM_UNIXTIME(addtime),'%Y年%m月') as l_month")->group("DATE_FORMAT(FROM_UNIXTIME(addtime),'%Y年%m月')")->select();
        $order_num = M('OrderInfo')->where($map)->group("DATE_FORMAT(FROM_UNIXTIME(addtime),'%Y年%m月')")->count('id');
        $months[5]["time"]=time_format(NOW_TIME,'Y年m月');
        for($i=1;$i<6;$i++){$months[(5-$i)]["time"]=time_format(strtotime('-'.$i.' month'),'Y年m月');}
        foreach($order_money  as $v){
            $order_moneys[$v['l_month']] = $v['l_money'];
            $order_nums[$v['l_month']]=$order_num;
        }
        $name=array("订单金额（元）","订单数量（个）");
        $formart = array('order_moneys'=>$order_moneys,'order_nums'=>$order_nums);
        $formarttime =  array_keys($order_moneys);
        $formart = echarts_time_formarts($formart,$formarttime);
        $money_count = array(
                "legend"=>array('data'=>array($name[0],$name[1])),
                "xaxis"=>array("type"=>"category","data"=>$formarttime),     
                "series"=>array(
                    array("name"=>$name[0],"type"=>"line","stack"=>$name[0],"data"=>array_values($formart['order_moneys'])),
                    array("name"=>$name[1],"type"=>"line","stack"=>$name[1],"data"=>array_values($formart['order_nums']))
                ),
        );
        $ec = new \Common\Vendor\Echarts();
        $this->assign('Area_countm',$ec->show('Area_countm', $money_count,'line','销售额统计'));
        $this->assign($postdata);
    }
    private function hotgoods($shop_id){
        $map['shop_id']=$shop_id;
        $hot_goods=M('Goods')->where($map)->order('sell_count desc')->limit(5)->select();
        $this->assign('hot_goods',$hot_goods);
        $map['shop_id']=array('neq',0);
        $fellow_goods=M('Goods')->where($map)->order('sell_count desc')->limit(5)->select();
        $this->assign('fellow_goods',$fellow_goods);
    }
}
?>