<?php
/**商品属性
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author dongziyi <xiaogg@sina.cn>
 */

namespace Common\Model;
use Think\Model;
class GoodsAttrModel extends Model
{
    /**
     * 根据商品id得到商品属性，商品规格，商品内容(商品详情页用)
     * @param $goods_id 商品id
     */
    public function getattr($goods_id){
        $root = $stock = $attr = $newarr = array();
        $where['ga.goods_id'] = $map['goods_id'] = $goods_id;
        $stockcount = M('GoodsAttrStock')->where($map)->count();
        if ($stockcount > 0) {
            $all_stocks=array();
            $liststock = M('GoodsAttrStock')->field('attr_key,stock_cfg,sell_count,attr_price')->where($map)->select();
            if (!empty($liststock)) {
                foreach ($liststock as $k => $v) {//判断商品库存
                    if (empty($v['attr_key'])) contiue;
                    $stock[$k] = explode('_', $v['attr_key']);
                    $all_stocks+=$stock[$k];
                    //$stockmap['id'] = array('in', $stock[$k]);
                    //$attr_price = M('GoodsAttr')->where($stockmap)->sum('attr_price');
                    $stocks[$v['attr_key']]['attr_key'] = $v['attr_key'];
                    $stocks[$v['attr_key']]['stock_cfg'] = $v['stock_cfg'];
                    $stocks[$v['attr_key']]['sell_count'] = $v['sell_count'];
                    $stocks[$v['attr_key']]['attr_price'] = $v['attr_price'];
                }
            }
            
            $list = M('GoodsAttribute')->alias('g')->where($where)->JOIN('LEFT JOIN __GOODS_ATTR__ ga ON ga.attr_id=g.id')->field('ga.*,g.name,g.options,g.type')->select();
            foreach ($list as $k => $v) {
                if ($v['type'] == "text") {
                    $attr[$v['attr_id']]['name'] = $v['name'];
                    if ($v['attr_img']) {
                        $attr[$v['attr_id']]['attr_img'] = $v['attr_img'];
                    }
                    //$attr[$v['attr_id']]['price'] = $v['attr_price'];
                    $attr[$v['attr_id']]['attr_value'] = $v['attr_value'];
                } else {
                    if(in_array($v['id'],$all_stocks)){
                        $formatarr = array();
                        $newarr[$v['attr_id']]['name'] = $v['name'];
                        $newarr[$v['attr_id']]['options'][$v['id']]['id'] = $v['id'];
                        $formatarr = strtoarray($v['options']);
                        $newarr[$v['attr_id']]['options'][$v['id']]['optionsval'] = $formatarr[$v['attr_value']];
                        //$newarr[$v['attr_id']]['options'][$v['id']]['attr_price'] = empty($v['attr_price']) ? 0 : $v['attr_price'];
                        $newarr[$v['attr_id']]['options'][$v['id']]['attr_img'] = empty($v['attr_img']) ? '' : $v['attr_img'];
                    }
                }
            }
        }
        $root['newarr'] = $newarr;//属性
        $root['spec'] = $attr;//规格
        $root['combination'] = json_encode($stock);//属性组合
        $root['combinationnum'] = count($stock);//属性组合种数
        $root['combinationprice'] = json_encode($stocks);//属性组合库存
        $root['combinationpricenum'] = count($stock[0]);//第一个属性组合
        return $root;
    }

    /**
     * 根据属性id获取属性名称
     * @param $attr_ids
     * @return string
     */
    public function goods_to_attrname($attr_ids)
    {
        $where['ga.id'] = array("in", explode("_", $attr_ids));
        $where['g.type'] = "checkbox";
        $list = M('GoodsAttribute')->alias('g')->where($where)->JOIN('LEFT JOIN __GOODS_ATTR__ ga ON ga.attr_id=g.id')->field('ga.attr_value,g.name,g.options')->select();
        $attrname = '';
        foreach ($list as $key => $val) {
            if ($val['options']) {
                $formatarr = strtoarray($val['options']);
                $attrname .= $val['name'] . ":" . $formatarr[$val['attr_value']] . " ";
            }
        }
        return $attrname;
    }

