<?php
/**
 * 权限规则模型
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
 
namespace Shop\Model;
use Think\Model;
class GoodsModel extends Model
{
    protected $_auto = array(
        array('promote_start_date', 'strtotime', self::MODEL_BOTH, 'function'),
        array('promote_end_date', 'strtotime', self::MODEL_BOTH, 'function'),
    );//更新商品属性

    public function update_goodstype($postdata, $type = 0)
    {
        $goodstypearr = $newgoodsattr = $check_unique_array = array();
        if ($postdata['config']) {
            $a = 0;
            foreach ($postdata['config'] as $k => $v) {
                if (str_exists($k, '_') || !$v) continue;
                if (!empty($v[$k . '_text'])) {
                    if (!in_array($postdata['id'] . $k . $v[$k . '_text'], $check_unique_array)) {
                        $newgoodsattr[$a]['goods_id'] = !empty($postdata['id']) ? $postdata['id'] : 0;
                        $newgoodsattr[$a]['attr_id'] = !empty($k) ? $k : 0;
                        $newgoodsattr[$a]['attr_value'] = $v[$k . '_text'];
                        $newgoodsattr[$a]['attr_price'] = 0;
                        $newgoodsattr[$a]['supplier_price'] = 0;
                        $newgoodsattr[$a]['attr_img'] = '';
                        $check_unique_array[] = $postdata['id'] . $k . $v[$k . '_text'];
                        $goodstypearr[] = $v[$k . '_text'] . "0";
                        ++$a;
                    }

                } elseif (!empty($v[$k . '_select'])) {
                    foreach ($v[$k . '_select'] as $x => $y) {
                        if (!in_array($postdata['id'] . $k . $v[$k . '_select'][$x], $check_unique_array) && is_numeric($v[$k . '_select'][$x])) {
                            $newgoodsattr[$a]['goods_id'] = !empty($postdata['id']) ? $postdata['id'] : 0;
                            $newgoodsattr[$a]['attr_id'] = !empty($k) ? $k : 0;
                            $newgoodsattr[$a]['attr_value'] = $v[$k . '_select'][$x];
                            $newgoodsattr[$a]['attr_price'] = floatval($v[$k . '_price'][$x]);
                            $newgoodsattr[$a]['supplier_price'] = floatval($v[$k . '_balance_price'][$x]);
                            $newgoodsattr[$a]['attr_img'] = !empty($v[$k . '_img'][$x]) ? $v[$k . '_img'][$x] : '';
                            $check_unique_array[] = $postdata['id'] . $k . $v[$k . '_select'][$x];
                            $goodstypearr[] = $newgoodsattr[$a]['attr_value'] . $newgoodsattr[$a]['attr_price'] . $newgoodsattr[$a]['attr_img'];
                            ++$a;
                        }
                    }
                }
            }
            if ($postdata['configstr'] != md5(implode('', $goodstypearr)) || $type) {
                $goodsattrmod = M('GoodsAttr');
                if (empty($type)) {
                    M('GoodsAttrStock')->where('goods_id=' . $postdata['id'])->delete();//属性发生变化，删除所有对应货品属性
                    $goodsattrmod->where('goods_id=' . $postdata['id'])->delete();//print_r($newgoodsattr);exit;
                }
                if ($newgoodsattr) {
                    $goodsattrmod->addAll($newgoodsattr);/*foreach($newgoodsattr as $v){$goodsattrmod->add($v);}*/
                }
            }
        }
        unset($goodstypearr, $newgoodsattr, $postdata);
    }

    /**
     * 更新扩增分类
     * @param array $postdata 表单提交数据
     * @param int $type 提交的类型:0修改,1添加
     */
    public function update_goodsattr($postdata, $type = 0)
    {
        $newgoodscat = array();
        if (($postdata['more_cat'] && $postdata['morecatid'] != implode(',', $postdata['more_cat'])) || ($type && $postdata['more_cat'])) {
            $goodscatmod = M('GoodsCat');
            if (empty($type)) $goodscatmod->where('goods_id=' . $postdata['id'])->delete();
            foreach ($postdata['more_cat'] as $v) {
                if (!$v) continue;
                $newgoodscat[] = array('goods_id' => $postdata['id'], 'catid' => $v);
            }
            if ($newgoodscat) $goodscatmod->addAll($newgoodscat);
        }
        unset($newgoodscat, $postdata);
    }

    /**
     * 更新商品相册
     * @param array $postdata 表单提交数据
     * @param int $type 提交的类型:0修改,1添加
     */
    public function update_goodsimg($postdata, $type = 0)
    {
        $newgoodsimg = array();
        $moreimgstr = md5(implode('', $postdata['goods_img']) . implode('', $postdata['img_desc']) . implode('', $postdata['img_del']));
        if (($postdata['goods_img'] && $postdata['moreimgstr'] != $moreimgstr) || ($type && $postdata['goods_img'])) {
            $goodsimgmod = M('GoodsGallery');
            if (empty($type)) $goodsimgmod->where('goods_id=' . $postdata['id'])->delete();
            foreach ($postdata['goods_img'] as $k => $v) {
                if (!$v || $postdata['img_del'][$k]) continue;
                $newgoodsimg[] = array('goods_id' => $postdata['id'], 'goods_img' => $v, 'img_desc' => $postdata['img_desc'][$k]);
            }
            if ($newgoodsimg) $goodsimgmod->addAll($newgoodsimg);
        }
        unset($newgoodsimg, $postdata);
    }

    /**
     * 更新会员价
     * @param array $postdata 表单提交数据
     * @param int $type 提交的类型:0修改,1添加
     */
    public function update_user_price($postdata, $type = 0)
    {
        $user_price = $postdata['user_price'];
        $arr = array();
        if (!empty($user_price)) {
            $member_price = M('member_price');
            $member_price->where('goods_id=' . $postdata['id'])->delete();
            foreach ($user_price as $key => $value) {
                if ($value != -1) {
                    $arr['goods_id'] = $postdata['id'];
                    $arr['user_rank'] = $key;
                    $arr['user_price'] = $value;
                    $member_price = M('member_price');
                    $member_price->add($arr);
                }
            }
        }
        unset($arr, $postdata);
    }

    /**
     * 更新货号
     * @param array $postdata 表单提交数据
     * @param int $type 提交的类型:0修改,1添加
     */
    public function update_goods_sn($postdata, $type = 0)
    {
        $goods_sn = array();
        if (empty($postdata['goods_sn'])) {
            $sn_prefix=C("GOODS_NUM_PREFIX");
            $num_sn = str_pad($postdata['id'], 7, 000, STR_PAD_LEFT);
            $goods_sn['goods_sn'] = $sn_prefix . $num_sn;
            M('goods')->where('id=' . $postdata['id'])->save($goods_sn);
        }
        unset($goods_sn, $postdata);
    }

    /**
     * 更新商品详情和seo
     * @param array $postdata 表单提交数据
     * @param int $type 提交的类型:0修改,1添加
     * @param int $is_base 是否提交的基本信息:0否,1是
     */
    public function update_goods_content($postdata, $type = 0, $is_base = 0)
    {
        $save = $where = array();
        $save['goods_id'] = $postdata['id'];
        if($is_base==1) {
            $save['content'] = $postdata['content'];
        }else {
            $save['seotitle'] = $postdata['seotitle'];
            $save['seokeywords'] = $postdata['seokeywords'];
            $save['seodescription'] = $postdata['seodescription'];
        }
        $where['goods_id'] = $postdata['id'];
        $goodscontent = M('GoodsContent')->where('goods_id = ' . $postdata['id'])->find();
        if (empty($goodscontent)) {
            M('GoodsContent')->add($save);
        } else {
            M('GoodsContent')->where($where)->save($save);
        }
        unset($where, $save, $postdata);
    }

    //更新商品属性库存,货品编号
    public function update_goodsattr_stock($postdata)
    {
        $newgoodsattr = $check_unique_array = array();
        if ($postdata['config']) {
            foreach ($postdata['config'] as $k => $v) {
                if (!in_array("select", array_keys($postdata['config']))) continue;//必须有属性组合
                if ($k == "select") {//属性选择
                    foreach ($v as $selectkey => $selectval) {
                        $attr_key_array = array();
                        foreach ($selectval as $key => $val) {
                            $where['goods_id'] = $postdata['id'];
                            $where['attr_id'] = $key;
                            $where['attr_value'] = $val;
                            if (!is_numeric($val)) continue;
                            $attr_key_array[] = M('GoodsAttr')->where($where)->getField('id');
                        }
                        if (count($attr_key_array) != count($selectval)) continue;//属性选择不全，不存入数据库
                        sort($attr_key_array);
                        $select_attr_key = implode('_', $attr_key_array);
                        if (in_array($select_attr_key, $check_unique_array)) continue;
                        $newgoodsattr[$selectkey]['goods_id'] = $postdata['id'];
                        $newgoodsattr[$selectkey]['attr_key'] = $select_attr_key;
                        $check_unique_array[] = $select_attr_key;
                    }
                }
                if (!empty($select_attr_key)) {
                    if ($k == "goods_attr_sn") {//属性货号
                        foreach ($v as $selectkey => $selectval) {
                            $newgoodsattr[$selectkey]['goods_attr_sn'] = !empty($selectval) ? $selectval : '';
                            $check_goods_attr_sn[] = !empty($selectval) ? $selectval : '';
                        }
                    }
                    if ($k == "stock_cfg") {//属性库存
                        foreach ($v as $selectkey => $selectval) {
                            $newgoodsattr[$selectkey]['stock_cfg'] = !empty($selectval) ? $selectval : 0;
                        }
                    }
                    if ($k == "sell_count") {//销售量
                        foreach ($v as $selectkey => $selectval) {
                            $newgoodsattr[$selectkey]['sell_count'] = !empty($selectval) ? $selectval : 0;
                        }
                    }
                    if($k=='attr_price'){//价格
                        foreach ($v as $selectkey => $selectval) {
                            $newgoodsattr[$selectkey]['attr_price'] = !empty($selectval) ? $selectval : 0;
                        }
                    }
                }


            }
            $map['goods_attr_sn'] = array('in', implode(',', $check_goods_attr_sn));
            $map['goods_id'] = array('neq', $postdata['id']);
            $goodsattrmod = M('GoodsAttrStock');
            $check_goods_attr_sn_count = $goodsattrmod->where($map)->count();
            if ($check_goods_attr_sn_count > 0) {
                return false;
            }
            $goodsattrmod->where('goods_id=' . $postdata['id'])->delete();//print_r($newgoodsattr);exit;
            foreach ($newgoodsattr as $v) {
                $goodsattrmod->add($v);
            }
        }
        unset($goodstypearr, $newgoodsattr, $postdata);
        return true;
    }

    /**
     * 商品关于列表页的筛选条件
     * @param array $postdata
     * @return array
     */
    public function index_condition($postdata = array())
    {
        $map = array();
        if(!isset($postdata['keyword'])){
            $postdata['keyword']='';
        }
        if (is_numeric($postdata['keyword'])) {
            $map['id|goods_name'] = array(intval($postdata['keyword']), array('like', '%' . $postdata['keyword'] . '%'), '_multi' => true);
        } else if (!empty($postdata['keyword'])) {
            $map['goods_sn|goods_name'] = array('like', '%' . (string)$postdata['keyword'] . '%');
        }
        if (!empty($postdata['catid'])) {
            $cat_sons = get_children($postdata['catid'], 1);
            $catstr = implode(',', $cat_sons);
            $extension_goods_id = get_extension_goods($postdata['catid'], 1);
            $extensionstr = implode(',', $extension_goods_id);
            $where = array();
            if (!empty($cat_sons) && !empty($catstr)) {
                $where['cat_id'] = array('in', $cat_sons);
            }
            if (!empty($extension_goods_id) && !empty($extensionstr)) {
                $where['id'] = array('in', $extension_goods_id);
            }
            if (!empty($where)) {
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
            }
        }
        if (!empty($postdata['suppliersid'])) {
            $map['suppliers_id'] = $postdata['suppliersid'];
        }
        if (!empty($postdata['brandid'])) {
            $map['brand_id'] = $postdata['brandid'];
        }
        if (isset($postdata['shops_keyword'])) {
            if(!empty($postdata['shops_keyword'])) {
                $shop_ids = array();
                if (is_numeric($postdata['shops_keyword'])) {
                    $shop_map['id|name'] = array(intval($postdata['shops_keyword']), array('like', '%' . $postdata['shops_keyword'] . '%'), '_multi' => true);
                } else if (!empty($postdata['shops_keyword'])) {
                    $shop_map['name'] = array('like', '%' . (string)$postdata['shops_keyword'] . '%');
                }
                $shops = M('Shops')->field('id')->where($shop_map)->select();
                foreach ($shops as $k => $v) {
                    $shop_ids[$k] = $v['id'];
                }
                if (empty($shop_ids)) {
                    $map['shop_id'] = array('lt', 0);
                } else {
                    $map['shop_id'] = array('in', $shop_ids);
                }
            }else{
                $map['shop_id'] = array('gt', 0);
            }
        } else {
            $map['shop_id'] = 0;
        }
        $map['is_delete'] = !empty($postdata['is_delete'])?$postdata['is_delete']:0;
        if(!isset($postdata['publish_wait'])){
            $postdata['publish_wait']='';
        }
        $map['publish_wait'] = $postdata['publish_wait'];
        return $map;
    }

    /**
     * 更新商品标签
     * @param array $postdata 表单提交数据
     * @param int $type 提交的类型:0修改,1添加
     */
    public function update_goods_label($postdata, $type = 0)
    {
        $id = $postdata['id'];
        $goods_label = $postdata['goods_label'];
        $selectstr = implode(',', $postdata['goods_label']);
        if ($type == 0 && !empty($goods_label) && $selectstr != $postdata['selectstr']) {
            $map['goods_id'] = $id;
            M('ProjectLabelLink')->where($map)->delete();
            foreach ($goods_label as $k => $v) {
                $map['label_id'] = $v;
                M('ProjectLabelLink')->add($map);
            }
        } elseif ($type == 1) {
            $data['goods_id'] = $id;
            foreach ($goods_label as $k => $v) {
                $data['label_id'] = $v;
                M('ProjectLabelLink')->add($data);
            }
        }
        unset($goods_label, $map, $data);
    }
	/**
	 * 删除属性
	 * @param $postdata mixed
	 * @return  mixed  
	*/
    public function del_attr($postdata){
		$return=array('status'=>0,'info'=>'');
		
		$ids=$postdata['check_id'];
		if(!$ids){$return['info']='请选择要删除的选项';return $return;}
		
		//检查属性是否使用
		$map_atr['attr_id']=array('in',$ids);
		$have=M('GoodsAttr')->where($map_atr)->count();
		if($have && is_array($ids)){
			$return['info']='有商品正在使用的属性，暂不能全部删除';return $return;
		}elseif($have && !is_array($ids)){
			$return['info']='此属性已被使用，暂不能删除';return $return;
		}
		
		$map['id']=array('in',$ids);
		$res=M('GoodsAttribute')->where($map)->delete();
		if($res){
			$return['status']=1;
			$return['info']='删除成功';
		}else{
			$return['info']='删除失败';
		}
		return $return;
    }
}