<?php
/**
 * 商品模型
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaol <1094186793@qq.com>
 */

namespace Common\Model;
use Think\Model;
class GoodsModel extends Model
{
    /**
     * 根据类型查商品
     * @param int $type 类型（0普通商品列表，没有其他条件；1精品；2新品；3热卖；456）
     * @param int $goods_type 类型（0普通商品列表，5订货商品）
     * @param array $map
     * @return array
     */
    public function get_goods_list($type = 0, $map = array(), $join = '', $order = '', $p = 1, $pagesize = 0,$goods_type=1){
        $pagesize = empty($pagesize) ? C('WEB_GOODS_PAGE') : $pagesize;
        $p = empty($p) ? 1 : $p;
        $map['status'] = 1;
        $map['publish_wait'] = 1;
        $map['is_delete'] = 0;
        $map['goods_type'] = $goods_type;
        switch ($type) {
            case 1:
                $map['is_best'] = 1;
                break;
            case 2:
                $map['is_new'] = 1;
                break;
            case 3:
                $map['is_hot'] = 1;
                break;
        }
        $catid = $map['cat_id'];
        if (!empty($catid)) {
            if($goods_type==5){
                GLOBAL $PurchaseCategory;
                $catinfo = $PurchaseCategory[$catid];
            }else{
                GLOBAL $GoodsCategory;
                $catinfo = $GoodsCategory[$catid];
            }
            
            $extension_goods_id = get_extension_goods($catinfo['allson'], 1);
            if (!empty($catinfo['allson'])) $where['cat_id'] = array('in', $catinfo['allson']);
            if (!empty($extension_goods_id)) $where['id'] = array('in', $extension_goods_id);
            if (!empty($where)) {
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
                unset($map['cat_id']);
            } else {
                $map['cat_id'] = $catid;
            }
        }
        $order = empty($order) ? 'sell_count desc,avg_point desc,count desc,updatetime desc' : $order;
        /*if(C('IS_WAREHOUSE')==1&&$goods_type==5){//仓库开启
            $shops_info=session('shops_info');
            $area = idtoname($shops_info['shop_id'],'Shops','province,city_id,district');
            $area_id='';
            if($area['district']){
                $area_id = $area['district'];
            }
            if(!$area_id){
                $area_id = $area['city_id'];
            }
            if(!$area_id){
                $area_id = $area['province'];
            }
            $ids = library_goods($area_id);
            if(count($ids)>0){
                $map['id']=array('in',$ids);
            }else{
                $map['id']='bcz';
            }

        }*/
        $goodslist = page_list('Goods', $map, $order, true, $pagesize, $join, $p);
        foreach ($goodslist['list'] as $key => $val) {
            $goodslist['list'][$key] = $this->format_goodslist_item($val);
			$where['style_ext_id'] = $val['id'];
            $price = M('PromotExt')->where($where)->order('id desc')->field('remarks,act_id')->find();
            $goodslist['list'][$key]['remarks'] = unserialize($price['remarks']);
        }
        return $goodslist;
    }

    /**
     * 格式化商品项
     * @param array $data
     * @return array
     */
    public function format_goodslist_item($data = array())
    {
        $result = $data;
        $result['goods_weight'] = format_decimal($data['goods_weight']);
        $result['market_price'] = format_price($data['market_price']);
        $result['shop_price'] = format_price($data['shop_price'], false);
        $result['supply_price'] = format_price($data['supply_price']);
        $result['avg_point'] = format_decimal($data['avg_point']);
        $result['promot'] = D('Common/Promot')->goods_to_promot($data['id'],1);
        return $result;
    }