    /**
     * 根据属性id获取属性价格
     * @param $attr_id
     */
    public function getattr_price($attr_id = 0, $goods_id = 0)
    {
        if (empty($goods_id)) {
            return false;
        }
        $goodsattr_info = $ats_map = array();
        $ats_map['goods_id'] = $goods_id;
        $attr_stock = M('GoodsAttrStock')->where($ats_map)->select();
        foreach ($attr_stock as $key => $val) {
            $attr = explode("_", $val['attr_key']);
            $attr = implode(',', $attr);
            $map = array();
            $map['id'] = array("in", $attr);
            $price_info = M('GoodsAttr')->where($map)->Field('attr_price')->select();
            $price = 0;
            foreach ($price_info as $k => $v) {
                $price += $v['attr_price'];
            }
            $goodsattr_info[$val['attr_key']]['price'] = $price;
            $goodsattr_info[$val['attr_key']]['stock'] = $val['stock_cfg'];
        }
        $attr_price = json_encode($goodsattr_info);
        return $attr_price;
    }

    /**
     * 获取属性获取价格
     * @param string $attr商品属性
     * @param $price 价格
     * @return mixed加上属性的价格
     */
    public function get_goods_attrprice($attr = '', $price)
    {
        if ($attr) {
            $attr = explode("_", $attr);
            $attr = implode(',', $attr);
            $map['id'] = array("in", $attr);
            $attr_price = M('GoodsAttr')->where($map)->getField('sum(attr_price)');
        } else {
            $attr_price = 0;
        }
        $total_price = format_decimal($price + $attr_price);
        return $total_price;
    }

    /**
     * 判断商品属性是否有库存
     * @param $attrs 属性组合的字符串
     * @param $goods_id 商品id 必填
     * @param $number 数量 必填
     * @param $cart_type 1直营商品 2订货商品 3外卖商品
     */
    public function check_attr_stock($attrs = '', $goods_id, $number, $name = '',$cart_type=1)
    {
        $root = array();
        $root['status'] = 1;
        $goods_id = intval($goods_id);
        $number = intval($number);
        if (empty($number) && $cart_type==1) {
            $root['status'] = 0;
            $root['msg'] = '商品数量不能为0';
        }
        if (empty($goods_id)) {
            $root['status'] = 0;
            $root['msg'] = '请选择商品';
        }
        $g_map['id'] = $goods_id;
        $goods_info = M("Goods")->where($g_map)->field('goods_number,sell_count,user_max_bought,user_min_bought')->find();
        if ($attrs && $cart_type!=3) {

            $map['goods_id'] = $goods_id;
            $map['attr_key'] = $attrs;
            $attr_info = M("goods_attr_stock")->field(true)->where($map)->find();
            $attrs_stock = $attr_info['stock_cfg'];//本商品库存
            //本商品已售数量（销量）
            $goods_buy_count = $attr_info['sell_count'];
        } elseif(!$attrs && $cart_type!=3) {

            $attrs_stock = $goods_info['goods_number'];
            $goods_buy_count = $goods_info['sell_count'];
        } elseif($cart_type==3) {
           $shop_id=get_wxsmall_shop_id();
            $goods_buy_count = $goods_info['sell_count'];
            $goodsnum = D('Common/Cart')->shopgoodsstock($goods_id,$shop_id,$attrs);
            $attrs_stock = $goodsnum['goods_number'];
        }
        if($cart_type == 2){
            $memberinfo = checkuserauthtype(2);
        }else{
            $memberinfo = checkuserauthtype();
        }
        
        $re_shopping = C('NOT_ADD_CART');//是否允许未登录购买
        if ($attrs) {
            $goodsattr_info = array(
                'key' => $attrs,
                'name' => $name
            );
            $attr_info = serialize($goodsattr_info);
        } else {
            $attr_info = '';
        }
        $cart_map = array();
        if ($re_shopping > 0 && empty($memberinfo) && $cart_type==0) {
            $cart_map['cookie_id'] = cookie('u_cookieid');
        } else {
            if($cart_type==2){
                $cart_map['user_id'] = $memberinfo['shop_id'];
            }else{
                $cart_map['user_id'] = $memberinfo['id'];
            }
            
        }
        $cart_map['goods_id'] = $goods_id;
        $cart_map['goods_attr'] = $attr_info;
        $goods_user_cart_count = M("Cart")->where($cart_map)->sum('goods_num');
        if ($number > $attrs_stock || $attrs_stock <= 0) {
            $root['status'] = 0;
            $root['msg'] = '商品库存不足';
        }
        $goods_user_paid_count = 0;
        if ($memberinfo) {
            //本商品未付款的数量
            $unpaid_map['g.goods_id'] = $goods_id;
            $unpaid_map['g.goods_attr'] = $attr_info;
            $unpaid_map['o.pay_status'] = array('neq', 3);
            $unpaid_map['o.status'] = array('elt', 3);
            $unpaid_map['o.is_delete'] = 0;
            $goods_user_unpaid_count = M('OrderGoods')->alias('g')->where($unpaid_map)->JOIN('LEFT JOIN __ORDER_INFO__ o ON o.id=g.order_id')->sum('g.goods_number');
            // print_r($goods_user_unpaid_count);exit;
            //本商品已付款的数量
            $pay_map['g.goods_id'] = $goods_id;
            $pay_map['g.goods_attr'] = $attr_info;
            $pay_map['o.pay_status'] = 3;
            $pay_map['o.is_delete'] = 0;
            $goods_user_paid_count = M('OrderGoods')->alias('g')->where($pay_map)->JOIN('LEFT JOIN __ORDER_INFO__ o ON o.id=g.order_id')->sum('g.goods_number');

            if ($goods_user_cart_count + $goods_user_unpaid_count + $goods_user_paid_count + $number > $goods_info['user_max_bought'] && $goods_info['user_max_bought'] > 0) {
                $root['status'] = 0;
                $root['msg'] = "已超出商品最大购买量，不能再购买";
                return $root;
            }
            if ($goods_user_cart_count + $goods_user_unpaid_count + $goods_user_paid_count + $number < $goods_info['user_min_bought'] && $goods_info['user_min_bought'] > 0) {
                $root['status'] = 0;
                $root['msg'] = "已低于商品最小购买量，不能再购买";
                return $root;
            }
        }
        return $root;

    }

