<?php
/**
 * 供货商中心
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaol <1094186793@qq.com>
 */
namespace Supplier\Controller;
use Think\Controller;
class PurGoodsController extends BaseController {
    public function _initialize()
    {
        parent::_initialize();
		$supplier_info=session('suppliers_info');
        if(empty($supplier_info['id'])) $this->error('身份过期，请重新登录',U('Supplier/Register/sup_login'));
		$this->inputtype = array('text' => L('TEXT'), 'checkbox' => L('REDIO'));
        $this->assign('inputtype', $this->inputtype);
    }

    /**
     * 商品列表
     */
    public function index()
    {
        $tabid = I('param.tabid');
        if (!empty($tabid)) $this->display($tabid);
        else{
            $postdata = I('param.');
            $postdata['suppliers_id']=MID;
            $postdata['is_delete'] = 0;
            $list = $this->get_supplier_goods_list($postdata);
            $this->assign('list', $list);
            $this->assign($postdata);
            $this->display();
        }
    }
    /**
     * 回收站的商品
     */
    public function recycle()
    {
        $tabid = I('param.tabid');
        if (!empty($tabid)) $this->display($tabid);
        else {
            $postdata = I('param.');
            $postdata['is_delete'] = 1;
            $postdata['suppliers_id'] = MID;
            $list = $this->get_supplier_goods_list($postdata);
            $this->assign('list', $list);
            $this->assign($postdata);
            $this->display();
        }
    }
    private function get_supplier_goods_list($postdata){
        $name = 'Goods';
        $map = D('Admin/Goods')->index_condition($postdata);
        $map['goods_type'] = 5;
        $map['suppliers_id'] = MID;
        if (!isset($postdata['catid'])) {
            $postdata['catid'] = 0;
        }
        if (!isset($postdata['brandid'])) {
            $postdata['brandid'] = 0;
        }
        if (!isset($postdata['suppliers_id'])) {
            $postdata['suppliers_id'] = 0;
        }
        $this->getcateTree($postdata['catid'], '', $postdata['brandid'], $postdata['suppliers_id']);
        $return = $this->lists($name, $map);
        return $return;
    }