    /**
     * 根据商品id查找该商品的内容
     * @param int $id
     * @return array
     */
    public function get_goods_item($id = 0,$rank='')
    {
        $return = $map = array();
        $return['status'] = 0;
        if (empty($id)) {
            $return['msg'] = '参数错误';
            $return['url'] = getjumpurl('JUMP_2');
            return $return;
        }
        $map['g.id'] = $id;
        $data = M('Goods')->alias('g')->where($map)->JOIN('LEFT JOIN __GOODS_CONTENT__ gc ON gc.goods_id=g.id')->field('g.*,gc.*')->find();
        if (empty($data)) {
            $return['msg'] = '未找到该商品';
            return $return;
        }
        $member_info=session('member_info');
        if($member_info){

            $data['rank_id']=$member_info['rank_id'];
        }
        if($rank !=''){
            $data['rank_id']=$rank;
        }
        $return['status'] = 1;
        $return['data'] = $this->format_goods_item($data);
        return $return;
    }

    /**
     * 格式化商品项
     * @param array $data
     * @return array
     */
    public function format_goods_item($data = array())
    {
        $result = $data;
        $result['goods_weight'] = format_decimal($data['goods_weight']);
        $result['market_price'] = $data['market_price'];
        $result['market_price_format'] = format_price($data['market_price']);
        $result['shop_price'] = format_price($data['shop_price'], false);
        $result['shop_prices'] = empty($data['shop_price']) ? 0 : $data['shop_price'];
        $result['supply_price'] = format_price($data['supply_price']);
        $result['avg_point'] = format_decimal($data['avg_point'])*100;
        $result['sell_count'] = empty($data['sell_count']) ? 0 : $data['sell_count'];
        $result['img'] = format_url($data['img']);
        $shop_id=get_wxsmall_shop_id();
        $rank=$data['rank_id'];
        $price_info=D('Common/Takeout')->get_min_price($shop_id,$data['id']);
        if($data['is_promote']){

            $result['promote_type']=1;
            $result['is_promote'] =$data['is_promote'];
            $result['promote_price'] = $data['promote_price'];

            // $result['promote_number'] = intval($data['sell_count']); //已抢
            // if($data['goods_number']>0) $result['pover_number'] = intval($data['goods_number'])-intval($data['sell_count']); //仅剩
            // if($data['goods_number']==-1) $result['pover_number'] = 99999; //仅剩
            $result['promote_number'] = intval($data['goods_max_number'])-intval($data['goods_number']); //已抢
            if($data['goods_number']>0) $result['pover_number'] = intval($data['goods_number']); //仅剩
            if($data['goods_number']==0) $result['pover_number'] = 0;
            if($data['goods_number']==-1) $result['pover_number'] = 99999; //仅剩
            /*
            * 6-29 $promote_info
            */
            $promote_info = M('PromotAct')->where('id='.$data['promote_id'])->field(true)->find();
            if($data['promote_end_time']<NOW_TIME || ($rank < $promote_info['user_rank'])){
                $result['is_overdue'] = 1; //活动结束
                $result['type_show']=1;
                $result['is_promote']=0;
            }else if($data['promote_start_time']<=NOW_TIME && $data['promote_end_time']>NOW_TIME){
                $result['is_overdue'] = 0;
                $result['shop_price'] = $price_info['goods_price'];
                $result['type_show']=0;

                $result['shop_price']=$data['promote_price'];
                $discount=format_decimal($price_info['goods_price']/$data['shop_price']*10,1);
                $result['discount_mark']='限时'.$discount.'折';
                $result['deil_name'] ='限时'.$discount.'折';
            }


        }else if($data['pt_id']){
            $result['promote_type']=2;
            $ptid = M('PromotAct')->where('id='.$data['pt_id'])->field('id,buy_limit,start_time,end_time,user_rank,group_number')->find();
            $pt_arr=array();
            $pt_arr['act_id'] = $ptid['id'];
            $pt_arr['style_ext_id'] = $data['id'];
            $pt_arr['style'] = 4;
            $pt_money = M('PromotExt')->where($pt_arr)->getField('remarks');
            $pt_money = unserialize($pt_money);
            if($pt_money>0) {$result['pt_price'] = format_decimal($pt_money,2);}
            $result['pt_id'] = $data['pt_id'];
            // $result['goods_number'] = $data['goods_number']; //累计售出
            if($data['goods_number']>0) $result['goods_number'] = intval($data['goods_number']); //仅剩
            if($data['goods_number']==-1) $result['goods_number'] = 99999; //仅剩

            if($ptid['end_time']<NOW_TIME || ($rank < $ptid['user_rank'])){
                // $result['is_overdue'] = 1; //拼团已过期
                $result['is_ptdue'] = 1; //拼团已过期
                $result['type_show']=1;
                $result['pt_id']=0;

            }else if($ptid['start_time']<=NOW_TIME && $ptid['end_time']>NOW_TIME){
                $result['shop_price']=$result['pt_price'];
                // $result['is_overdue'] = 0;
                $result['is_ptdue'] = 0;
                $result['type_show']=0;
                $result['pin_mark']=$ptid['group_number'].'人团';
            }

            //已拼
            $oarrs=array();
            $oarrs['pt_id'] = $data['pt_id'];
            $oarrs['pay_status'] = 3;
            $oarrs['status'] = array('neq',4);
            $oarrs['is_delete'] = 0;
            $oi_ids = M('OrderInfo')->where($oarrs)->getField('id',true);
            if($oi_ids){
                $maph = array();
                $maph['order_id'] = array('in',$oi_ids);
                $maph['goods_id'] = $data['id'];
                $og_count = M('OrderGoods')->where($maph)->sum('goods_number');
            }else{
                $og_count = 0;
            }
            $result['yp_number'] = intval($og_count);
        }
        // $result['contract_list']=$this->get_goods_contract($data['shop_id']);
        return $result;
    }
    public function get_goods_contract($shop_id=0){
        $return=array();
        if($shop_id==0) return $return;
        $map['pll.shop_id']=$shop_id;
        $map['pll.publish_wait']=array('in','1,3');
        $map['pl.type']=1;
        $map['pl.status']=1;
        $return=M('ProjectLabelLink')->Distinct(true)->alias('pll')->join('LEFT JOIN __PROJECT_LABEL__ pl ON pll.label_id = pl.id')->where($map)->field('pl.label_name as name,pl.images as img,pl.brief_url as url')->select();
        return $return;
    }