    /**
     * 根据分类查找属性
     * @param $cate_id
     */
    public function getcate_to_attr($cate_id)
    {
        $map['id'] = $cate_id;
        $goodsattr = M('GoodsCategory')->alias('gc')->field('gc.type_id	,g.type,g.is_img,g.name,g.options,g.id')->where("gc.id=" . $cate_id)->JOIN('LEFT JOIN __GOODS_ATTRIBUTE__ g ON g.type_id=gc.type_id')->order('gc.id')->select();
        $attrlist = array();
        if ($goodsattr) {
            foreach ($goodsattr as $key => $val) {
                $attrlist[$val['id']]['attr'] = $val['name'];
                $attrs_options = strtoarray($val['options']);
                $attrlist[$val['id']]['attr_value'] = $attrs_options;
            }
        }
        return $attrlist;
    }

    /**
     * 商品收藏取消收藏
     * @param $id
     */
    public function collect_goods($id)
    {/*
        $member_info = $this->member_info;
        if (!$member_info) {
            $data['status'] = 1;
            $data['info'] = '你还没有登入，收藏失败！';
            $data['url'] = U('Home/Login');
        } else {
            $model = M("MemberCollect");
            $map['item_id'] = $id;
            $map['type'] = 0;
            $map['uid'] = $member_info['id'];
            $collectinfo = $model->where($map)->count();
            if ($collectinfo) {
                $model->where($map)->delete();
                $data['status'] = 2;
                $data['info'] = '取消收藏成功!';
            } else {
                $postdata['item_id'] = $id;
                $postdata['uid'] = $member_info['id'];
                $postdata['type'] = 0;
                $postdata['addtime'] = NOW_TIME;
                $result = $model->add($postdata);
                if ($result) {
                    $data['status'] = 0;
                    $data['info'] = '收藏成功';
                } else {
                    $data['status'] = 3;
                    $data['info'] = '收藏失败!';
                }
            }
        }
        return $data;*/
    }

