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

namespace Common\Model;
use Think\Model;
class PurGoodsModel extends Model{   
    protected $tableName = 'goods';
    /**
     * 根据类型查商品
     * @param int $type 类型（0普通商品列表，没有其他条件；1精品；2新品；3热卖；456）
     * @param array $map
     * @return array
     */
    public function get_goods_list($type = 0, $map = array(), $join = '', $order = '', $p = 1, $pagesize = 0)
    {
        $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'] = 5;
        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)) {
            GLOBAL $PurchaseCategory;
            $catinfo = $PurchaseCategory[$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;
        $goodslist = page_list('Goods', $map, $order, true, $pagesize, $join, $p);
        foreach ($goodslist['list'] as $key => $val) {
            $goodslist['list'][$key] = $this->format_goodslist_item($val);
        }
        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)
    {
        $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;
        }
        $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['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 = $labels = $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;unset($labels[14]);}//标签id=14是满减
			if(in_array('15',$labels)){$labels_array[]=2;unset($labels[15]);}//标签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', implode(',', $labels));
				$goodsids_otherlabels = M('ProjectLabelLink')->where($ids_map)->getField('goods_id', true);
				if(!empty($goodsids_otherlabels))$goodsids=array_merge($goodsids,$goodsids_otherlabels);
			}
			if (!empty($goodsids)) $return['map']['id'] = array('in', implode(',', $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='')
    {
        $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)) {
            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();
        $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 $PurchaseCategory;
            if ($is_integral == 1) $catinfo = $PurchaseCategory[$info['catid']];
            else $catinfo = $PurchaseCategory[$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)
    {
		if(empty($param['default']))$param['default']=0;
		if(empty($param['shop_price']))$param['shop_price']=1;
		if(empty($param['updatetime']))$param['updatetime']=1;
		if(empty($param['sell_count']))$param['sell_count']=1;
		
        $order_list['default'] = array('name' => '默认', 'class' => 1, 'icon' => 0);
        $order_list['shop_price'] = array('name' => '价格', 'class' => 0, 'icon' => 1, 'sort'=>1);
        $order_list['updatetime'] = array('name' => '时间', 'class' => 0, 'icon' => 1, 'sort'=>1);
        $order_list['sell_count'] = array('name' => '销量', 'class' => 0, 'icon' => 1, 'sort'=>1);
        
        foreach ($order_list as $k => $v) {
			$tmp_url_param = $param;
            $tmp_url_param['p'] = 1;
            if ($param[$k] == 1) {//1为降序
				$tmp_url_param['order_name']=$k;
				if( !empty($param['order_name']) && $param['order_name']==$k ){
					$order_list[$k]['icon'] = 1;//升序
					$order_list[$k]['class'] = 1;
					$order_list['default']['class'] = 0;
					$tmp_url_param[$k]=2;//改为升序
					$order_list[$k]['sort'] = 2;//手机变更排序
				}
            }elseif($param[$k] == 2) {//2为升序
				$tmp_url_param['order_name']=$k;
				if( !empty($param['order_name']) && $param['order_name']==$k ){
					$order_list[$k]['icon'] = 2;//降序
					$order_list[$k]['class'] = 1;
					$order_list['default']['class'] = 0;
				}
				$tmp_url_param[$k]=1;//改为降序
				$order_list[$k]['sort'] = 1;//手机变更排序
            }else{
				unset($tmp_url_param['order_name']);
			}
			$order_list[$k]['url'] = geturl("index", $tmp_url_param);
        }
		return $order_list;
    }
}
?>