    /**
     * 收藏
     * @param $goods_id
     * @return  array
     */
    public function favorite($goods_id, $type, $is_on)
    {
        $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('GoodsCollect');
            $map_co['goods_id'] = $goods_id;
            $map_co['uid'] = $member_info['id'];
            $map_co['type'] = $type;
            if ($type == 1) {
                $where['goods_id'] = $goods_id;
                $map_co['integral_id'] = M('GoodsIntegral')->where($where)->getField('id');
            }
            $favinfo = $collect->where($map_co)->count();
            if ($favinfo) {
                $favinfo = $collect->where($map_co)->delete();
                $return['status'] = 2;
                $return['msg'] = '取消收藏成功!';
            } else {
                $postdata['goods_id'] = $goods_id;
                $postdata['uid'] = $member_info['id'];
                $postdata['addtime'] = NOW_TIME;
                $postdata['status'] = 1;
                $postdata['type'] = $type;
                if ($type == 1) {
                    $where['goods_id'] = $goods_id;
                    $postdata['integral_id'] = M('GoodsIntegral')->where($where)->getField('id');
                }
                $result = $collect->add($postdata);
                if ($result) {
                    $return['status'] = 1;
                    $return['is_on'] = $is_on;
                    $return['msg'] = '收藏成功';
                } else {
                    $return['status'] = 3;
                    $return['is_on'] = $is_on;
                    $return['msg'] = '收藏失败!';
                }
            }
        }
        return $return;
    }

    /**
     *判断是否收藏
     * @param $goods_id
     * @return  array
     */
    public function is_collect($goods_id, $type)
    {
        $where = $map = array();
        //是否收藏
        $member_info = checkuserauthtype();
        $map['uid'] = $member_info['id'];
        $map['goods_id'] = $goods_id;
        $map['type'] = $type;
        if ($type == 1) {
            $where['goods_id'] = $goods_id;
            $map['integral_id'] = M('GoodsIntegral')->where($where)->getField('id');
        }
        $is_collection = M('GoodsCollect')->where($map)->count();
        return $is_collection;
    }

    /**
     * 获取商品列表页标签筛选条件
     * @param $param
     * @return array
     */
    public function get_label_map($param)
    {
        $return =  $ids_map =$goodsids =array();
        foreach ($param as $ke => $va) {
            if ($param['unsetlabel']!=$va && str_exists($ke, 'label_')) $labels[] = str_replace('label_', '', $ke);
        }
        if (!empty($labels)) {
            if(in_array('9',$labels)){//标签id=9是新品
                $return['map']['is_new']=1;
                unset($labels[9]);
            }
            if(in_array('10',$labels)){//标签id=10是包邮
                $return['map']['is_shipping']=1;
                unset($labels[10]);
            }

            $labels_array=array();
            if(in_array('14',$labels)){$labels_array[]=1;$key = array_search('14', $labels);unset($labels[$key]);}//标签id=14是满减
            if(in_array('15',$labels)){$labels_array[]=2;$key = array_search('15', $labels);unset($labels[$key]);}//标签id=14是满减
            if($labels_array){
                $pp_map=array();
                $pp_map['pa.start_time']=array('lt',NOW_TIME);
                $pp_map['pa.end_time']=array('gt',NOW_TIME);
                $pp_map['pa.act_type']=count($labels_array)>1?array('in',$labels_array):implode('',$labels_array);
                $pp_map['pe.style']=3;
                $goodsids=M('PromotExt')->alias('pe')->join('LEFT JOIN __PROMOT_ACT__ pa ON pe.act_id = pa.id')->where($pp_map)->getField('style_ext_id', true);
            }
            if(!empty($labels)){
                $ids_map['label_id'] = array('in',$labels);
                $goodsids_otherlabels = M('ProjectLabelLink')->where($ids_map)->getField('goods_id', true);
                if(!empty($goodsids_otherlabels) && !empty($goodsids))$goodsids=array_merge($goodsids,$goodsids_otherlabels);
                else $goodsids=!empty($goodsids_otherlabels)?$goodsids_otherlabels:$goodsids;
            }
            if (!empty($goodsids)) $return['map']['id'] = array('in',$goodsids);
            else $return['map']['id'] = 0;
        }
       $return['labels'] = $labels;
        return $return;
    }

    //列表页的seo
    public function format_listseotile($brand_id, $catid, $is_integral = 0, $is_new = 0, $is_hot = 0,$keywords='',$goods_type=1)
    {
        $seotitle = $seokeywords = $seodescription = '';
        $return = array();
        if (!empty($brand_id)) {
            $map=array();
            $map['id']=$brand_id;
            $brandinfo = M('Brand')->where($map)->field('id,brand_name,seotitle,seokeywords,seodescription')->cache(true)->find();
            $seotitle .= ($brandinfo['seotitle'] ? $brandinfo['seotitle'] : $brandinfo['brand_name']) . '_';
            $seokeywords .= (empty($brandinfo['seokeywords']) ? $brandinfo['brand_name'] : $brandinfo['seokeywords']) . ',';
            $seodescription .= (empty($brandinfo['seodescription']) ? $brandinfo['brand_name'] : $brandinfo['seodescription']) . ',';
        }
        if (!empty($catid) && $goods_type==1) {
            GLOBAL $GoodsCategory;
            $catinfo = $GoodsCategory[$catid];
            $seotitle .= ($catinfo['seotitle'] ? $catinfo['seotitle'] : $catinfo['name']) . '_';
            $seokeywords .= (empty($catinfo['seokeywords']) ? $catinfo['name'] : $catinfo['seokeywords']) . ',';
            $seodescription .= (empty($catinfo['seodescription']) ? $catinfo['name'] : $catinfo['seodescription']) . ',';
        }elseif(!empty($catid) && $goods_type==5){
            GLOBAL $PurchaseCategory;
            $catinfo = $PurchaseCategory[$catid];
            $seotitle .= ($catinfo['seotitle'] ? $catinfo['seotitle'] : $catinfo['name']) . '_';
            $seokeywords .= (empty($catinfo['seokeywords']) ? $catinfo['name'] : $catinfo['seokeywords']) . ',';
            $seodescription .= (empty($catinfo['seodescription']) ? $catinfo['name'] : $catinfo['seodescription']) . ',';
        }
        // if ($is_integral == 1) $seotitle .= '积分商城_';
        if($is_new == 1) $seotitle .= '新品_';
        if($is_hot == 1) $seotitle .= '热销商品_';
        if(!empty($keywords)) $seotitle .='搜索结果_'.$keywords.'_';
        $seotitle .= C('WEB_SITE_TITLE');
        $return['tplseo_keywords'] = $seokeywords;
        $return['tplseo_description'] = $seodescription;
        $return['tplseo_title'] = $seotitle;
        return $return;
    }

    //内容页的seo
    public function format_contseotitle($info, $is_integral = 0)
    {
        $seotitle = $seokeywords = $seodescription = '';
        $return = array();
        // zjn 19-1-18 商品内容页title加上小店名称
        $lshop_id=cookie("lshop_id");
        if($lshop_id){
            $lname = idtoname($lshop_id,'LittleShop','name');
            $seotitle.=$lname.'_';
        }
        // end--------
        $seotitle .= ($info['seotitle'] ? $info['seotitle'] : $info['goods_name']) . '_';
        $seokeywords .= empty($info['seokeywords']) ? $info['goods_name'] : $info['seokeywords'];
        $seodescription .= empty($info['seodescription']) ? $info['goods_name'] : $info['seodescription'];
        if (($is_integral == 0 && (!empty($info['cat_id']))) || ($is_integral == 1 && (!empty($info['catid'])))) {
            GLOBAL $GoodsCategory;
            if ($is_integral == 1) $catinfo = $GoodsCategory[$info['catid']];
            else $catinfo = $GoodsCategory[$info['cat_id']];
            $seotitle .= $catinfo['name'] . '_';
            $seokeywords .= (empty($catinfo['seokeywords']) ? $catinfo['name'] : $catinfo['seokeywords']) . ',';
            $seodescription .= (empty($catinfo['seodescription']) ? $catinfo['name'] : $catinfo['seodescription']) . ',';
        }
        if ($is_integral == 1) $seotitle .= '积分商城_';
        $seotitle .= C('WEB_SITE_TITLE');
        $return['tplseo_keywords'] = $seokeywords;
        $return['tplseo_description'] = $seodescription;
        $return['tplseo_title'] = $seotitle;
        return $return;
    }

    /**
     *排序
     * @param $param
     * @return array
     */
    public function cate_order($param,$goods_type = 1){
        if(empty($param['sort']))$param['sort']='desc';
        $now_sort=$next_sort=$param['sort'];
        $next_sort=$param['sort']=='desc'?'asc':'desc';
        $order_list[] = array('name' => '价格(由低到高)','field'=>"shop_price",'sort'=>'asc');
        $order_list[] = array('name' => '价格(由高到低)','field'=>"shop_price",'sort'=>'desc');
        $order_list[] = array('name' => '时间','field'=>"updatetime");
        $order_list[] = array('name' => '销量','field'=>"sell_count");
        if(!empty($param['cat_id'])){$param['id']=$param['cat_id'];unset($param['cat_id']);}
        foreach ($order_list as $key => $v) {
            $k=$v['field'];
            $tmp_url_param = $param;
            $tmp_url_param['p'] = 1;
            $tmp_url_param['order_name']=$k;
            $loopsort=$v['sort']?$v['sort']:$now_sort;
            $order_list[$key]['class']=0;
            if( !empty($param['order_name']) && $param['order_name']==$k){
                if(empty($v['sort'])){
                    $loopsort=$next_sort;
                    $order_list[$key]['class']=$loopsort!=$now_sort?1:0;
                }else{
                    $order_list[$key]['class']=$loopsort==$now_sort?1:0;
                }
            }
            $order_list[$key]['sort']=$tmp_url_param['sort']=$loopsort;
            $tmp_url_param=array_filter($tmp_url_param);
            if($goods_type == 5){
                $order_list[$key]['url'] = geturl("goods_list", $tmp_url_param);
            }else{
                $order_list[$key]['url'] = geturl("index", $tmp_url_param);
            }
        }
        return $order_list;
    }
	public function service_cont($goods_id,$type=4){
		if(empty($goods_id))return false;
		$data = M('Goods')->field(true)->find($goods_id);
		if($data['shop_ids']){
			$shop_ids = implode(',',array_filter(explode(',',$data['shop_ids'])));
			$s_map['id'] = getShopid($shop_ids);
		}else{
			$s_map['id'] = get_wxsmall_shop_id();
		}
		$return['shop_info'] = M('Shops')->where($s_map)->find();
		$return['url']=U('Article/article_cont',array('id'=>$data['id'],'type'=>'goods','eid'=>MID));
		//其它热门服务
		if($data['shop_id']){
			$shopid = $data['shop_id'];
		}else{
			if($data['shop_ids']){
				$shop_ids = implode(',',array_filter(explode(',',$data['shop_ids'])));
				$shopid = getShopid($shop_ids);
			}else{
				$shopid = get_wxsmall_shop_id();
			}
		}
		if($type == 6){
			//套餐内服务信息
			$return['service_infos'] = json_decode($data['contain_service'],true);
		}
		$return['hot_service'] = get_service_goods($shopid,4,'sell_count desc');
		$return['data'] = $data;
		return $return;
	}
	public function service_list($shop_id,$pagesize,$p=1,$type=4){
		$pagesize=empty($pagesize)?C('WEB_GOODS_PAGE'):$pagesize;
		// $shop_ids = ','.$shop_id.',';
		$map['goods_type'] = $type;
		$map['status'] = 1;
		$map['is_delete'] = 0;
		$map['publish_wait'] = 1;
		// $map['_string'] = "shop_ids like '%".$shop_ids."%' OR shop_ids='0'";
		$map['_string'] = "shop_ids = ".$shop_id." OR shop_ids='0'";
		$list = page_list('Goods', $map,'', true, $pagesize,'', $p);
		if($type == 6){
			foreach ($list['list'] as $key => $value) {
				$list['list'][$key]['contain_service'] = json_decode($value['contain_service'],true);
			}
		}
		return $list;
	}
	public function services_list($map,$order,$pagesize,$p=1){
		$pagesize=empty($pagesize)?C('WEB_GOODS_PAGE'):$pagesize;
		if(!$order)$order = '';
		if(!$map)$map = '';
		$list = page_list('Goods', $map, $order, true, $pagesize,'', $p);
		return $list;
	}
    /**
     * 商品名称和商品编号同步
     * @param $goods_id 商品id
     * @param $goods_sn 商品编号
     * @param $goods_name 商品名称
     * @param $attr_key 属性
     */
    public function sync_goods_sn($goods_id,$goods_sn='',$goods_name='',$attr_key=''){
        if(empty($goods_id))return false;
        if(empty($goods_sn) && empty($goods_name))return false;
        //更新进销存
        $data=$map=array();
        if(!empty($goods_sn))$data['goods_sn']=$goods_sn;
        if(!empty($goods_name))$data['goods_name']=$goods_name;
        $map['goods_id']=$goods_id;
        $map['goods_attr_sn']=$attr_key;
        $map['status']=array('lt',3);
        M('InvoicingGoods')->where($map)->save($data);      
        
        //更新购物车
        if(empty($attr_key)){            
            $data=$map=array();
            $data['goods_sn']=$goods_sn;
            if(!empty($goods_name))$data['goods_name']=$goods_name;
            $map['goods_id']=$goods_id;
            M('Cart')->where($map)->save($data);
        }        
        //更新门店商品        
        if(!empty($goods_sn) && empty($attr_key)){            
            $data=$map=array();
            $data['goods_sn']=$goods_sn;
            $map['goods_id']=$goods_id;
            M('ShopsGoods')->where($map)->save($data);
        } 
    }
}
?>