    /**
     * 列表页属性
     * @param $param
     * @param $type_id
     * @return mixed
     */
    public function get_attr($param, $type_id)
    {
        $ext = '';
        if (!empty($type_id)) {
            $attribute = get_type_attr($type_id, $param['cat_id'], 1, '0', 5);
            if ($attribute) {
                foreach ($param as $key => $v) {
                    if (in_array($key, $attribute)) {
                        $extarr = get_extension_attr(str_replace('p', '', $key), $v);
                        if ($extarr) $ext .= ' AND ' . trim($extarr);
                    }
                }
            }
            if ($map['_string']) {
                $map['_string'] .= $ext;
            } else if ($ext) {
                $map['_string'] = substr($ext, 5);
            }
            return $map;
        }
    }
	
    /**
     * 根据商品id得到商品属性，商品规格，商品内容(商品详情页用)
     * @param $goods_id 商品id
     */
    public function get_shop_attr($goods_id)
    {
        $root = $stock = $attr = $newarr=$allstocks = array();
        $where['ga.goods_id'] = $map['goods_id'] = $goods_id;
        $stockcount = M('GoodsAttrStock')->where($map)->count();
        if ($stockcount > 0) {
            
            $liststock = M('ShopsGoodsStock')->field('goods_stock,goods_number,sell_count')->where($map)->select();
            if (!empty($liststock)) {
                foreach ($liststock as $k => $v) {//判断商品库存
                    if (empty($v['goods_stock'])) continue;
                    $stock[$k] = explode('_', $v['goods_stock']);
                    $allstocks=$allstocks?array_merge($allstocks,$stock[$k]):$stock[$k];
                    $stocks[$v['goods_stock']]['attr_key'] = $v['goods_stock'];
                    $stocks[$v['goods_stock']]['stock_cfg'] = floatval($v['goods_number']);
                    $stocks[$v['goods_stock']]['sell_count'] = floatval($v['sell_count']);
					
                    $stockmap = array();
                    $stockmap['goods_id'] = $goods_id;
                    $stockmap['attr_key'] = $v['goods_stock'];
                    $attr_price = M('GoodsAttrStock')->where($stockmap)->getField('attr_price');
                    //有会员返回会员价
                    $memberinfo = checkuserauthtype();
                    if($memberinfo){
                        $shop_id=get_wxsmall_shop_id();
                        $min_price=D('Pad/Cashier')->get_min_price($shop_id,$goods_id,$memberinfo,$v['goods_stock']);
                        $stocks[$v['goods_stock']]['attr_price'] = $min_price['goods_price'];
                    }else{
                        $stocks[$v['goods_stock']]['attr_price'] = $attr_price;
                    }

                }
            }
            $list = M('GoodsAttribute')->alias('g')->where($where)->JOIN('LEFT JOIN __GOODS_ATTR__ ga ON ga.attr_id=g.id')->field('ga.*,g.name,g.options,g.type')->select();
            foreach ($list as $k => $v) {
                if ($v['type'] == "text") {
                    $attr[$v['attr_id']]['name'] = $v['name'];
                    if ($v['attr_img']) {
                        $attr[$v['attr_id']]['attr_img'] = $v['attr_img'];
                    }
                    // $attr[$v['attr_id']]['price'] = $v['attr_price'];
                    $attr[$v['attr_id']]['attr_value'] = $v['attr_value'];
                } else {
                    if(in_array($v['id'],$allstocks)){
                        $formatarr = array();
                        $newarr[$v['attr_id']]['name'] = $v['name'];
                        $newarr[$v['attr_id']]['options'][$v['id']]['id'] = $v['id'];
                        $formatarr = strtoarray($v['options']);
                        $newarr[$v['attr_id']]['options'][$v['id']]['optionsval'] = $formatarr[$v['attr_value']];
                        // $newarr[$v['attr_id']]['options'][$v['id']]['attr_price'] = empty($v['attr_price']) ? 0 : $v['attr_price'];
                        $newarr[$v['attr_id']]['options'][$v['id']]['attr_img'] = empty($v['attr_img']) ? '' : $v['attr_img'];
                    }
                }
            }
        }
        $root['newarr'] = $newarr;//属性
        $root['spec'] = $attr;//规格
        $stock = array_values($stock);
        $root['combination'] = json_encode($stock);//属性组合
        $root['combinationnum'] = count($stock);//属性组合种数
        $root['combinationprice'] = json_encode($stocks);//属性组合库存
        $root['combinationpricenum'] = count($stock[0]);//第一个属性组合
        return $root;
    }
	/**
     * 根据商品id得到商品属性，商品规格，商品内容(商品详情页用)
     * @param $goods_id 商品id
     */
    public function get_change_attr($goods_id)
    {
        $root = $stock = $attr = $newarr = array();
        $where['ga.goods_id'] = $map['goods_id'] = $goods_id;
        $stockcount = M('GoodsAttrStock')->where($map)->count();
        if ($stockcount > 0) {
            $list = M('GoodsAttribute')->alias('g')->where($where)->JOIN('LEFT JOIN __GOODS_ATTR__ ga ON ga.attr_id=g.id')->field('ga.*,g.name,g.options,g.type')->select();
            foreach ($list as $k => $v) {
                if ($v['type'] == "text") {
                    $attr[$v['attr_id']]['name'] = $v['name'];
                    if ($v['attr_img']) {
                        $attr[$v['attr_id']]['attr_img'] = $v['attr_img'];
                    }
                    // $attr[$v['attr_id']]['price'] = $v['attr_price'];
                    $attr[$v['attr_id']]['attr_value'] = $v['attr_value'];
                } else {
                    $formatarr = array();
                    $newarr[$v['attr_id']]['name'] = $v['name'];
                    $newarr[$v['attr_id']]['options'][$v['id']]['id'] = $v['id'];
                    $formatarr = strtoarray($v['options']);
                    $newarr[$v['attr_id']]['options'][$v['id']]['optionsval'] = $formatarr[$v['attr_value']];
                    // $newarr[$v['attr_id']]['options'][$v['id']]['attr_price'] = empty($v['attr_price']) ? 0 : $v['attr_price'];
                    $newarr[$v['attr_id']]['options'][$v['id']]['attr_img'] = empty($v['attr_img']) ? '' : $v['attr_img'];
                }
            }
            $liststock = M('ShopsGoodsStock')->field('goods_stock,goods_number,sell_count')->where($map)->select();
            if (!empty($liststock)) {
                foreach ($liststock as $k => $v) {//判断商品库存
                    if (empty($v['goods_stock'])) contiue;
                    $stock[$k] = explode('_', $v['goods_stock']);
                    // $stockmap['id'] = array('in', $stock[$k]);
                    // $attr_price = M('GoodsAttr')->where($stockmap)->sum('attr_price');
                    $stocks[$v['goods_stock']]['attr_key'] = $v['goods_stock'];
					$stockmap = array();
					$stockmap['goods_id'] = $goods_id;
					$stockmap['attr_key'] = $v['goods_stock'];
                    $attr_price = M('GoodsAttrStock')->where($stockmap)->getField('attr_price');
                    $stocks[$v['goods_stock']]['stock_cfg'] = floatval($v['goods_number']);
                    $stocks[$v['goods_stock']]['sell_count'] = floatval($v['sell_count']);
                    $stocks[$v['goods_stock']]['attr_price'] = $attr_price;
                }
            }
        }
		
        $root['newarr'] = $newarr;//属性
        $root['spec'] = $attr;//规格
        $root['combination'] = json_encode($stock);//属性组合
        $root['combinationnum'] = count($stock);//属性组合种数
        $root['combinationprice'] = json_encode($stocks);//属性组合库存
        $root['combinationpricenum'] = count($stock[0]);//第一个属性组合
        return $root;
    }
}
?>