<?php
/**
 * 店铺中心
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaol <1094186793@qq.com>
 */
namespace Shop\Controller;
use Think\Controller;
class GoodsController extends BaseController {
    public function _initialize(){
        parent::_initialize();
        $shops_info=session('shops_info');
        if(empty($shops_info['id'])) $this->error('身份过期，请重新登录',U('Shop/Register/shop_login'));
        $this->mendian();
        $this->inputtype = array('text' => L('TEXT'), 'checkbox' => L('REDIO'));
        $this->assign('inputtype', $this->inputtype);
        $this->assign('if_publish_wait',C('IS_OPEN_GOODS_SHOW')?C('IS_OPEN_GOODS_SHOW'):0);
        // 1117 ggw 
        $suc=D('Shops')->shop_option(MID,'goods');
        if(!$suc){$this->error('该店铺没有此权限，请联系管理员授权！');die;}

    }

    /**
     * 商品列表
     */
    public function index(){
        $auth_code = 'goodslist_info';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);}

        $this->assign('publish_wait_array',array('1'=>'待审核','2'=>'已审核','3'=>'不通过'));
        $this->assign('is_type_array',array('1'=>'普通商品','2'=>'计重商品'));
        $shops_info=session('shops_info');
        $postdata = I('param.');
        $postdata['is_delete'] = 0;
        // $postdata['publish_wait'] = 1;
        $keyword = $postdata['keyword'];
        $tabid = I('param.tabid');
        if (!empty($tabid)) 
            $this->display($tabid);
        else{
            $map=$g_map=$whereor=$g_ids=$cat_ids=array();
            
               if($keyword){
                    $whereor['goods_sn'] = array('like', '%' . $keyword . '%');
                    $whereor['goods_name'] = array('like', '%' . $keyword . '%');
                    $whereor['_logic'] = 'or';
                    $map['_complex'] = $whereor;
                }
                if($postdata['catid']){
                    GLOBAL $PurchaseCategory;
                    if(empty($PurchaseCategory))$PurchaseCategory = getcache('PurchaseCategory');
                    $cat_ids = $PurchaseCategory[$postdata['catid']]['allson'];
                    if($cat_ids){
                        $map['cat_id'] = array('in',$cat_ids);
                    }
                }
                if($postdata['suppliersid']){
                    $map['suppliers_id'] = $postdata['suppliersid'];
                }
                $map['is_delete']=0;
                // $map['publish_wait']=1;
                if($postdata['publish_wait']) $map['publish_wait']=$postdata['publish_wait']-1;
                if($postdata['is_type']){$map['is_type']=$postdata['is_type']-1;}
                
                $map['goods_type'] = array('eq','5,2');//商品 赠品
              // 1130
                // $map['_string']="shop_id =0 or shop_id =".MID;
           
                $shop_type=idtoname(MID,'Shops','shop_type');

                if($shop_type==1){
                    $map['_string']="shop_id =0 or shop_id =".MID;//兼容
                }else{
                    $map['_string']="shop_id =".MID;
                }
            // 1130

             if($postdata['print']=='print'){$list=M('Goods')->where($map)->field(true)->select();}
             else{$list=$this->lists('Goods',$map,'id desc','','',20);}
            //从shoopgoods表里查出自己店下的  进行货品预警操作
            $shop_where['shop_id']=MID;
            $shop_where['is_delete']=0;
            $shop_data=M('ShopsGoods')->where($shop_where)->getField('goods_id,qh_count,id,is_hot,status');
            foreach($list as $k=>$v){
                if($shop_data[$v['id']]){
                    $list[$k]['shop_goods_id']=$shop_data[$v['id']]['id'];
                    if($postdata['print']=='print')$list[$k]['self']=1;
                }
            }
            if($postdata['print']=='print')$this->export_goods($list,1);
            $this->getcateTree($postdata['catid'], '', $postdata['brandid'], $postdata['suppliersid'],'',5);
            $this->assign('list', $list);
            $this->assign($postdata);
            $this->assign('title_ass','商品');
            $this->display();
        }
    }
    public function export_goods($list,$is_index=0){

        $title = array('ID', '商品编号', '商品名称', '供货商','分类','商品类型', '价格', '预警上限/下限');
        $data = array();
        foreach ($list as $k => $v) {
            if($is_index){

                $data[$k][] = $v['id'];
                $data[$k][] = "'".$v['goods_sn'];
                $data[$k][] = $v['goods_name'];
                $data[$k][] = idtoname($v['suppliers_id'], 'Suppliers');
                $data[$k][] = idtoname($v['cat_id'], 'GoodsCategory');
                $data[$k][] = $v['market_price'];
                $data[$k][] = $v['limit_count'].'/'.$v['lower_count'];
            }else{
                $arr=idtoname($v['goods_id'],'Goods','goods_name,cat_id,market_price,is_type');
                 $data[$k][] = $v['id'];
                $data[$k][] = "'".$v['goods_sn'];
                $data[$k][] = $arr['goods_name'];
                $data[$k][] = idtoname($v['suppliers_id'], 'Suppliers');
                $data[$k][] = idtoname($arr['cat_id'],'PurchaseCategory');
                $data[$k][] = $arr['is_type']==1?'计重商品':'普通商品';
                $data[$k][] = $arr['market_price'];
                $data[$k][] = $v['limit_count'].'/'.$v['lower_count'];
                unset($arr);
            }

        }
        export_xls($title, $data, 'utf8');
        unset($title, $data);
        exit;

    }


    // 旧版列表页
    public function old_index(){
        $this->assign('publish_wait_array',array('1'=>'待审核','2'=>'已审核','3'=>'不通过'));
        $this->assign('is_type_array',array('1'=>'普通商品','2'=>'计重商品'));
        $shops_info=session('shops_info');
        $postdata = I('param.');
        $postdata['is_delete'] = 0;
        // $postdata['publish_wait'] = 1;
        $keyword = $postdata['keyword'];
        $tabid = I('param.tabid');
        if (!empty($tabid)) 
            $this->display($tabid);
        else{
            $shop_id = intval($shops_info['shop_id']);
            $map=$g_map=$whereor=$g_ids=$cat_ids=array();
            if($keyword){
                $whereor['goods_sn'] = array('like', '%' . $keyword . '%');
                $whereor['goods_name'] = array('like', '%' . $keyword . '%');
                $whereor['_logic'] = 'or';
                $g_map['_complex'] = $whereor;
            }
            if($postdata['catid']){
                GLOBAL $PurchaseCategory;
                if(empty($PurchaseCategory))$PurchaseCategory = getcache('PurchaseCategory');
                $cat_ids = $PurchaseCategory[$postdata['catid']]['allson'];
                if($cat_ids){
                    $g_map['cat_id'] = array('in',$cat_ids);
                }
            }
             if($postdata['publish_wait']) $g_map['publish_wait']=$postdata['publish_wait']-1;
            if($postdata['is_type']){$g_map['is_type']=$postdata['is_type']-1;}

            $g_map['goods_type'] = 5;
            $g_ids = M('Goods')->where($g_map)->getField('id',true);
            if($g_ids){
                $map['goods_id'] = array('in',$g_ids);
            }else{
                $list = '';
                $this->error('该分类下没有对应商品');
                
                $this->assign('list', $list);
                $this->display();
            }
            
            if($postdata['suppliersid']){
                $map['suppliers_id'] = $postdata['suppliersid'];
            }
            $map['shop_id'] = $shop_id;
            if($postdata['print']=='print'){$list=M('ShopsGoods')->where($map)->field(true)->select();}
            else $list = $this->lists('ShopsGoods', $map,'','','',20);
             // 自己的商品id
            $self_ids=M('Goods')->where('shop_id='.MID)->getField('id',true);
            foreach($list as $k=>$v){
                if(in_array($v['goods_id'],$self_ids))$list[$k]['self']=1;
                $arr=idtoname($v['goods_id'],'Goods','is_type,publish_wait');
                $list[$k]['publish_wait']=$arr['publish_wait'];
                $list[$k]['is_type']=$arr['is_type'];
            }
             if($postdata['print']=='print')$this->export_goods($list);
            $this->getcateTree($postdata['catid'], '', $postdata['brandid'], $postdata['suppliersid'],'',5);
            $this->assign('list', $list);
            $this->assign($postdata);
            $this->assign('title_ass','商品');
            $this->display();
        }
    }
    /**
     * 货品管理
     */
    public function stock(){   
        $shops_info=session('shops_info');
        $postdata = I('param.');
        if(!$postdata)
         $this->error('参数错误！');
        
        $goods_id = intval($postdata['goods_id']);
        $shop_id = intval($shops_info['shop_id']);
        $stock_map['goods_id'] = $goods_id;
        $stock_map['shop_id'] = $shop_id;
        $yj_count=idtoname($shop_id,'Goods','limit_count,lower_count');
        $goods_huopin=D('Shop/GoodsAttrStock')->liststock($goods_id,$shop_id,'-1');
        if($goods_huopin['status']==1){//有货品 需要前台选择
            foreach($goods_huopin['data'] as $key => $vo){
                $goods_attr=attr_key2name($vo['goods_stock'],$vo['goods_id']);
                $goods_huopin['data'][$key]['goods_attr']=$goods_attr;
                $goods_huopin['data'][$key]['qh_count']=$yj_count['limit_count'].'/'.$yj_count['lower_count'];//$vo['qh_count'];1109
            }
        }elseif($goods_huopin['status']==2){
            $goods_huopin['data'][0]['goods_attr'] = idtoname($goods_id,'Goods','goods_name');
            $goods_huopin['data'][0]['goods_number'] = M('ShopsGoodsStock')->where($stock_map)->getField('goods_number');
            $goods_huopin['data'][0]['qh_count']=$yj_count['limit_count'].'/'.$yj_count['lower_count'];//1109 M('ShopsGoodsStock')->where($stock_map)->getField('qh_count');
        }elseif($goods_huopin['status']==3){
            $stock_info=$goods_huopin['data'][0];
            $stock_id=$stock_info['goods_stock'];
            $goods_huopin['data'][0]['goods_attr']=attr_key2name($stock_id,$stock_info['goods_id']);
            $goods_huopin['data'][0]['qh_count']=$yj_count['limit_count'].'/'.$yj_count['lower_count'];//1109 $stock_info['qh_count'];
        }
        // print_r($goods_huopin['data']);exit;
        foreach($goods_huopin['data'] as $k=>$v ){
            $sgmap['goods_id']=$v['goods_id'];
            $sgmap['attr_key']=$v['goods_stock'];
            $goods_huopin['data'][$k]['goods_attr_sn']=M('GoodsAttrStock')->where($sgmap)->getField('goods_attr_sn');

        }
        $this->assign('stock', $goods_huopin['data']);
        $this->assign('id',$goods_id);
        $this->assign('menu_action','index');
        $this->assign('tplseo_title','门店货品_'.C('WEB_SITE_TITLE'));
        $this->assign('title_ass','货品');
        $this->display();
    }

    /**
     * shops_goods表外卖商品上下架
     */
    public function status(){
        $model = D('Goods');
        $id     = intval(I('id'));
        $type   = I('type');
        
        $values = $model->where('id='.$id)->field($type)->find();
        $data[$type]=($values[$type]+1)%2;
        $res=$model->where('id='.$id)->save($data);
        $this->ajaxReturn($data[$type]);
    }
    /**
     * shops_goods_stock表货品上下架
     */
    public function stock_status(){
        $model = D('ShopsGoodsStock');
        $id     = intval(I('id'));
        $type   = I('type');
        
        $values = $model->where('id='.$id)->field($type)->find();
        $data[$type]=($values[$type]+1)%2;
        $res=$model->where('id='.$id)->save($data);
        $this->ajaxReturn($data[$type]);
    }
    
    /**
     * 回收站的商品
     */
    public function recycle(){
        $tabid = I('param.tabid');
        if (!empty($tabid)) 
            $this->display($tabid);
        else {
            $postdata = I('param.');
            $postdata['is_delete'] = 1;
            $postdata['shop_id'] = MID;
            $list = $this->get_shop_goods_list($postdata);
            $this->assign('list', $list);
            $this->assign($postdata);
            $this->display();
        }
    }
    private function get_shop_goods_list($postdata){
        $name = CONTROLLER_NAME;
        $map = D('Admin/Goods')->index_condition($postdata);
        if (!isset($postdata['catid'])) {
            $postdata['catid'] = 0;
        }
        if (!isset($postdata['brandid'])) {
            $postdata['brandid'] = 0;
        }
        if (!isset($postdata['suppliersid'])) {
            $postdata['suppliersid'] = 0;
        }
        if($postdata['goodstype']){
            $map['goods_type'] = $postdata['goodstype'];
        }
        $this->getcateTree($postdata['catid'], '', $postdata['brandid'], $postdata['suppliersid']);
        $return = $this->lists($name, $map);
        return $return;
    }
    /**
     * 删除，回收站
     * @param $is_delete 0恢复,1删除
     */
    public function recycling(){
        $auth_code = 'goodslist_del';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);exit;}

        $name = 'Goods';
        $postdata = I('post.');
        $id = I('get.id');
        if (empty($postdata['id']) && !empty($id)) $postdata['id'][] = $id;
        $is_delete = I('is_delete');
        if (empty($postdata['id'])) {
            if ($is_delete == 1) $this->error('请选择要删除的商品！');
            else $this->error('请选择要恢复的商品！');
        }
        $where['is_delete'] = $is_delete;
        foreach ($postdata['id'] as $key => $value) {
            $map['id'] = $value;
            $g_info = M($name)->where($map)->save($where);
        }
        if ($is_delete == 1) {
            if (isset($g_info)) {
                $this->success('已成功放入回收站');
            } else {
                $this->error('删除失败');
            }
        } else {
            if (isset($g_info)) {
                $this->success('恢复成功');
            } else {
                $this->error('恢复失败');
            }
        }
    }
    /**
     * 编辑缺货预警值
     */
    public function edit_quehuo(){
        $return['status'] = 0;$return['info'] = '编辑失败';
        $goods_id = I('post.goods_id');
        $map['goods_id'] = $goods_id;
        $map['shop_id'] = MID;
        $goods = M('ShopsGoods')->where($map)->field(true)->find();
        $qh_num = I('post.qh_num');
        if($goods && $goods_id && $qh_num){
            $save['qh_count'] = $qh_num;
            $ret = M('ShopsGoods')->where($map)->save($save);
            $res = M('ShopsGoodsStock')->where($map)->save($save);
            if($ret && $res){
                $return['status'] = 1;
                $return['info'] = '编辑成功';
            }
        }
        $this->ajaxReturn($return);
    }

    /**
     * 添加商品
     */
    public function add(){
        $tab_id=I('param.tabid');
        $tab_id=empty($tab_id)?'baseinfo':$tab_id;
        if($tab_id=='baseinfo'){
            $this->getNodeTree();
            $basedefault = array('moreimg' => '', 'moreimgstr' => '', 'morecatarr' => '', 'morecatid' => '', 'configstr' => '');
            $this->assign($basedefault);
            $this->get_member_price();//会员价
        }
        $postdata['publish_wait'] = 0;
        $postdata['shop_id']=MID;
        $this->assign($postdata);
        $this->assign('menu_tab',$tab_id);
        $this->assign('menu_action_current','index');
        $this->display($tab_id);
    }

    /**
     * 资料更新
     */
    public function data_edit(){
        $id = I('get.id');
        if (!$id) $this->error(L('PARAM_ERR'));
        $info = M('Goods')->field(true)->find($id);
        $this->assign('info',$info);
        $this->assign('menu_action','add');
        $this->assign('menu_tab','baseinfo');
        $this->assign('menu_action_current','index');
        $this->display();
    }
    
    /**
     * 更新资料
     */
    public function data_update(){
        $model = D('Admin/Goods');
        $postdata = I('post.');
        $id = array_unique((array)I('id', 0));
        $id = is_array($id) ? implode(',', $id) : $id;
        $where = array_merge(array('id' => array('in', $id)), (array)$where);
        $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        if (D('Goods')->where($where)->save($postdata) !== false) {
            clearhomehtml($id);//更新静态缓存
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
    }
    

    /**
     * 得到会员价
     * @param int $id
     */
    public function get_member_price($id=0){
        //会员
        $morerank = M('MemberRank')->field('id,name')->select();
        //会员价
        if(!empty($id))$user_price = M('MemberPrice')->where('goods_id = ' . $id)->select();
        $member_price = array();
        foreach ($morerank as $k => $v) {
            $member_price[$k]['id'] = $morerank[$k]['id'];
            $member_price[$k]['name'] = $morerank[$k]['name'];
            if(!empty($user_price[$k]['user_price']))$member_price[$k]['user_price'] = $user_price[$k]['user_price'];
        }
        $this->assign('member_price', $member_price);
        $this->assign('morerank', $morerank);
    }


    /**
     * 得到树节点
     * @param string $pid
     */
    private function getNodeTree($pid = '', $assign = '', $brandid = '', $suppliersid = '',$shop_cat_id='',$goods_type=1)
    {
        if (empty($pid))$pid = I('pid');
        $this->getcateTree($pid, $assign, $brandid, $suppliersid,$shop_cat_id，,$goods_type);
        //获取所有供货商
        $smap['status']=array('gt',0);
        $smap['shop_id']=MID;
        $suppliersattr = M('Suppliers')->where($smap)->field('id,name')->cache(true)->order('id desc')->select();
        $supplierattr = array();
        if (!empty($suppliersattr)) {
            foreach ($suppliersattr as $v) {
                $supplierattr[$v['id']] = $v['name'];
            }
        }
        $this->assign('suppliers', $supplierattr);
        unset($suppliersattr, $supplierattr);
    }
    
    
    
    
    /**
     * 得到节点树
     */
    private function getcateTree($pid = '', $assign = '', $brandid = '', $suppliersid = '',$shop_id='',$goods_type)
    {
        if($goods_type==5){
            $GoodsCategory = getcache('PurchaseCategory');
        }else{
            $GoodsCategory = getcache('GoodsCategory');
        }
        $shopid=idtoname($shop_id,"Goods",'shop_id');

        $Tree = new \Common\Vendor\Tree();
        $select_categorys = '';
        $treemini = $Tree->treemini($GoodsCategory);
        $select_categorys .= $Tree->treeminioption($treemini, $pid);
        if ($assign) return $select_categorys; else $this->assign('select_categorys', $select_categorys);
        $brand = M('Brand')->where('status=1')->order('convert(brand_name using gb2312) ASC')->field('id,brand_name')->select();
        $brand_op = "<option value=''>" . L('PLEASE_SELECT_BRAND') . "</option>";
        foreach ($brand as $k => $v) {
            // if(intval($shopid)>0&&!in_array($v['id'],$use_BrandCategory)){unset($brand[$k]);continue;}
            if ($brandid == $v['id']) {
                $brand_op .= "<option selected='selected' value='" . $v['id'] . "'>" . $v['brand_name'] . "</option>";
            } else {
                $brand_op .= "<option value='" . $v['id'] . "'>" . $v['brand_name'] . "</option>";
            }
        }
        $this->assign('select_brands', $brand_op);
        $where_s=array();
        $where_s['status']=1;
        if($goods_type==5){
            $where_s['is_purchase']=1;
        }else{
            $where_s['is_direct']=1;
        }
        $suppliers_info = M('Suppliers')->where($where_s)->order('convert(name using gb2312) ASC')->field('id,name')->select();
        $suppliers_op = '';
        if (!empty($suppliers_info)) {
            foreach ($suppliers_info as $k => $v) {
                if ($suppliersid == $v['id']) {
                    $suppliers_op .= "<option selected='selected' value='" . $v['id'] . "'>" . $v['name'] . "</option>";
                } else {
                    $suppliers_op .= "<option value='" . $v['id'] . "'>" . $v['name'] . "</option>";
                }
            }
        }
        $this->assign('select_suppliers', $suppliers_op);
        unset($GoodsCategory, $select_categorys, $brand, $brand_op, $suppliers_info, $suppliers_op);
    }

    /**
     * 获取商品属性
     */
    public function attr_html($goods_catid,$goodsid)
    {
        $id_all=$id_shop=array();
        if ($goods_catid > 0) {
            
            $getallson = getallson($goods_catid, 'GoodsCategory');//获取所有子分类
            $getallparent = getallparent($goods_catid, '', 'GoodsCategory');//获取所有父级分类
            $new_catid_array = array_unique(array_merge($getallson, explode(',', $getallparent)));
            
            if ($new_catid_array) {
                $map['id']=array('in',$new_catid_array);
                $type_ids=M('GoodsCategory')->where($map)->getField('type_id',true);
                $type_ids=array_unique($type_ids);
                
                $all_map['type_id']=array('in',$type_ids);
                $all_map['shop_id']=0;
                $id_all =M('GoodsAttribute')->where($all_map)->getField('id',true);
            }
        }
        $shop_map['shop_id']=MID;
        $id_shop =M('GoodsAttribute')->where($shop_map)->getField('id',true);
        if($id_shop && $id_all){
            $ids=array_unique(array_merge($id_all, $id_shop));
        }elseif($id_shop){
            $ids=array_unique($id_shop);
        }elseif($id_all){
            $ids=array_unique($id_all);
        }
        if($ids){
            $ga_map['id']=array('in',$ids);
        }else{
            $ga_map['id'] = 0;
        }
        $allattr=M('GoodsAttribute')->where($ga_map)->select();
        
        foreach ($allattr as $k => $v) {
            if (empty($v['id'])) continue;
            $all_attr[$v['id']] = $v['type'];
            if ($allattr[$k]['options']) {
                $v['options'] = strtoarray($v['options']);
            }
            $all_attr_format[$v['id']] = $v;
        }
        if ($goodsid > 0) {//获取商品属性值
            $goodsval = $goodsattrarr = array();
            $goodsattr = M('GoodsAttr')->where('goods_id=' . $goodsid)->field('attr_id,attr_value,attr_price,supplier_price,attr_img')->order('id')->select();
            foreach ($goodsattr as $k => $v) {
                $goodsattrarr[] = $v['attr_value'] . intval($v['attr_price']) . $v['attr_img'];
                $goodsval[$v['attr_id']]['attr_id'] = $v['attr_id'];
                if ($all_attr[$v['attr_id']] == 'text') {
                    $goodsval[$v['attr_id']]['attr_text'] = $v['attr_value'];
                } else {
                    $goodsval[$v['attr_id']]['attr_select'][] = $v['attr_value'];
                    $goodsval[$v['attr_id']]['attr_price'][] = $v['attr_price'];
                    $goodsval[$v['attr_id']]['attr_balance_price'][] = $v['supplier_price'];
                    $goodsval[$v['attr_id']]['attr_img'][] = $v['attr_img'];
                    $goodsval[$v['attr_id']]['attr_count'] = count($goodsval[$v['attr_id']]['attr_select']);//循环总数
                }
            }
            $this->assign('configstr', md5(implode('', $goodsattrarr)));
            $this->assign('goodsattr', $goodsval);
        }
        $this->assign('allattr', $all_attr_format);
        unset($allattr, $goodsattr, $goodsattrarr, $goodsval);
    }

    /**
     * 导出商品
     */
    public function export()
    {
        $postdata = I('param.');
        $postdata['is_delete'] = 0;
        $postdata['publish_wait'] = 1;
        $postdata['shop_id']=MID;
        $map = D('Admin/Goods')->index_condition($postdata);
        $list = M('Goods')->where($map)->field(true)->select();
        $title = array('序号', '商品编号', '商品名称', '分类', '品牌', '供货商', '库存', '销量');
        $data = array();
        foreach ($list as $k => $v) {
            $data[$k][] = $v['id'];
            $data[$k][] = $v['goods_sn'];
            $data[$k][] = $v['goods_name'];
            $data[$k][] = idtoname($v['cat_id'], 'GoodsCategory');
            $data[$k][] = idtoname($v['brand_id'], 'Brand', 'brand_name');
            $data[$k][] = idtoname($v['suppliers_id'], 'Suppliers');
            $data[$k][] = $v['goods_number'];
            $data[$k][] = $v['sell_count'];
        }
        export_xls($title, $data, 'utf8');
        unset($title, $data);
        exit;
    }

    public function stock_update()
    {
         $auth_code = 'goodslist_add';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);exit;}

        $model = D(CONTROLLER_NAME);
        $postdata = I('post.');
        $data = $model->create($postdata);
        $goods_type=idtoname($postdata['id'],'Goods','goods_type');
        if($goods_type != 5){
            $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/index');
        }else{
            $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/stock_purchase',array('id'=>$postdata['id']));
        }
        if($postdata['attr_key']){
            $success_msg = '编辑成功';
        }else{
            $success_msg = '添加成功，编辑货品的初始库存！';
        }
        $msg = array_merge(array('success' => $success_msg, 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        if (!$model->update_goodsattr_stock($postdata)) {//更新商品属性库存，货品
            $this->error('货品编号不能为空或者有重复，请重新输入');
        }
        clearhomehtml($postdata['id']);//更新静态缓存
        unset($data, $postdata);
        $this->success($msg['success'], $msg['url'], $msg['ajax']);
    }

    public function check_goods_attr_sn()
    {
        $postdata = I('post.');
        $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => '', 'ajax' => IS_AJAX), (array)$msg);
        $map['goods_attr_sn'] = $postdata['goods_attr_sn'];
        $goodsattrstock = M('GoodsAttrStock')->where($map)->count();
        $status = 0;
        if ($goodsattrstock > 0) $status = 1;
        unset($data, $postdata);
        $this->success($status, '', $msg['ajax']);
    }

    /**
     * 搜索品牌
     */
    public function search_brand()
    {
        $return = array();
        $postdata = I('param.');
        $keyword = $postdata['keyword'];
        //获取可用品牌分类
        $map=array();
        if (is_numeric($keyword)) {
            $map['id|brand_name'] = array(intval($keyword), array('like', '%' . $keyword . '%'), '_multi' => true);
        } else if (!empty($keyword)) {
            $map['brand_name'] = array('like', '%' . (string)$keyword . '%');
        }
        // $map['id']=array('in',$use_BrandCategory);
        $brands = M('Brand')->where($map)->field('id,brand_name,brand_cat_id')->select();
        $options = "<option value=''>" . L('PLEASE_SELECT') . "</option>";
        foreach ($brands as $k => $v) {
            // if(!in_array($v['id'],$use_BrandCategory)){unset($brand[$k]);continue;}
            $options .= "<option value='" . $v['id'] . "'>" . $v['brand_name'] . "</option>";
        }
        $return['status'] = 1;
        $return['options'] = $options;
        $this->ajaxReturn($return);
    }
    public function cat_list(){
        $tabid=I('param.tabid');
        $shop_id=$this->shops_info['id'];
        $tablename='ShopsCategory';
        $map['shop_id']=MID;
        $data=D('Shops')->cat_nav_list($tablename,$map); 
        $this->assign('cateString', $data);
        if(!empty($tabid)) $this->display($tabid);
        else $this->display();
    }
    /**
     * 添加服务
     */
    public function service_add(){
        $tab_id=I('param.tabid');
        $tab_id=empty($tab_id)?'service_baseinfo':$tab_id;
        if($tab_id=='service_baseinfo'){
            $basedefault = array('moreimg' => '', 'moreimgstr' => '', 'morecatarr' => '', 'morecatid' => '', 'configstr' => '');
            $this->assign($basedefault);
            $this->get_member_price();//会员价
        }
        $postdata['publish_wait'] = 0;
        $postdata['shop_id']=MID;
        $serviceCat = M('ServiceCategory')->where('status=1')->field('id,name')->select();
        $this->getSeviceCat();
        $this->assign($postdata);
        $this->assign('menu_tab',$tab_id);
        $this->assign('menu_action_current','service');
        $this->display($tab_id);
    }
    /**
     * 修改服务
     */
    public function service_edit(){
        $tab_id=I('param.tabid');
        $id = I('get.id');
        if (!$id) $this->error(L('PARAM_ERR'));
        $map['shop_ids']=','.MID.',';
        $map['id']=$id;
        $info = M('Goods')->where($map)->field(true)->find();
        if(!$info)$this->error('无此操作权限');
        //获取商品的长字段
        $goodscontent = M('GoodsContent')->where('goods_id = ' . $id)->find();
        $info['content'] = $goodscontent['content'];
        $this->assign($info);
        $this->getSeviceCat();
        $this->assign('menu_tab',$tab_id);
        $this->assign('menu_action_current','service');
        $this->assign('title_ass','服务');
        $this->display('service_baseinfo');
    }
    /**
     * 插入服务
     */
    public function service_insert()
    {
        $postdata = I('post.');
        // echo "<pre>";
        // print_r($postdata);exit;
        $postdata['status']=1;
        $postdata['publish_wait']=1;//是否审核
        $shop_ids = ','.MID.',';
        $postdata['shop_ids']=$shop_ids;
        $postdata['shop_id']=MID;
        $postdata['addtime']=NOW_TIME;
        $postdata['goods_type'] = 4;
        $tab_id=$postdata['menu_tab'];
        $model = D('Admin/Goods');
        if(!$postdata['service_tostore'] && !$postdata['service_tohome']){
            $this->error('服务类型请至少选择一种');
        }
        if(!$postdata['service_tostore'])$postdata['service_tostore'] = 0;
        if(!$postdata['service_tohome'])$postdata['service_tohome'] = 0;
        if($tab_id=='service_baseinfo') {
            if (false === D('Goods')->create($postdata)) {
                $this->error(D('Goods')->getError());
            }
            $id = D('Goods')->add();
            if ($id !== false) {
                $postdata['id'] = $id;
                $model->update_user_price($postdata, 1);//更新会员价
                $model->update_goods_sn($postdata, 1);//更新货号
                $model->update_goods_content($postdata, 1);//更新商品详情和seo
                unset($postdata);
                if ($_POST['isajax']) $this->assign('dialog', '1');
                $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(CONTROLLER_NAME . '/service');
                $this->assign('jumpUrl', $jumpUrl);
                $this->success('添加成功',$jumpUrl);
            } else {
                $this->error('添加失败' . ': ' . $model->getDbError());
            }
        }
    }
    /**
     * 修改服务
     * @param string $model
     * @param string $data
     * @param string $where
     * @param string $msg
     */
    public function service_update($model = '', $data = '', $where = '1', $msg = '')
    {
        $model = D('Admin/Goods');
        $postdata = I('post.');
        if(!$postdata['service_tostore'] && !$postdata['service_tohome']){
            $this->error('服务类型请至少选择一种');
        }
        if(!$postdata['service_tostore'])$postdata['service_tostore'] = 0;
        if(!$postdata['service_tohome'])$postdata['service_tohome'] = 0;
        $postdata['updatetime']=NOW_TIME;
        $id = array_unique((array)I('id', 0));
        // print_r($id);exit;
        $shop_id=idtoname($id['0'],'Goods','shop_ids','id',false);
        $s_ids = array_filter(explode(',', $shop_id));
        // echo "<pre>";print_r($a);exit;
        if($s_ids['1']!=MID)$this->error('无此操作权限');
        $id = is_array($id) ? implode(',', $id) : $id;
        $where = array_merge(array('id' => array('in', $id)), (array)$where);
        $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(CONTROLLER_NAME . '/service');
        $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        $tab_id=$postdata['menu_tab'];
        $savedata['status']=1;
        $savedata['publish_wait']=1;
        D('Goods')->where($where)->data($savedata)->save();
        $data = D('Goods')->create($postdata);
        if (D('Goods')->where($where)->save($data) !== false) {
            $postdata['id'] = $id;
            $model->update_user_price($postdata);//更新会员价
            $model->update_goods_sn($postdata);//更新货号
            $model->update_goods_content($postdata);//更新商品详情和seo
            clearhomehtml($id);//更新静态缓存
            unset($data, $postdata, $newgoodscat, $newgoodsimg, $goodstype, $goodstypearr, $newgoodsattr);
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
        
    }
    public function getSeviceCat(){
        $serviceCat = M('ServiceCategory')->where('status=1')->field('id,name')->select();
        if ($serviceCat) {
            $serviceCat = format_array2select($serviceCat); 
        }
        $this->assign('serviceCat', $serviceCat);
    }
    /**
     * 添加套餐
     */
    public function package_add(){
        $tab_id=I('param.tabid');
        $tab_id=empty($tab_id)?'package_baseinfo':$tab_id;
        if($tab_id=='package_baseinfo'){
            $basedefault = array('moreimg' => '', 'moreimgstr' => '', 'morecatarr' => '', 'morecatid' => '', 'configstr' => '');
            $this->assign($basedefault);
            $this->get_member_price();//会员价
        }
        $postdata['publish_wait'] = 0;
        $postdata['shop_id']=MID;
        $serviceCat = M('ServiceCategory')->where('status=1')->field('id,name')->select();
        $this->getService();
        $this->assign($postdata);
        $this->assign('menu_tab',$tab_id);
        $this->assign('menu_action_current','package');
        $this->display($tab_id);
    }
    /**
     * 修改套餐
     */
    public function package_edit(){
        $tab_id=I('param.tabid');
        $id = I('get.id');
        if (!$id) $this->error(L('PARAM_ERR'));
        $map['shop_id']=MID;
        $map['id']=$id;
        $info = M('Goods')->where($map)->field(true)->find();
        if(!$info)$this->error('无此操作权限');
        $info['contain_service'] = json_decode($info['contain_service'],true);
        $info['contain'] = $info['contain_service'];
        foreach($info['contain_service'] as $k=>$v){
            $info['contain_service'][$k] = idtoname($k,'Goods','goods_name')."(".idtoname($k,'Goods','shop_price').")(".$v."次)";
        }unset($k,$v);
        $info['check'] =implode(',',array_keys($info['contain_service']));
        
        //获取商品的长字段
        $goodscontent = M('GoodsContent')->where('goods_id = ' . $id)->find();
        $info['content'] = $goodscontent['content'];
        $this->assign($info);
        $this->getService();
        $this->assign('menu_tab',$tab_id);
        $this->assign('menu_action_current','package');
        $this->display('package_baseinfo');
    }
    /**
     * 插入套餐
     */
    public function package_insert(){
        $model = M('Goods');
        $postdata=I('param.');
        foreach($postdata['service'] as $k=>$v){
            $postdata['contain_service'][$v] = $postdata['nums'][$v]; 
        }unset($postdata['service'],$postdata['nums']);
        // if($postdata['shop_ids'])$postdata['shop_ids'] = ','.implode(',',$postdata['shop_ids']).',';
        $postdata['shop_ids'] = ','.MID.',';
        $postdata['shop_id'] = MID;
        $postdata['contain_service'] = json_encode($postdata['contain_service']);
        $postdata['continued'] = intval($postdata['continued']);
        $postdata['shop_price'] = $postdata['market_price'];
        $postdata['addtime'] = NOW_TIME;
        $postdata['publish_wait'] = 1;
        $postdata['status'] = 1;
        $postdata['goods_type'] = 6;
        $map['goods_name'] = $postdata['goods_name'];
        $map['goods_type'] = 6;
        $count = $model->where($map)->count();
        if($count){
            $this->error('套餐名称重复');
        }
        $id = $model->add($postdata);
        $content['goods_id'] = $id;
        $content['content'] = $postdata['content'];
        M('GoodsContent')->add($content);
        if($id){
            $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(CONTROLLER_NAME . '/package');
            $this->assign('jumpUrl', $jumpUrl);
            $this->success('添加成功',$jumpUrl);
        }else{
            $this->error('添加失败');
        }
    }
    public function package_update(){
        $model = M('Goods');
        $postdata=I('param.');
        // echo "<pre>";
        // print_r($postdata);exit;
        foreach($postdata['service'] as $k=>$v){
            $postdata['contain_service'][$v] = $postdata['nums'][$v]; 
        }unset($postdata['service'],$postdata['nums']);
        $postdata['contain_service'] = json_encode($postdata['contain_service']);
        
        $postdata['shop_price'] = $postdata['market_price'];
        $postdata['continued'] = intval($postdata['continued']);
        $postdata['updatetime'] = NOW_TIME;
        $postdata['status'] = 1;
        $postdata['publish_wait'] = 1;
        $map['goods_name'] = $postdata['goods_name'];
        $map['id'] = array('neq',$id);
        $count = $model->where($map)->count();
        if($count){
            $this->error('套餐名称重复');
        }
        $id = $model->save($postdata);
        $content['content'] = $postdata['content'];
        $where['goods_id'] = $postdata['id'];
        M('GoodsContent')->where($where)->save($content);
        if($id){
            $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(CONTROLLER_NAME . '/package');
            $this->assign('jumpUrl', $jumpUrl);
            $this->success('编辑成功',$jumpUrl);
        }else{
            $this->error('编辑失败');
        }
    }
    /**
     * 服务查询
     */
    private function getService(){
        $map = array();
        $map['goods_type'] = 4;
        $map['status'] = 1;
        $map['shop_id'] = MID;
        $map['is_delete'] = 0;
        $serviceData = M('Goods')->where($map)->field('id,goods_name,shop_price')->select();
        $this->assign('serviceData',$serviceData);
    }
    
    /**
     * 外卖分类
     */
    public function cate(){
        $tabid=I('tabid');
        if($tabid=='add_cate'){
            $this->get_location();
            $this->assign('shop_id',MID);
            $tabid='edit_cate';
        } elseif($tabid=='edit_cate'){
            $id=I('id');$where=array();$where['id']=$id;
            $shop_cate_info=M('ShopsCategory')->where($where)->field(true)->find();
            $this->assign($shop_cate_info);
            $this->get_location();
        } else {
            $map = array();
            $map['shop_id'] = MID;
            $list = page_list('ShopsCategory', $map);
            $this->assign($list);
            $tabid='cate';
        }
        $this->assign('menu_tab','cate');
        $this->assign('menu_action_current','cate');
        $this->display($tabid);
    }
    /**
     * shops_category表外卖分类上下架
     */
    public function cate_status(){
        $model = D('ShopsCategory');
        $id     = intval(I('id'));
        $type   = I('type');
        
        $values = $model->where('id='.$id)->field($type)->find();
        $data[$type]=($values[$type]+1)%2;
        $res=$model->where('id='.$id)->save($data);
        $this->ajaxReturn($data[$type]);
    }
    private function get_location(){
        $where = array();
        $where['shop_id']=MID;
        $where['status']=1;
        $where['pid']=0;
        $shops_account = M('ShopsAccount')->where($where)->field('id,name')->select();
        $account_arr = format_array2select($shops_account, 'name');
        $this->assign('account_arr', $account_arr);
    }

    public function insert_cate(){
        $name='ShopsCategory';
        $model = D($name);
        $postdata = I('post.');
        if (false === $model->create($postdata)) {
            $this->error($model->getError());
        }
        $id = $model->add();
        if ($id !== false) {
            $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U('Goods/cate');
            $this->assign('jumpUrl', $jumpUrl);
            $this->success(L('ADD_OK'));
        } else {
            unset($postdata);$this->error(L('ADD_ERROR') . ': ' . $model->getDbError());
        }
    }
    public function update_cate(){
        $name='ShopsCategory';
        $model = D($name);
        $postdata = I('post.');
        $data = $model->create($postdata);
        $jumpUrl = I('forward') ? I('forward') : U('Goods/cate');

        $where['id'] = I('id');
        $where['shop_id'] = MID;
        $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        if ($model->where($where)->save($data) !== false) {
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            unset($postdata);
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
    }
    public function delete_shops_cate(){
        $id=I('id');
        $where=array();
        $where['id']=$id;
        $where['shop_id']=MID;
        $count=M('ShopsCategory')->where($where)->delete();
        if($count){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    public function service(){
        $name = CONTROLLER_NAME;
        $tabid = I('param.tabid');
        if (!empty($tabid)) $this->display($tabid);
        else{
            $postdata = I('param.');
            $shop_ids = ','.MID.',';
            $map['is_delete'] = 0;
            $map['goods_type'] = 4;
            $map['_string'] = "shop_ids like '%".$shop_ids."%' OR shop_ids='0'";
            if($postdata['catid'])$map['cat_id'] = $postdata['catid'];
            $keyword = I('keyword');
            if(!empty($keyword)){
                $whereor['id']=array('like','%'.$keyword.'%');
                $whereor['goods_sn']=array('like','%'.$keyword.'%');
                $whereor['goods_name']=array('like','%'.$keyword.'%');
                $whereor['_logic'] = 'or';
                $map['_complex'] = $whereor;
                $seotitle=$keyword.'_';
            }
            $this->getSeviceCat();
            $list = $this->lists($name, $map);
            foreach($list as $k=>$v){
                if($v['shop_id'] === MID){
                    $list[$k]['s_edit'] = 1;
                    $list[$k]['s_shop'] = 1;
                }
            }unset($k,$v);
            $this->assign('list', $list);
            $this->assign($postdata);
            $this->assign('title_ass','服务');
            $this->display();
        }
    }
    public function package(){
        $name = M('Goods');
        $map = array();
        $map['goods_type'] = 6;
        $postdata = I('param.');
        $keyword = $postdata['keyword'];
        if(!empty($keyword)){
            $map['name']=array('like','%'.$keyword.'%');
        }
        if(!empty($postdata['reg_from']))$map['addtime'][]=array('EGT',strtotime($postdata['reg_from']));
        if(!empty($postdata['reg_to']))$map['addtime'][]=array('elt',strtotime($postdata['reg_to']));
        $shop_ids = ','.MID.',';
        $map['is_delete'] = 0;
        $map['goods_type'] = 6;
        $map['_string'] = "shop_ids like '%".$shop_ids."%' OR shop_ids='0' OR shop_id=".MID;
        $list = $this->lists($name, $map);
        foreach($list as $k=>$v){
            $list[$k]['contain_service'] = json_decode($v['contain_service'],true);
        }
        foreach($list as $k=>$v){
            if($v['shop_id'] === MID){
                $list[$k]['s_edit'] = 1;
                $list[$k]['s_shop'] = 1;
            }
        }unset($k,$v);
        $this->assign('list', $list);
        $this->assign($postdata);
        $this->display();
    }
    /**
     * 商品发布
     */
    public function publish(){
        $postdata = array();
        $id = array_unique((array)I('id', 0));
        $id = is_array($id) ? implode(',', $id) : $id;
        $where = array_merge(array('id' => array('in', $id)), (array)$where);
        $msg = array_merge(array('success' => '发布成功,等待审核！', 'error' => '发布失败！', 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        $postdata['status']=1;
        if (D('Goods')->where($where)->save($postdata) !== false) {
            clearhomehtml($id);//更新静态缓存
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
    }
    /**
     * 更新门店信息
     */
    public function update_setting(){
        $shops_info=session('shops_info');
        $shop_id = $shops_info['shop_id'];
        
        $name = 'ShopsAccount';
        $model = D('Shop/ShopsAccount');
        $postdata = I('post.'); 
        $data = M($name)->create($postdata);

        $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/setting');
        $id = array_unique((array)I('id', 0));
        $id = is_array($id) ? implode(',', $id) : $id;
        
        if(empty($shop_id)){
            $this->error('参数错误！');
        }
        if($shops_info['pid'] != 0){
            $this->error('您对此没有权限，请更换有权限的账户登录！');
        }
        
        $where = array_merge(array('id' => array('in', $id)), (array)$where);
        $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        if (M($name)->where($where)->save($data) !== false) {
            $postdata['shop_id'] = $shop_id;
            $model->update_shipping_info($postdata);//更新配送信息
            $model->update_bagging_info($postdata);//更新包装费信息
            unset($data, $postdata);
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
    }
    public function add_purchase(){
         $auth_code = 'goodslist_add';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);}
        $shop_type = M('Shops')->where('id='.MID)->getField('shop_type');
        //连锁店直接默认是后台商品
		if($shop_type != 1){
            $this->assign('shop_id',MID);
        }else{
            $this->assign('shop_id',0);
        }


        $umap = array();
        $umap['status']=1;
        $unitlist = M('GoodsUnit')->where($umap)->select();
        $select_unit = '';
        if (!empty($unitlist)) {
            foreach ($unitlist as $k => $v) {
                $select_unit .= "<option value='" . $v['id'] . "'>" . $v['name'] . "</option>";
            }
        }
        $this->assign('select_unit', $select_unit);
        
        $this->getNodeTree('','','','','',5);
        $basedefault = array('moreimg' => '', 'moreimgstr' => '', 'morecatarr' => '', 'morecatid' => '', 'configstr' => '');
        $this->assign($basedefault);
        $this->attr_arr();
        $this->get_goods_label();
        $this->get_member_price();//会员价
        $tab_id=I('tabid');
        if($tab_id){$this->error('请先填写商品主要信息！');}
        $this->display('edit_purchase');


    }

    /**
     * 搜索供货商
     */
    public function search_suppliers()
    {
        $return = array();
        $postdata = I('param.');
        $keyword = $postdata['keyword'];
        if (is_numeric($keyword)) {
            $map['id|name'] = array(intval($keyword), array('like', '%' . $keyword . '%'), '_multi' => true);
        } else if (!empty($keyword)) {
            $map['name'] = array('like', '%' . (string)$keyword . '%');
        }
        $brands = M('Suppliers')->where($map)->field('id,name')->order('id asc')->select();
        $options = "<option value=''>" . L('PLEASE_SELECT_SUPPLIER') . "</option>";
        foreach ($brands as $k => $v) {
            $options .= "<option value='" . $v['id'] . "'>" . $v['name'] . "</option>";
        }
        $return['status'] = 1;
        $return['options'] = $options;
        $this->ajaxReturn($return);
    }
      /**
     * 插入订货商品
     */
    public function insert_pur(){
        $auth_code = 'goodslist_add';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);exit;}

        $model = D('Admin/'.CONTROLLER_NAME);
        $data = $model->create();
        $this->check_goods_sn(I('param.'));
        if($data['goods_code']){
            $map_sn = array();
            if($data['id']){
                $map_sn['id'] = array('neq',$data['id']);
            }
            $map_sn['goods_code'] = $data['goods_code'];
            $map_sn['goods_type'] = 5;
            $g_count = $model->where($map_sn)->count();
            if($g_count){
                $this->error('货码不能重复，不填可以自动生成');exit;
            }
        }
        if($data['is_type'] == 1){
            if($data['goods_plu']){
                $map_sn = array();
                if($data['id']){
                    $map_sn['id'] = array('neq',$data['id']);
                }
                $map_sn['goods_plu'] = $data['goods_plu'];
                $plu_count = $model->where($map_sn)->count();
                if($plu_count){
                    $this->error('商品PLU不能重复');exit;
                }
            }
        }else{
            $data['goods_plu'] = 0;
        }
        
        if($data['sale_type'] == 1){
            $data['limit_count'] = $data['lower_count'] = 0;
        }
        // echo "<pre>";print_r($data);exit;
        if (false === $data) {
            $this->error($model->getError());
        }
        $id = $model->add();
        if ($id !== false) {
            $postdata = I('post.');
            // echo "<pre>";print_r($postdata);exit;
            if($postdata['is_integral']!=1){
                $postdata['is_integral']=0;
            }
            $postdata['id'] = $id;
            $model->update_goodsattr($postdata, 1);//更新扩增分类
            $model->update_goodsimg($postdata, 1);//更新商品相册
            $model->update_goodstype($postdata, 1);//更新商品属性
            $model->update_user_price($postdata, 1);//更新会员价
            // $model->update_goods_sn($postdata, 1);//更新货号
            $model->update_goods_code($postdata, 1);//更新货码
            $model->update_goods_content($postdata, 1);//更新商品详情和seo
            // 有添加属性，不添加初始库存
            if(!$postdata['config'] && !empty($postdata['goods_num']) && $postdata['sale_type'] != 1){
                $model->save_shops_stock($postdata);//门店初始库存
            }

            if($postdata['sale_type']==1){
                $res = $model->update_goods_package($postdata);//添加商品包装
                if($res['status']==0){
                    $this->error('组合包装商品数量必须大于0');exit;
                }
            }
			if($id && $postdata['custom_goods_price']){
				$postdata['current_shop_id'] = MID;
				//添加门店商品价格
				D('App/Goods')->add_goods_price($id,$postdata);
			}
            unset($postdata);
            if ($_POST['isajax']) $this->assign('dialog', '1');
            $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(CONTROLLER_NAME . '/index');
            $this->assign('jumpUrl', $jumpUrl);
            $url=U(CONTROLLER_NAME.'/edit_purchase',array('id'=>$id,'tabid'=>'group_type'));
            $this->success(L('ADD_OK'),$url);
        } else {
            $this->error(L('ADD_ERROR') . ': ' . $model->getDbError());
        }
    }

     /**
     * 编辑商品
     */
    public function edit_purchase()
    {
        $tab_id=I('param.tabid');
        // add时网上销售信息也走这块
        if(empty($tab_id)){
            $auth_code = 'goodslist_edit';
            $ret=D('Shop/Shops')->shop_account_option($auth_code);
            if($ret['status']!=1) {$this->error($ret['msg']);exit;}
        }
         $id = I('get.id');
        $info = '';
        if (!$id) $this->error(L('PARAM_ERR'));
        $map=array();
        $map['id']=$id;
        // 避免连锁店添加商品直接shop_id=0报错
        if(idtoname(MID,'Shops','shop_type')!=1){
            $map['shop_id']=MID;
        }
        $info = M('Goods')->where($map)->field(true)->find();
        if (!$info) $this->error(L('PARAM_ERR'));
        $this->attr_arr();
        $this->get_goods_label($id);
        $this->pattr_html($id);//获取属性
        //获取关联分类
        $morecatarr = $morecatidarr = array();
        $where1['goods_id'] = $id;
        $morecat = M('GoodsCat')->where($where1)->field(true)->select();
        if (!empty($morecat)) {
            foreach ($morecat as $v) {
                $morecatidarr[] = $v['catid'];
                $morecatarr[] = $this->getcateTree($v['catid'], 1,'','','',5);
            }
        }
        $this->assign('morecatarr', $morecatarr);
        $this->assign('morecatid', implode(',', $morecatidarr));
        //获取商品相册
        $moreimg = M('GoodsGallery')->where('goods_id=' . $id)->field('id,goods_img,img_desc,img_sort')->order('id')->select();
        $moreimgarr = array();
        $moreimgstr = '';
        if (!empty($moreimg)) {
            foreach ($moreimg as $v) {
                $moreimgarr['goods_img'][] = $v['goods_img'];
                $moreimgarr['img_desc'][] = $v['img_desc'];
                $moreimgarr['img_sort'][] = $v['img_sort'];
            }
            $moreimgstr = implode('', $moreimgarr['goods_img']) . implode('', $moreimgarr['img_desc']) . implode('', $moreimgarr['img_sort']);

        }
        $this->assign('moreimg', $moreimg);
        $this->assign('moreimgstr', md5($moreimgstr));
        //获取分类 类型 品牌 店铺
        $this->getNodeTree($info['cat_id'], '', $info['brand_id'], $info['suppliers_id'],$id,5);
        //获取商品的长字段
        $goodscontent = M('GoodsContent')->where('goods_id = ' . $id)->find();
        $info['content'] = $goodscontent['content'];
        $info['seotitle'] = $goodscontent['seotitle'];
        $info['seokeywords'] = $goodscontent['seokeywords'];
        $info['seodescription'] = $goodscontent['seodescription'];
        $this->get_member_price($id);//会员价
		
		$info['is_custom'] = $info['custom_goods_price'] = 0;
		
		$map = array();$map['id'] = MID;
		$shop_center_rule = M('Shops')->where($map)->getField('shop_center_rule');
		if($shop_center_rule){
			$shop_center_rule_array = json_decode($shop_center_rule,true);
			$info['is_custom'] = $shop_center_rule_array['custom_goods_price'];
			if($info['is_custom'] == 1){
				$map = array();$map['shop_id'] = MID;$map['goods_id'] = $id;
				$info['custom_goods_price'] = M('ShopsGoods')->where($map)->getField('goods_price');
			}
		}
		
        // $this->assign('info', $info);
        $this->assign($info);
        $umap['status']=1;
        $unitlist = M('GoodsUnit')->where($umap)->select();
        $select_unit = '';
        if (!empty($unitlist)) {
            foreach ($unitlist as $k => $v) {
                if ($info['unit_id'] == $v['id']) {
                    $select_unit .= "<option selected='selected' value='" . $v['id'] . "'>" . $v['name'] . "</option>";
                } else {
                    $select_unit .= "<option value='" . $v['id'] . "'>" . $v['name'] . "</option>";
                }
            }
        }
        $this->assign('select_unit', $select_unit);
        $this->group_goods($id);
        unset($info, $morecatarr, $morecatidarr, $moreimg, $moreimgarr, $moreimgstr);
        
        $tab_id=empty($tab_id)?'edit_purchase':$tab_id;
        $this->display($tab_id);
    }
    public function get_goods_label($goods_id = ''){
        $selectstr =$select_str = $label_arr =  array();
        $this->assign('selectstr', $selectstr);
        $this->assign('label_arr', $label_arr);
        $this->assign('select_str', $select_str);
    }
    public function attr_arr(){
        $ga_map = array();
        $ga_map['status'] = 1;
        $attr_arr=M('GoodsAttribute')->where($ga_map)->field(true)->select();
        $this->assign('attr_arr', $attr_arr);
    }
        /**
     * 获取订货商品属性
     */
    public function pattr_html($goodsid){
        // $goodsid = intval($_REQUEST['goodsid']);//商品id
        $ga_map = array();
        $ga_map['status'] = 1;
        $allattr=M('GoodsAttribute')->where($ga_map)->select();
        
        $all_attr_format = array();
        foreach ($allattr as $k => $v) {
            if ($allattr[$k]['options']) {
                $v['options'] = strtoarray($v['options']);
            }
            $all_attr_format[$v['id']] = $v;
        }
        
        if ($goodsid > 0) {//获取商品属性值
            $attr_ids = $goodsval = $goodsattrarr = array();
            $goodsattr = M('GoodsAttr')->where('goods_id=' . $goodsid)->field(true)->select();
            foreach ($goodsattr as $k => $v) {
                $goodsattrarr[] = $v['attr_value'] . floatval($v['attr_price']) . $v['attr_img'];
                $goodsval[$v['attr_id']]['attr_id'] = $v['attr_id'];
                
                $attr_ids[] = $v['attr_id'];
                if ($all_attr[$v['attr_id']] == 'text') {
                    $goodsval[$v['attr_id']]['attr_text'] = $v['attr_value'];
                } else {
                    $goodsval[$v['attr_id']]['attr_select'][] = $v['attr_value'];
                    $goodsval[$v['attr_id']]['attr_img'][$v['attr_value']] = $v['attr_img'];
                }
                $map = array();
                $map['id'] = $v['attr_id'];
                $map['status'] = 1;
                $attr_all = M('GoodsAttribute')->where($map)->getField('options');
                $goodsval[$v['attr_id']]['attr_all'] = explode(',',$attr_all);
            }
            $attr_idstr = ','.implode(',',array_unique(array_filter($attr_ids))).',';
            // echo "<pre>";
            // print_r($goodsval);exit;
            $this->assign('configstr', md5(implode('', $goodsattrarr)));
            $this->assign('goodsattr', $goodsval);
            $this->assign('attr_ids', $attr_idstr);
        }
        $this->assign('allattr', $all_attr_format);
        unset($allattr, $goodsattr, $goodsattrarr, $goodsval);
    }
    // 商品属性
    public function search_attrinfo(){
        $return = array();
        $return['status'] = 0;
        $goodsid = intval($_REQUEST['goodsid']);//商品id
        $postdata = I('post.');
        
        $attr_id = $postdata['attrid'];
        
        if($attr_id){
            $ga_map = array();
            $ga_map['status'] = 1;
            $ga_map['id'] = $attr_id;
            $allattr=M('GoodsAttribute')->where($ga_map)->field(true)->find();
            
            $allattr['options'] = strtoarray($allattr['options']);
            if($allattr){
                $return['status'] = 1;
                $this->assign($allattr);
                $return['html'] = $this->fetch("pattr_html");
            }else{
                $return['msg'] = '没有找到相关信息！';
            }
        }else{
            $return['msg'] = '请选择属性！';
        }
        $this->ajaxReturn($return);
    }
    /**
     * 获得计重商品编码
     */
    public function jz_sn(){
        $return = array();
        $return['status'] = 1;
        $sn = weight_goods_sn();
        if($sn){
            $return['sn'] = $sn;
        }else{
            $return['status'] = 0;
        }
        $this->ajaxReturn($return);
    }
    public function choose_shops(){
        $postdata=I('post.');
        $goods_id = $postdata['goods_id'];
        $map = array();
        // $map['status'] = 1;
        // $map['id'] = array('gt',0);
        // $total=M('Shops')->where($map)->count();
        // if(empty($total)){
        //     $return['status']=2;
        //     $return['info']='没有查询到门店';
        //     $this->ajaxReturn($return);//返回查询商品为空
        // }
        // // $pagehtml = '<span class="sum_shop">共有'.$total.'个门店</span>';
        // $list=array();
        // $list=M('Shops')->where($map)->field('id,name')->select();

        $html='<table class="table_shops">';
        $html.='<thead><tr><th width="220">门店名称</th><th width="180">当前库存</th><th width="120">增减</th><th width="140">变更数量</th></tr></thead><tbody>';
        // if($list){
            // foreach($list as $k=>$v){
        $shop_info=session('shops_info');
        $v=array();$v['id']=MID;$v['name']=idtoname(MID,'Shops','name');
                if($goods_id){
                    $where = array();
                    $where['shop_id'] = $v['id'];
                    $where['goods_id'] = $goods_id;
                    if($postdata['is_edit'] != 1){
                        $where['goods_stock'] = $postdata['attr_key'];
                    }else{
                        $where['goods_stock'] = 0;
                    }
                    $v['shop_num'] = M('ShopsGoodsStock')->where($where)->getField('goods_number');
                    if(!$v['shop_num']){
                        $v['shop_num'] = 0;
                    }
                }else{
                    $v['shop_num'] = 0;
                }
                $html.='<tr><td>'.$v['name'].'</td><td>'.floatval($v['shop_num']).'</td>';
                $html.='<td class="t_c"><select name="type_num[]" class="shops_control">';
                $html.='<option value="0">增加</option><option value="1">减少</option></select></td>';
                $html.='<td><input type="hidden" value="'.$v['id'].'" name="shop_ids[]" />';
                $html.='<input type="text" value="" name="goods_num[]" /></td></tr>';
            // }
        // }else{
        //     $html.='<tr><td colspan="4" class="t_c">暂无门店</td></tr>';
        // }
        $html.='</tbody></table>';
        $return['status']=1;
        $return['data']=$html;
        $return['page']=$pagehtml;
        // $return['totalpages']=$page->totalPages;
        $this->ajaxReturn($return);
    }
     public function update_pur($model = '', $data = '', $where = '1', $msg = '')
    {

        $model = D('Admin/'.CONTROLLER_NAME);
        $postdata = I('post.');
        unset($postdata['menu_tab']);
        if($postdata['is_integral']!=1){
            $postdata['is_integral']=0;
        }
        $checkcheckbox = array('is_best', 'is_new', 'is_hot', 'is_shipping');
        foreach ($checkcheckbox as $v) {
            if (empty($postdata[$v])) $postdata[$v] = '0';
        }
        if($postdata['sale_type'] == 1){
            $postdata['limit_count'] = $postdata['lower_count'] = 0;
        }
        $this->check_goods_sn($postdata);
        
        if($postdata['goods_code']){
            $map_sn = array();
            if($postdata['id']){
                $map_sn['id'] = array('neq',$postdata['id']);
            }
            $map_sn['goods_code'] = $postdata['goods_code'];
            $map_sn['goods_type'] = 5;
            $g_count = $model->where($map_sn)->count();
            if($g_count){
                $this->error('货码不能重复，不填可以自动生成');exit;
            }
        }
        if($postdata['is_referral']==2){
            if(!$postdata['commission'] && $postdata['commission']!==0){
                $this->error('分佣设置不正确！');exit;
            }
        }
        if(!preg_match('/^(0|[1-9][0-9]{0,9})(\.[0-9]{1,2})?$/',$postdata['commission'])&& $postdata['commission']){
             $this->error('分佣设置不正确！');exit;
        }


        $data = $model->create($postdata);
        $jumpUrl = I('forward') ? I('forward') : U(CONTROLLER_NAME . '/index');
        $id = array_unique((array)I('id', 0));
        $id = is_array($id) ? implode(',', $id) : $id;
        $where = array_merge(array('id' => array('in', $id)), (array)$where);
        $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        if ($model->where($where)->save($data) !== false) {
            $postdata['id'] = $id;
            $model->update_goodsattr($postdata);//更新扩增分类
            $model->update_goodsimg($postdata);//更新商品相册
           
            if($postdata['config']){    //取消最后一个属性
                $true=false;
                foreach ($postdata['config'] as $k => $v) {
                    if (str_exists($k, '_') || !$v) continue;
                    if (!empty($v[$k . '_text'])) {
                       $true=true;break;
                    } elseif (!empty($v[$k . '_select'])) {
                        $true=true;break;
                    }

                }
                if(!$true){unset($postdata['config']);};
            }
             $model->update_goodstype($postdata);//更新商品属性
            $model->update_user_price($postdata);//更新会员价
            // $model->update_goods_sn($postdata);//更新货号
            $model->update_goods_code($postdata);//更新货码
            $model->update_goods_content($postdata);//更新商品详情和seo
            $model->update_goods_package($postdata);//更新商品包装
			
			if($postdata['id'] && $postdata['custom_goods_price']){
				$postdata['current_shop_id'] = MID;
				//添加门店商品价格
				D('App/Goods')->add_goods_price($postdata['id'],$postdata);
			}
            
            clearhomehtml($id);//更新静态缓存
            unset($data, $postdata, $newgoodscat, $newgoodsimg, $goodstype, $goodstypearr, $newgoodsattr);
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        } else {
            $this->error($msg['error'], $msg['url'], $msg['ajax']);
        }
    }
     
    /**
     * 检查商品编号是否正确
     */
    private function check_goods_sn($data){
       
        if(empty($data['goods_sn'])){
            $this->error('商品编码不能为空！');exit;
        }else{
            if(strlen(intval($data['goods_sn'])) < 5){
                $this->error('商品编码最少为5位，可以重新生成！');exit;
            }
            $map_sn = array();
            if($data['id']){
                $map_sn['id'] = array('neq',$data['id']);
            }
            $map_sn['goods_sn'] = $data['goods_sn'];
            $map_sn['goods_type'] = 5;
            $g_count = M('Goods')->where($map_sn)->count();
            if($g_count){
                $this->error('商品编码不能重复，可以重新生成！');exit;
            }else{
                if($data['is_type'] == 1 && strlen(intval($data['goods_sn'])) != 5){
                    $this->error('商品编码不正确，可以重新生成！');exit;
                }
                if($data['is_type'] != 1 && strlen(intval($data['goods_sn'])) == 5){
                    $this->error('商品编码不正确，可以重新生成！');exit;
                }
            }
        }
    }

    /**
     * 修改订货商品初始库存
     */
    public function sub_shops_stock(){
        $return = array();$return['status'] = 1;
        $postdata = I('param.');
        if ($postdata['id'] && $postdata['goods_num']) {
            $ret = D('Admin/Goods')->save_shops_stock($postdata);//门店初始库存
            if ($ret['status'] == 0) {
                $return['status'] = 0;$return['msg'] = $ret['msg'];
            }
        }else{
            $return['status'] = 0;$return['msg'] = '参数错误！';
        }
        $this->ajaxReturn($return);
    }

    public function group_goods($id){
        $map=array();
        $map['goodsid'] = $id;
        $list = M('GroupGoods')->where($map)->select();
        foreach($list as $k=>$v){

            if($v['attr_key']){
                $attr_key = explode('-',$v['attr_key']);
                $list[$k]['attr']=attr_key2name($attr_key[1],$v['linkid']);
                $list[$k]['shop_price']=idtoname($attr_key[1],'GoodsAttrStock','attr_price','attr_key',false);
                $list[$k]['goods_sn']=idtoname($attr_key[1],'GoodsAttrStock','goods_attr_sn','attr_key',false);
            }else{
                $list[$k]['shop_price']=idtoname($v['linkid'],'Goods','shop_price','id',false);
                $list[$k]['goods_sn']=idtoname($v['linkid'],'Goods','goods_sn','id',false);
            }

        }
        $this->assign('groupnum',count($list));
        $this->assign('groupgoods',$list);
    }
    /**
     * 订货货品管理
     */
    public function stock_purchase()
    {
        $postdata = I('param.');
        $goods_id = intval($postdata['id']);
        if ($goods_id > 0) {
            $goodsdata = M('Goods')->where('id=' . $goods_id)->field('goods_name,goods_sn')->find();
            $this->assign('goodsdata', $goodsdata);
            $this->assign('id', $goods_id);
            $goodsattr = M('GoodsAttr')->alias('ga')->where("gatt.type='checkbox' and ga.goods_id = " . $goods_id)->JOIN("LEFT JOIN __GOODS_ATTRIBUTE__ gatt ON ga.attr_id=gatt.id")->select();
            foreach ($goodsattr as $k => $v) {
                if (empty($v['id'])) continue;
                $v['options'] = strtoarray($v['options']);
                $check_option[$v['id']][] = $v['attr_value'];
                $goodsattr_format[$v['id']] = $v;
            }
            foreach ($check_option as $k => $v) {
                $check[$k] = array_values($v);
                foreach ($goodsattr_format[$k]['options'] as $key => $val) {
                    if (in_array($key, $check[$k])) {
                        $goodsattr_format[$k]['options_format'][$key] = $val;
                    }
                }
            }
            $goodsattrstock = M('GoodsAttrStock')->where('goods_id=' . $goods_id)->order('id')->field(true)->select();
            foreach ($goodsattrstock as $k => $v) {
                $attr_key_array[$k]['attr_key_arr'] = $v['attr_key'];
                $attr_key_array[$k]['attr_key'] = explode('_', $v['attr_key']);
                // $attr_key_array[$k]['stock_cfg'] = $v['stock_cfg'];
                $attr_key_array[$k]['goods_attr_sn'] = $v['goods_attr_sn'];
                $attr_key_array[$k]['sell_count'] = $v['sell_count'];
                $attr_key_array[$k]['attr_price'] = $v['attr_price'];
            }
            foreach ($attr_key_array as $k => $v) {
                foreach ($v['attr_key'] as $val) {
                    if (empty($val)) continue;
                    $goods_attr_info = M('GoodsAttr')->where('id=' . $val)->field('id,attr_id,attr_value')->find();
                    $attr_key_array_format[$k]['attr_val'][$goods_attr_info['attr_id']]['id'] = $goods_attr_info['attr_id'];
                    $attr_key_array_format[$k]['attr_val'][$goods_attr_info['attr_id']]['val'] = $goods_attr_info['attr_value'];
                    // $attr_key_array_format[$k]['stock_cfg'] = $v['stock_cfg'];
                    $attr_key_array_format[$k]['goods_attr_sn'] = $v['goods_attr_sn'];
                    $attr_key_array_format[$k]['sell_count'] = $v['sell_count'];
                    $attr_key_array_format[$k]['attr_price'] = $v['attr_price'];
                    $attr_key_array_format[$k]['attr_key'] = $v['attr_key_arr'];
                }
            }
            if (empty($attr_key_array_format)) {//构造空数组循环
                foreach ($goodsattr_format as $k => $v) {
                    $where[$k]['goods_id'] = $goods_id;
                    $where[$k]['attr_id'] = $k;
                    $goods_attr_info = M('GoodsAttr')->where($where[$k])->field('id,attr_id,attr_value')->order('id asc')->find();
                    $attr_key_array_format[0]['attr_val'][$k]['id'] = $goods_attr_info['attr_id'];
                    $attr_key_array_format[0]['attr_val'][$k]['val'] = $goods_attr_info['attr_value'];
                }
            }
            // echo "<pre>";
            // print_r($attr_key_array_format);exit;
            $this->assign('attr_count', count(array_keys($attr_key_array_format)));//循环总数
            $this->assign('goodsattr_format', $goodsattr_format);
            $this->assign('attr_key_array_format', $attr_key_array_format);
        }
        $this->display();
    }
    public function goods_moresn(){
        if (IS_POST) {
            $postdata = I('post.');
            $res = D('Admin/Goods')->update_goods_moresn($postdata);//更新商品一品多码
            if($res['status'] == 1){
                $this->success('编辑成功！');
            }else{
                $this->error($res['msg']);
            }
        }else{
            $goods_id = I('id');
            if(!$goods_id){$this->error("参数错误！");}
            $map = array();$map['goods_id'] =  $goods_id;
            $goods_code = M('GoodsMorecode')->where($map)->getField('goods_sn',true);
            $goods_sns = implode(',',$goods_code);
            $this->assign('goods_sns',$goods_sns);
            $this->assign('goods_id',$goods_id);
            $this->display();
        }


    }
    
    
}
?>