<?php
/**
 * 供货商模型
 * @Copyright (C) 2017 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaol <1094186793@qq.com>
 * @Author chang <13331202938@126.com>
 */
namespace Common\Model;
use Think\Model;
class SuppliersModel extends Model
{
	public function get_common($param){
		$return=array();
		$return['status']=1;
		$suppliersid=$param['id'];
		$return=$this->get_suppliers($suppliersid,$param['mid']);
		if(!$return['status'])return $return;
		$return['suppliers_id']=$suppliersid;
		$cates=$this->get_suppliers_category($suppliersid,$param);
		$return['cates']=$cates;
		$cates_name=idtoname($param['suppliers_id'],'GoodsCategory');
		$return['cates_name']=$cates_name?$cates_name:'分类';
		$return['data']['setting']=$this->supplierss_setting($suppliersid,$param['request_type']);
		if(ACTION_NAME=='index'&&$return['data']['setting']['mode']==1)$return['data']['setting']['left']=1;
		$return['act_name']=ACTION_NAME;
		$hot_list=$this->get_suppliers_goods($suppliersid,2);
		$return['hot_list']=$hot_list['list'];
		$map=array();
		$map['suppliers_id']=$suppliersid;
		$map['status']=1;
		$map['pid']=0;
		$return['nav']=M('Nav')->where($map)->field('id,name,url')->select();
		return $return;
	}
	public function get_lists($suppliersid,$param=array()){
		$return=array();
		$return['request']=$param;
		$map=array();
		$map['suppliers_id']=$suppliersid;
		$map['status']=1;
		$map['is_delete']=0;
		$map['publish_wait']=1;
		$map['brand_id']=array('gt',0);
		$brandids=M('Goods')->where($map)->field('brand_id')->group('brand_id')->select();
		$all=array('brand_id'=>0,'name'=>'全部');
		if(!$param['brand_id'])$all['check']=1;
		array_unshift($brandids,$all);
		foreach($brandids as $k=>$v){
			if($param['brand_id']==$v['brand_id']){$brandids[$k]['check']=1;}
			$param_b=array();
			$param_b['id']=$suppliersid;
			$param_b['brand_id']=$v['brand_id'];
			if($param['suppliers_cid'])$param_b['suppliers_cid']=$param['suppliers_cid'];
			if($param['keyword'])$param_b['keyword']=$param['keyword'];
			if($v['brand_id']>0)$brandids[$k]['name']=idtoname($v['brand_id'],'Brand','brand_name');
			$brandids[$k]['url']=U(MODULE_NAME.'/suppliers/lists',$param_b);
		}
		$return['brands']=$brandids;
		$pricelists=$this->get_price_map($suppliersid,$param['price']);
		$return['pricelist']=$pricelists['pricelist'];
		$order_list=D('Common/Brand')->get_order_list($param,MODULE_NAME.'/suppliers/lists',2);
		$return['order_list']=$order_list['order_list'];
		$map=array();
		$map['suppliers_id']=$suppliersid;
		$map['status'] = 1;
        $map['publish_wait'] = 1;
        $map['is_delete'] = 0;
		$suppliers_goods_ids=M('Goods')->where($map)->getField('id',true);
		$map_label=array();
		$map_label['goods_id']=array('in',$suppliers_goods_ids);
		$labels=M('ProjectLabelLink')->where($map_label)->field('label_id')->group('label_id')->select();
		$label_ids=array();
		foreach($labels as $k=>$v){
			$param_l=I('param.');
			$labels[$k]['name']=idtoname($v['label_id'],'ProjectLabel','label_name');
			$param_l['label'.$k]=$v['label_id'];
			$labels[$k]['url']=U(MODULE_NAME.'/suppliers/lists',$param_l);
			if($param['label'.$k]==$v['label_id']){
				$labels[$k]['check']=1;
				unset($param_l['label'.$k]);
				$labels[$k]['url']=U(MODULE_NAME.'/suppliers/lists',$param_l);
			}
			if($param['label'.$k]>0)$label_ids[]=$param['label'.$k];
		}
		$return['labels']=$labels;
		$search_map=array();
		$search_map['suppliers_id']=$suppliersid;
		$keyword=trim($param['keyword']);
		if($keyword)$search_map['goods_name']=array('like','%'.$keyword.'%');
		if($param['brand_id']>0){
			$search_map['brand_id']=$param['brand_id'];
		}
		if($param['price_id']>0){
			$price_map=$price[$param['price_id']];
			if($price_map['max']>0)$search_map['suppliers_price']=array(array('elt',$price_map['max']),array('gt',$price_map['min']));
			if($price_map['max']==0&&$price_map['min']>0)$search_map['suppliers_price']=array('gt',$price_map['min']);
		}
		if(!empty($label_ids)){
			$map=array();
			$map['label_id']=array('in',$label_ids);
			$goods_ids=M('ProjectLabelLink')->where($map)->getField('goods_id',true);
			$search_map['id']=array('in',$goods_ids);
		}
		if(!empty($pricelists['suppliers_price']))$search_map['suppliers_price']=$pricelists['suppliers_price'];
		$page=$param['page']?$param['page']:1;
		$list=D('Common/Goods')->get_goods_list(0,$search_map,'',$order_list['order'],$page,8);
		$return['glist']=$list;
		return $return;
	}
    public function get_suppliers($id=0,$mid=0){
        $return=array();
        $return['status']=0;
        if(empty($id)){
            $return['msg']='参数错误！';
            return $return;
        }
        $suppliers=M('supplierss')->where('id = '.$id)->field(true)->find();
        if(empty($suppliers)){
            $return['msg']='该供货商不存在！';
            return $return;
        }
        if(empty($suppliers['status'])){
            $return['msg']='该供货商已闭店！';
            return $return;
        }
        $data=$this->format_suppliers_item($suppliers);
		$data['is_collect']=0;
		if($mid>0){
			$map=array();
			$map['suppliers_id']=$id;
			$map['uid']=$mid;
			$is_collect=M('suppliersCollect')->where($map)->count();
			if($is_collect)$data['is_collect']=1;
		}
        $return['status']=1;
        $return['data']=$data;
        return $return;
    }
    public function format_suppliers_item($data){
		$return=$data;
		$catids=explode(',',$data['cate_ids']);
		$catstr='';
		$catlong='';
        global $GoodsCategory;
		foreach($catids as $k=>$v){
			if($k<3)$catstr.=idtoname($v,'GoodsCategory').' ';
			$catlong.=idtoname($v,'GoodsCategory').' ';
		}
		$return['catlong']=$catlong;
		$return['catids']=$catstr;
        $return['city_format']=idtoname($data['city_id'],'Area');
        $return['district_format']=idtoname($data['district'],'Area');
        $return['town_format']=idtoname($data['town'],'Area');
        $return['community_format']=idtoname($data['community'],'Area');
        $return['updatetime_format']=date_format($data['updatetime'],'Y-m-d');
        $return['rank']=($data['end_time']>NOW_TIME)?0:$data['rank'];
        $return['rank_format']=empty($return['rank'])?'普通店铺':idtoname($return['rank'],'ProjectLabel','label_name');
        $return['cat_format']=idtoname($return['catids'],'GoodsCategory');
        $return['collect_count']=$this->collect_count($data['id']);
        $return['commont_info']=$this->get_suppliers_commont($data['id']);
        $return['average']=0;foreach($return['commont_info'] as $k=>$v){$return['average']+=$v['score'];}
        $return['cates']=$this->get_suppliers_category($data['id']);
        $return['goods_count']=$this->get_goods_count($data['id']);
        $return['good_rate']=empty($data['dp_count'])?'100%':(round(($data['dp_count_3']/$data['dp_count'])*100,2).'%');
        $return['middle_rate']=empty($data['dp_count'])?'0%':(round(($data['dp_count_2']/$data['dp_count'])*100,2).'%');
		$return['bad_rate']=empty($data['dp_count'])?'0%':(round(($data['dp_count_1']/$data['dp_count'])*100,2).'%');
        return $return;
    }
    public function get_goods_count($suppliersid=0){
        $return=0;
        $map=array();
        $map['suppliers_id']=$suppliersid;
        $map['status']=1;
        $map['publish_wait'] = 1;
        $map['is_delete'] = 0;
        $return=M('Goods')->where($map)->count();
        return $return;
    }

	 
	 public function get_suppliers_goods($suppliersid,$page_size=0,$page=1,$type=1){
		$map=array();
		$map['suppliers_id']=$suppliersid;
		switch($type){
			case 1:$order='sell_count desc,is_hot desc';break;
			case 2:$order='addtime desc';break;
			default :$order='is_new desc';
		}
        $list=D('Common/Goods')->get_goods_list(0,$map,'',$order,$page,$page_size);
		return $list;
	 }
	 /*
	 *获取会员向供货商发起的订单
	 */
	 public function suppliers_order($postdata,$is_num=0,$page_num=10,$field=true){
		$suppliersinfo=session('suppliers_info');
		$suppliers_id=$suppliersinfo['id'];
		$map['suppliers_id']=$suppliers_id;
		$map['is_delete']=0;
		if($is_num){
			$all_order['num']=M('OrderGoods')->where($map)->count();
			return $all_order;
		}
		//搜索条件
		if(!empty($postdata['time_form']))$map['addtime'][]=array('egt',strtotime($postdata['time_form']));
		if(!empty($postdata['time_to']))$map['addtime'][]=array('elt',strtotime($postdata['time_to']));
		if(!empty($postdata['order_sn']))$map['order_sn']=$postdata['order_sn'];
		if(!empty($postdata['buyer_name'])){
			$search_map['username']=array('like','%'.$postdata['buyer_name'].'%');
			$search_user=M('Member')->where($search_map)->getField('id',true);
			if($search_user)$map['uid']=array('in',$search_user);
		}
		$all_order=$all_order=page_list('OrderInfo',$map,'id desc',$field,$page_num,'',1);
		//格式化订单数据
		if($all_order){
			foreach($all_order['list'] as $k=>$v){
				$goods_info['all_num']=$goods_info['num']=0;
				$all_order['list'][$k]=$v;
				$all_order['list'][$k]['goods_amount']=$v['goods_amount'];
				$goods_map['order_id']=$v['id'];
				$goods_info['list']=M('OrderGoods')->where($goods_map)->field('id,goods_id,goods_name,goods_attr,goods_price,goods_number')->select();
				// $goods_info['num']=M('OrderGoods')->where($goods_map)->count();
				foreach($goods_info['list'] as $ke=>$vo){
                    $goodsinfo=idtoname($vo['goods_id'],'Goods','img,goods_weight');
					$goods_info['list'][$ke]=$vo;
					$goods_info['all_num']+=$vo['goods_number'];
					$goods_info['list'][$ke]['goods_price']=$vo['goods_price'];
					$goods_info['list'][$ke]['img']=$goodsinfo['img'];
                    $goods_info['list'][$ke]['goods_attr_format'] = unserialize($vo['goods_attr']);
                    $goods_info['list'][$ke]['goods_weight'] = $goodsinfo['goods_weight'];
				}
				$all_order['list'][$k]['goods']=$goods_info;
			}
		}
        return $all_order;
    }
	public function collect_suppliers($id){
        $return = $where = $map_co = array();
        $member_info = checkuserauthtype();
        if (empty($member_info)) {
            $return['msg'] = '请登录';
            $return['status'] = 0;
            $return['url'] = getjumpurl('JUMP_1');
        } else {
            $collect = M('supplierssCollect');
            $map_co['suppliers_id'] = $id;
            $map_co['uid'] = $member_info['id'];
            $favinfo = $collect->where($map_co)->count();
            if ($favinfo) {
                $favinfo = $collect->where($map_co)->delete();
                $return['status'] = 2;
                $return['msg'] = '取消收藏成功!';
            } else {
                $postdata['suppliers_id'] = $id;
                $postdata['uid'] = $member_info['id'];
                $postdata['addtime'] = NOW_TIME;
                $postdata['status'] = 1;
                $result = $collect->add($postdata);
                if ($result) {
                    $return['status'] = 1;
                    $return['msg'] = '收藏成功';
                } else {
                    $return['status'] = 3;
                    $return['msg'] = '收藏失败!';
                }
            }
        }
        return $return;
	}
private function get_grade_price($suppliers_id){
    if(empty($suppliers_id)) return false;
    $map=array();
    $map['g.status']=1;
    $map['g.publish_wait']=1;
    $map['g.is_delete']=0;
    $map['g.suppliers_id']=$suppliers_id;
    $row = M('Goods')->alias('g')->field('min(g.suppliers_price) AS min, max(g.suppliers_price) AS max')->where($map)->find();
    $price_grade = 0.0001;
    for($i=-2; $i<= log10($row['max']); $i++){$price_grade *= 10;}      
    $dx = ceil(($row['max'] - $row['min']) / 4 / $price_grade) * $price_grade;
    if($dx == 0){$dx = $price_grade;}   
    for($i = 1; $row['min'] > $dx * $i; $i ++);
    for($j = 1; $row['min'] > $dx * ($i-1) + $price_grade * $j; $j++);
    $row['min'] = $dx * ($i-1) + $price_grade * ($j - 1);
    for(; $row['max'] >= $dx * $i; $i ++);
    $row['max'] = $dx * ($i) + $price_grade * ($j - 1);
    $price_grades = M('Goods')->alias('g')->field('(FLOOR((g.suppliers_price - '.$row['min'].') / '.$dx.')) AS sn, COUNT(*) AS goods_num')->where($map)->group('sn')->select();
    foreach ($price_grades as $key=>$val){
        $temp_key = $key + 1;
        $price_grades[$temp_key]['goods_num'] = $val['goods_num'];
        $price_grades[$temp_key]['start'] = $row['min'] + round($dx * $val['sn']);
        $price_grades[$temp_key]['end'] = $row['min'] + round($dx * ($val['sn'] + 1));
        $price_grades[$temp_key]['price_range'] = $price_grades[$temp_key]['start'] . '&nbsp;-&nbsp;' . $price_grades[$temp_key]['end'];
        $price_grades[$temp_key]['formated_start'] = number_format($price_grades[$temp_key]['start'] ,2, '.', '');
        $price_grades[$temp_key]['formated_end'] = number_format($price_grades[$temp_key]['end'],2, '.', '');
        $price_grades[$temp_key]['url'] = U('Cate/Index', array('cid'=>$cat_id, 'bid'=>$brand, 'price_min'=>$price_grades[$temp_key]['start'], 'price_max'=> $price_grades[$temp_key]['end'], 'filter_attr'=>$filter_attr_str));
        if (isset($_REQUEST['price_min']) && $price_grades[$temp_key]['start'] == $price_min && $price_grades[$temp_key]['end'] == $price_max){
            $price_grades[$temp_key]['selected'] = 1;
        }else{
            $price_grades[$temp_key]['selected'] = 0;
        }
        $pricelist[$temp_key] = $price_grades[$temp_key]['price_range'];
    }
    ksort($pricelist);
    return $pricelist;
}
private function get_price_map($suppliers_id,$price){
    if(empty($suppliers_id)) return $return;
    $pricelist = $this->get_grade_price($suppliers_id);
    $return['pricelist'] = $pricelist;
    if (!empty($price) && !empty($pricelist)) {
            $pricedata = $pricelist[$price];
            if (!empty($pricedata)) {
                if (str_exists($pricedata, '-')) {
                    $pricearr = explode('-', str_replace('&nbsp;', '', $pricedata));
                    $return['suppliers_price'][] = array('EGT', $pricearr[0]);
                    $return['suppliers_price'][] = array('elt', $pricearr[1]);
                } else if (str_exists($pricedata, '以上')) {
                    $return['suppliers_price'] = array('EGT', str_replace('以上', '', $pricedata));
                }
            }
    }
    return $return;
}
}
?>