    /**
     * 删除，回收站
     * @param $is_delete 0恢复,1删除
     */
    public function recycling()
    {
        $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 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);
        }
        $postdata['publish_wait'] = 0;
        $postdata['shop_id']=MID;
        $this->assign($postdata);
        $this->assign('menu_tab',$tab_id);
        $this->assign('menu_action_current','add');
        // 获取关联包装
        $this->assign('morep_num', 0);
        $this->display($tab_id);
    }

    /**
     * 插入商品
     */
    public function insert()
    {
        $postdata = I('post.');
		$postdata['status']=0;
		$postdata['publish_wait']=0;
		$postdata['suppliers_id']=MID;
        $postdata['addtime']=NOW_TIME;
        $tab_id=$postdata['menu_tab'];
        $model = D('Admin/Goods');
        if($tab_id=='baseinfo') {
            if (false === D('Goods')->create($postdata)) {
                $this->error(D('Goods')->getError());
            }
            $id = D('Goods')->add();
            if ($id !== false) {
                $postdata['id'] = $id;
                $model->update_goodsattr($postdata, 1);//更新扩增分类
                $model->update_goods_sn($postdata, 1);//更新货号
                $model->update_goods_content($postdata, 1);//更新商品详情和seo
                $model->update_goods_package($postdata);//更新商品包装
                unset($postdata);
                if ($_POST['isajax']) $this->assign('dialog', '1');
                // $jumpUrl = $_POST['forward'] ? $_POST['forward'] : U(CONTROLLER_NAME . '/index');
                $jumpUrl =geturl('Supplier/PurGoods/edit',array('id'=>$id,'tabid'=>'otherinfo','type'=>'add'));
                $this->assign('jumpUrl', $jumpUrl);
                redirect($jumpUrl);
            } else {
                $this->error('添加失败' . ': ' . $model->getDbError());
            }
        }
    }

    /**
     * 编辑商品
     */
    public function edit()
    {
        $type='';
        $jumptype=I('param.jumptype');
        $tab_id=I('param.tabid');
        $tab_id=empty($tab_id)?'baseinfo':$tab_id;
        $id = I('get.id');
        if (!$id) $this->error(L('PARAM_ERR'));
        $map['suppliers_id']=MID;
        $map['id']=$id;
        $info = M('Goods')->where($map)->field(true)->find();
        if(!$info)$this->error('无此操作权限');
        if($tab_id=='baseinfo') {
            //获取关联分类
            $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);
                }
            }
            $this->assign('morecatarr', $morecatarr);
            $this->assign('morecatid', implode(',', $morecatidarr));
            //获取分类 类型 品牌 供货商
            $this->getNodeTree($info['cat_id'], '', $info['brand_id'], $info['suppliers_id'], $info['shop_cat_id']);
            //获取商品的长字段
            $goodscontent = M('GoodsContent')->where('goods_id = ' . $id)->find();
            $info['content'] = $goodscontent['content'];

            if($jumptype)
            {
                $this->assign('jumptype',$jumptype);
            }
        }elseif($tab_id=='otherinfo') {
            $this->get_goods_label($id);
            //获取分类 类型 品牌 供货商
            $this->getNodeTree($info['cat_id'], '', $info['brand_id'], $info['suppliers_id']);
            //获取商品的长字段
            $goodscontent = M('GoodsContent')->where('goods_id = ' . $id)->find();
            $info['content'] = $goodscontent['content'];
            $info['seotitle'] = $goodscontent['seotitle'];
            $info['seokeywords'] = $goodscontent['seokeywords'];
            $info['seodescription'] = $goodscontent['seodescription'];
            $type=I('param.type');
            if($jumptype)
            {
                $this->assign('jumptype',$jumptype);
            }
        }elseif($tab_id=='attr'){
            $this->attr_html($info['cat_id'],$id);
            $type=I('param.type');
            if($jumptype)
            {
                $this->assign('jumptype',$jumptype);
            }
        }elseif($tab_id=='photo') {
            //获取商品相册
            $moreimg = M('GoodsGallery')->where('goods_id=' . $id)->field('id,goods_img,img_desc')->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'];
                }
                $moreimgstr = implode('', $moreimgarr['goods_img']) . implode('', $moreimgarr['img_desc']);

            }
            $type=I('param.type');
            if($jumptype)
            {
                $this->assign('jumptype',$jumptype);
            }
            $this->assign('moreimg', $moreimg);
            $this->assign('moreimgstr', md5($moreimgstr));
        }
        // 获取关联包装
        $wherep['goods_id'] = $id;
        $morep_num = M('GoodsPackage')->where($wherep)->field(true)->count();
        $morep = M('GoodsPackage')->where($wherep)->field(true)->select();
        $this->assign('package', $morep);
        $this->assign('morep_num', $morep_num);
        $this->assign($info);
        $this->assign('info', $info);
        $this->assign('type',$type);
        unset($info, $morecatarr, $morecatidarr, $moreimg, $moreimgarr, $moreimgstr);
        $this->assign('menu_tab',$tab_id);
        if($type){
            $this->assign('menu_action_current','add');
        }else{
            $this->assign('menu_action_current','index');
        }
        $this->display($tab_id);
    }

    /**
     * 修改商品
     * @param string $model
     * @param string $data
     * @param string $where
     * @param string $msg
     */
    public function update($model = '', $data = '', $where = '1', $msg = '')
    {
        $type=I('get.type');
        $jumptype=I('get.jumptype');
        $model = D('Admin/Goods');
        $postdata = I('post.');
        $postdata['updatetime']=NOW_TIME;
        $id = array_unique((array)I('id', 0));
        $suppliers_id=idtoname($id[0],'Goods','suppliers_id');
        if($suppliers_id!=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 . '/index');
        $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        $tab_id=$postdata['menu_tab'];

        if($jumptype)
        {
            $savedata['status']=1;
            $savedata['publish_wait']=1;
        }
        else
        {
            $savedata['status']=0;
            $savedata['publish_wait']=0;

        }
		D('Goods')->where($where)->data($savedata)->save();
        if($tab_id=='baseinfo') {
            $data = D('Goods')->create($postdata);
            if (D('Goods')->where($where)->save($data) !== false) {
                $postdata['id'] = $id;
                $model->update_goodsattr($postdata);//更新扩增分类
                $model->update_goods_sn($postdata);//更新货号
                $model->update_goods_content($postdata);//更新商品详情和seo
                $model->update_goods_package($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']);
            }
        }elseif($tab_id=='otherinfo') {
            $checkcheckbox = array('is_best', 'is_new', 'is_hot', 'is_shipping');
            foreach ($checkcheckbox as $v) {
                if (empty($postdata[$v])) $postdata[$v] = '0';
            }
            $data = D('Goods')->create($postdata);
            if (D('Goods')->where($where)->save($data) !== false) {
                $postdata['id'] = $id;
                $model->update_goods_content($postdata);//更新商品详情和seo
                clearhomehtml($id);//更新静态缓存
                unset($data, $postdata, $newgoodscat, $newgoodsimg, $goodstype, $goodstypearr, $newgoodsattr);
                if($type)
                {
                    $jumpUrl =geturl('Supplier/PurGoods/edit',array('id'=>$id,'tabid'=>'attr','type'=>'add'));
                    $this->assign('jumpUrl', $jumpUrl);
                    $this->assign('type','add');
                    redirect($jumpUrl);
                }
                else
                {
                    $this->success($msg['success'], $msg['url'], $msg['ajax']);
                }
            } else {
                $this->error($msg['error'], $msg['url'], $msg['ajax']);
            }
        }elseif($tab_id=='attr') {
            $postdata['id'] = $id;
            $model->update_goodstype($postdata);//更新商品属性
            clearhomehtml($id);//更新静态缓存
            if($type)
            {
                $jumpUrl =geturl('Supplier/PurGoods/edit',array('id'=>$id,'tabid'=>'photo','type'=>'add'));
                $this->assign('jumpUrl', $jumpUrl);
                $this->assign('type','add');
                redirect($jumpUrl);
            }
            else
            {
                $this->success($msg['success'], $msg['url'], $msg['ajax']);
            }
        }elseif($tab_id=='photo') {
            $postdata['id'] = $id;
            $model->update_goodsimg($postdata);//更新商品相册
            clearhomehtml($id);//更新静态缓存
            $this->success($msg['success'], $msg['url'], $msg['ajax']);
        }
    }
	
	/**
     * 资料更新
     */
	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']);
		}
	}
	
	/**
     * 商品发布
     */
	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']);
		}
	}



    /**
     * 商品标签
     * @param string $goods_id
     */
    public function get_goods_label($goods_id = '')
    {
        $goods_label_link = array();
        if (!empty($goods_id)) {
            $map = array();
            $map['goods_id'] = $goods_id;
            $label_link = M('ProjectLabelLink')->field('label_id')->where($map)->select();
            if (!empty($label_link)) {
                foreach ($label_link as $key => $val) {
                    $goods_label_link[$key] = $val['label_id'];
                }
            }
        }
        $where = array();
        $where['type']=0;
        $where['status']=1;
        $goods_label = M('ProjectLabel')->where($where)->select();
        $label_arr = format_array2select($goods_label, 'label_name');
        $select_str = implode(',', $goods_label_link);
        $selectstr = md5($select_str);
        $this->assign('selectstr', $selectstr);
        $this->assign('label_arr', $label_arr);
        $this->assign('select_str', $select_str);
    }

    /**
     * 得到树节点
     * @param string $pid
     */
    private function getNodeTree($pid = '', $assign = '', $brandid = '', $suppliersid = '',$shop_cat_id='')
    {
        if (empty($pid))$pid = I('pid');
        $this->getcateTree($pid, $assign, $brandid, $suppliersid,$shop_cat_id);
        //获取所有供货商
		$smap['status']=array('gt',0);
		$smap['suppliers_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_cat_id='')
    {

        $GoodsCategory = getcache('PurchaseCategory');
        $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,brand_cat_id')->select();
        $brand_op = "<option value=''>" . L('PLEASE_SELECT') . "</option>";
		foreach ($brand as $k => $v) {
			if(!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);
        $sc_map['status']=1;
        $sc_map['shop_id']=MID;
        $PurchaseCategory = M('PurchaseCategory')->where($sc_map)->order('convert(name using gb2312) ASC')->field('id,pid,name')->select();
        $ShopsTree = new \Common\Vendor\Tree();
        $select_shopscategorys = '';
        $shopstreemini = $ShopsTree->treemini($PurchaseCategory);
        $select_shopscategorys .= $Tree->treeminioption($shopstreemini, $shop_cat_id);
        if ($assign) return $select_shopscategorys; else $this->assign('select_shopscategorys', $select_shopscategorys);
        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, 'PurchaseCategory');//获取所有子分类
            $getallparent = getallparent($goods_catid, '', 'PurchaseCategory');//获取所有父级分类
            $new_catid_array = array_unique(array_merge($getallson, explode(',', $getallparent)));
            
            if ($new_catid_array) {
                $map['id']=array('in',$new_catid_array);
				$type_ids=M('PurchaseCategory')->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()
    {
        $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')->select();
            foreach ($goodsattrstock as $k => $v) {
                $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'];
            }
            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'];
                }
            }
            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'];
                }
            }
            $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->assign('menu_action','index');
        $this->assign('tplseo_title','供货商货品_'.C('WEB_SITE_TITLE'));
        $this->display();
    }

    public function stock_update()
    {
        $postdata = I('post.');
        $data = D('Goods')->create($postdata);
        $jumpUrl = I('forward') ? I('forward') : U('PurGoods/index');
        $msg = array_merge(array('success' => L('edit_ok'), 'error' => L('edit_error'), 'url' => $jumpUrl, 'ajax' => IS_AJAX), (array)$msg);
        if (!D('Goods')->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 . '%');
        }
        $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) {
            $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->shop_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 attr_list(){
		$tabid=I('param.tabid');
		if(empty($tabid)){
			$map['shop_id']=MID;
			$list=page_list('GoodsAttribute',$map,'id desc',$field,$page_num,'',1);
			$this->assign($list);
		}
		$tabid=$tabid?$tabid:'attr_list';
        $this->display($tabid);
    }
	/**
     * 添加属性
     */
	public function attr_insert(){
		$data=I('post.');
		//判断有没有GoodsType
		$type_id=M('GoodsType')->where('shop_id='.MID)->getField('id');
		if(!$type_id){
			$add['name']=idtoname(MID,'Shops','name').'自定义属性';
			$add['shop_id']=MID;
			$add['status']=1;
			$type_id=M('GoodsType')->add($add);
		}
		$Model = M("GoodsAttribute");
		$data['shop_id']=MID;
		$data['type_id']=$type_id;
		$Model->create($data);
		$res=$Model->add();
		if($res){
			$url=U('Goods/attr_list');
			$this->success ('添加成功',$url);
		}else{
			$url=U('Goods/attr_list',array('tabid'=>'add_attr'));
			$this->success ('添加失败',$url);
		}
    }
	/**
     * 编辑属性
     */
	public function edit_attr(){
		$data=I('param.');
		if(empty($data['id'])){$this->error('参数错误');}
		$info = M('GoodsAttribute')->field(true)->find($data['id']);
		$this->assign($info);
		$this->assign('menu_action','edit_attr');
		$this->assign('menu_tab','edit_attr');
        $this->assign('menu_action_current','attr_list');
		$this->display('add_attr');
    }
	/**
     * 修改属性
     */
	public function attr_update(){
		$data=I('post.');
		if(empty($data['id'])){$this->error('参数错误');}
		$Model = M("GoodsAttribute");
		$Model->create($data);
		$res=$Model->where('id='.$data['id'])->save();
		if($res===false){
			$url=U('Goods/edit_attr',array('id'=>$data['id']));
			$this->success ('修改失败',$url);
		}else{
			$url=U('Goods/attr_list');
			$this->success ('修改成功',$url);
		}
    }
	/**
     * 弹窗添加属性
     */
    public function add_attrs(){
        $order_id = I("order_id");
        $order_goods = I("order_goods");
        $this->assign('tplseo_title', '退款审核_会员中心_' . C('WEB_SITE_TITLE'));
        $this->display();
    }
	/**
     * 添加属性
     */
    public function ajax_add_attr(){
        $return = array('status'=>0,'msg'=>'');
        $postdata = I('post.');
		//判断有没有GoodsType
		$type_id=M('GoodsType')->where('shop_id='.MID)->getField('id');
		if(!$type_id){
			$add['name']=idtoname(MID,'Shops','name').'自定义属性';
			$add['shop_id']=MID;
			$add['status']=1;
			$type_id=M('GoodsType')->add($add);
		}
		$Model = M("GoodsAttribute");
		$postdata['shop_id']=MID;
		$postdata['type_id']=$type_id;
		$Model->create($postdata);
		$res=$Model->add();
		if($res){
			$return['status'] = 1;
			$return['msg'] = '添加成功';
		}else{
			$return['msg'] = '添加失败';
		}
        $this->ajaxReturn($return);
    }
	/**
     * 删除属性
     */
	public function del_attr(){
		$postdata=I('param.');
		$return=D('Goods')->del_attr($postdata);
		if($return['status']){$return['url']=U('Shop/Goods/attr_list');}
        $this->ajaxReturn($return);
    }
    /**
     * 申请调价
     */
    public function modify_price(){
        $id = I('get.id');
        $map['suppliers_id']=MID;
        $map['id']=$id;
        $info = M('Goods')->where($map)->field('supply_price,shop_price,market_price,id,unit_name')->find();
        $packageid = I('get.packageid');
        $p_map['id'] = $packageid;
        $packageinfo='';
        if($packageid){
            $packageinfo = M('GoodsPackage')->where($p_map)->field(true)->find();
        }
        $this->assign('packageinfo',$packageinfo);
        $this->assign('info',$info);
        $this->display();
    }
}
?>