<?php

namespace app\api\controller;

use think\facade\Db;
use think\facade\Lang;

/**
 * ============================================================================
 * 
 * ============================================================================
 * 版权所有 2014-2028 浙江惠利玛产业互联网有限公司，并保留所有权利。
 * 网站地址: https://www.valimart.net/
 * ----------------------------------------------------------------------------
 * 
 * ============================================================================
 * 卖家商品控制器
 */
class Sellergoods extends MobileSeller {

    public function initialize() {
        parent::initialize(); // TODO: Change the autogenerated stub
        Lang::load(base_path() . 'home/lang/' . config('lang.default_lang') . '/sellergoodsadd.lang.php');
    }

    /**
     * @api {POST} api/Sellergoods/goods_list 出售中的商品列表
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {String} keyword 关键词
     * @apiParam {String} goods_type 商品类型 lockup违规的商品 offline仓库的商品 waitverify等待审核的商品
     * @apiParam {Int} search_type 0商品名 1货号 2商品公共ID
     * @apiParam {String} page 页码
     * @apiParam {String} pagesize 每页显示数量
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object[]} result.goods_list  商品列表
     * @apiSuccess {String} result.goods_list.goods_addtime  添加时间
     * @apiSuccess {String} result.goods_list.goods_commonid  商品公共ID
     * @apiSuccess {String} result.goods_list.goods_image  商品图片
     * @apiSuccess {String} result.goods_list.goods_lock  商品锁定 0未锁，1已锁
     * @apiSuccess {String} result.goods_list.goods_name  商品名称
     * @apiSuccess {String} result.goods_list.goods_price  商品价格
     * @apiSuccess {String} result.goods_list.goods_state  商品状态 0:下架 1:正常 10:违规（禁售）
     * @apiSuccess {String} result.goods_list.goods_storage_sum  商品库存
     * @apiSuccess {Int} result.page_total  总页数
     * @apiSuccess {Boolean} result.hasmore  是否有更多 true是false否
     */
    public function goods_list() {
        $keyword = input('post.keyword');
        $goods_type = input('post.goods_type');
        $search_type = input('post.search_type');

        $goods_model = model('goods');

        $condition = array();
        $condition[] = array('store_id', '=', $this->store_info['store_id']);
        if (trim($keyword) != '') {
            switch ($search_type) {
                case 0:
                    $condition[] = array('goods_name', 'like', '%' . trim($keyword) . '%');
                    break;
                case 1:
                    $condition[] = array('goods_serial', 'like', '%' . trim($keyword) . '%');
                    break;
                case 2:
                    $condition[] = array('goods_commonid', '=', intval($keyword));
                    break;
            }
        }

        $fields = 'gc_id,goods_commonid,goods_name,goods_price,goods_addtime,goods_image,goods_state,goods_lock';
        switch ($goods_type) {
            // 违规的商品
            case 'lockup':
                $goods_list = $goods_model->getGoodsCommonLockUpList($condition, $fields, $this->pagesize);
                break;
            //仓库的商品
            case 'offline':
                $goods_list = $goods_model->getGoodsCommonOfflineList($condition, $fields, $this->pagesize);
                break;
            //等待审核的商品
            case 'waitverify':
                $goods_list = $goods_model->getGoodsCommonWaitVerifyList($condition);
                break;
            default:
                $goods_list = $goods_model->getGoodsCommonOnlineList($condition, $fields, $this->pagesize);
                break;
        }

        // 计算库存
        $storage_array = $goods_model->calculateStorage($goods_list);

        // 整理输出的数据格式
        foreach ($goods_list as $key => $value) {
            $goods_list[$key]['goods_storage_sum'] = $storage_array[$value['goods_commonid']]['sum'];
            $goods_list[$key]['goods_addtime'] = date('Y-m-d', $goods_list[$key]['goods_addtime']);
            $goods_list[$key]['goods_image'] = goods_cthumb($goods_list[$key]['goods_image']);
        }

        $result = array_merge(array('goods_list' => $goods_list), mobile_page($goods_model->page_info));
        ds_json_encode(10000, '', $result);
    }

    /**
     * @api {POST} api/Sellergoods/goods_show 商品上架
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} commonid 商品公共ID
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function goods_show() {
        if ($this->store_info['store_state'] != 1) {
            ds_json_encode(10001, lang('wait_administrator_review_goods'));
        }

        $commonid = input('param.commonid');
        if (!preg_match('/^[\d,]+$/i', $commonid)) {
            ds_json_encode(10001, lang('para_error'));
        }
        $commonid_array = explode(',', $commonid);
        if ($this->store_info['store_state'] != 1) {
            ds_json_encode(10001, lang('store_goods_index_goods_show_fail'));
        }
        $return = model('goods')->editProducesOnline(array(array('goods_commonid', 'in', $commonid_array), array('store_id', '=', $this->store_info['store_id'])));
        if ($return) {
            // 添加操作日志
            $this->recordSellerlog('商品上架，平台货号：' . $commonid);
            ds_json_encode(10000, '', 1);
        } else {
            ds_json_encode(10001, lang('store_goods_index_goods_show_fail'));
        }
    }

    /**
     * @api {POST} api/Sellergoods/goods_unshow 商品下架
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} commonid 商品公共ID
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function goods_unshow() {
        //参考PC端代码
        $common_id = $this->checkRequestCommonId(input('param.commonid'));
        $commonid_array = explode(',', $common_id);
        $goods_model = model('goods');
        $where = array();
        $where[] = array('goods_commonid', 'in', $commonid_array);
        $where[] = array('store_id', '=', $this->store_info['store_id']);
        $return = model('goods')->editProducesOffline($where);
        if ($return) {
            // 更新优惠套餐状态关闭
            $goods_list = $goods_model->getGoodsList($where, 'goods_id');
            if (!empty($goods_list)) {
                $goodsid_array = array();
                foreach ($goods_list as $val) {
                    $goodsid_array[] = $val['goods_id'];
                }
                model('pbundling')->editBundlingCloseByGoodsIds(array(array('goods_id', 'in', $goodsid_array)));
            }
            // 添加操作日志
            $this->recordSellerlog('商品下架，平台货号：' . $common_id);
            ds_json_encode(10000, '', 1);
        } else {
            ds_json_encode(10001, lang('store_goods_index_goods_unshow_fail'));
        }
    }

    /**
     * 验证commonid
     */
    private function checkRequestCommonId($common_ids) {
        if (!preg_match('/^[\d,]+$/i', $common_ids)) {
            ds_json_encode(10001, lang('para_error'));
        }
        return $common_ids;
    }

    /**
     * @api {POST} api/Sellergoods/goods_unshow 商品删除
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} commonid 商品公共ID
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function drop_goods() {
        $commonid = input('param.commonid');
        $common_id = $this->checkRequestCommonId($commonid);
        $commonid_array = explode(',', $common_id);

        $goods_model = model('goods');
        $where = array();
        $where[] = array('goods_commonid', 'in', $commonid_array);
        $where[] = array('store_id', '=', $this->store_info['store_id']);
        $return = $goods_model->delGoodsNoLock($where);

        if ($return) {
            // 添加操作日志
            $this->recordSellerlog('删除商品，平台货号：' . $common_id);
            ds_json_encode(10000, '', 1);
        } else {
            ds_json_encode(10001, lang('store_goods_index_goods_del_fail'));
        }
    }

    /**
     * @api {POST} api/Sellergoods/get_common_data 获取新增/编辑商品的公共数据
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} class_id 商品分类ID
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object} result.attr_list  属性列表，键为属性名id
     * @apiSuccess {String} result.attr_list.attr_name  属性名
     * @apiSuccess {Object[]} result.attr_list.value  属性值列表
     * @apiSuccess {Int} result.attr_list.value.attrvalue_id  属性值id
     * @apiSuccess {String} result.attr_list.value.attrvalue_name  属性值名称
     * @apiSuccess {Object[]} result.brand_list  品牌列表（返回字段参考brand表）
     * @apiSuccess {Object} result.goods_class  商品分类
     * @apiSuccess {Int} result.goods_class.gc_id  商品分类ID
     * @apiSuccess {Int} result.goods_class.gc_id_1  一级商品分类ID
     * @apiSuccess {Int} result.goods_class.gc_id_2  二级商品分类ID
     * @apiSuccess {Int} result.goods_class.gc_id_3  三级商品分类ID
     * @apiSuccess {Int} result.goods_class.gc_virtual  是否允许发布虚拟商品（0否1是）
     * @apiSuccess {String} result.goods_class.gctag_name  商品分类名称
     * @apiSuccess {String} result.goods_class.gctag_value  商品分类标签
     * @apiSuccess {Int} result.goods_class.type_id  类型ID
     * @apiSuccess {Object} result.sign_i  规格数量
     * @apiSuccess {Object} result.spec_json  规格值列表（键为规格名id，值中的键为规格值id）
     * @apiSuccess {String} result.spec_json.spvalue_color  规格值颜色
     * @apiSuccess {String} result.spec_json.spvalue_name  规格值
     * @apiSuccess {Object} result.spec_list  按规格名分类的规格列表（键为规格名id）
     * @apiSuccess {String} result.spec_list.sp_name  规格名
     * @apiSuccess {Object[]} result.spec_list.value  规格值列表
     * @apiSuccess {String} result.spec_list.value .spvalue_color  规格值颜色
     * @apiSuccess {String} result.spec_list.value .spvalue_name  规格值
     * @apiSuccess {Int} result.spec_list.value .spvalue_name  规格值id
     */
    public function get_common_data() {
        $result = array();
        $class_id = intval(input('param.class_id'));

        $goods_class = model('goodsclass')->getGoodsclassLineForTag($class_id);
        $result['goods_class'] = $goods_class;

        $type_model = model('type');
        // 获取类型相关数据
        $typeinfo = $type_model->getAttribute($goods_class['type_id'], $this->store_info['store_id'], $class_id);
        list($spec_json, $spec_list, $attr_list, $brand_list) = $typeinfo;
        $result['spec_json'] = $spec_json;
        $result['sign_i'] = count($spec_list);
        $result['spec_list'] = $spec_list;
        $result['attr_list'] = $attr_list;
        $result['brand_list'] = $brand_list;
        ds_json_encode(10000, '', $result);
    }

    /**
     * @api {POST} api/Sellergoods/edit_goods 获取商品信息
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} class_id 商品分类ID
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object} result.area  商品地区信息（返回字段参考area表）
     * @apiSuccess {Int[]} result.attr_checked  选择的属性值id
     * @apiSuccess {Object} result.goods  商品信息（返回字段参考goodscommon表）
     * @apiSuccess {Int} result.goods.goods_storage  商品总库存
     * @apiSuccess {Object[]} result.goods.mb_body  商品详情
     * @apiSuccess {String} result.goods.mb_body.type  商品详情类型（image图片text文字）
     * @apiSuccess {String} result.goods.mb_body.value  商品详情值
     * @apiSuccess {String} result.goods.mb_body.value_url  商品详情图片链接
     * @apiSuccess {String} result.goods.goods_image_url  商品图片
     * @apiSuccess {Object} result.sp_value  规格值列表（键为规格值id升序排列的字符串）
     * @apiSuccess {Int} result.sp_value.alarm  库存预警值
     * @apiSuccess {Int} result.sp_value.color  颜色规格id
     * @apiSuccess {Int} result.sp_value.id  商品id
     * @apiSuccess {String} result.sp_value.label  规格名（用|分隔）
     * @apiSuccess {Float} result.sp_value.marketprice  市场价
     * @apiSuccess {Float} result.sp_value.price  价格
     * @apiSuccess {String} result.sp_value.sku  货号
     * @apiSuccess {Object} result.sp_value.sp_value  规格值列表（键为规格值id，值为规格值名称）
     * @apiSuccess {Int} result.sp_value.stock  库存
     */
    public function edit_goods() {
        $common_id = intval(input('param.commonid'));
        if ($common_id <= 0) {
            ds_json_encode(10001, lang('param_error'));
        }
        $goods_model = model('goods');
        $goodscommon_info = $goods_model->getGoodsCommonInfoByID($common_id);
        if (empty($goodscommon_info) || $goodscommon_info['store_id'] != $this->store_info['store_id'] || $goodscommon_info['goods_lock'] == 1) {
            ds_json_encode(10001, lang('goods_not_exist_or_lock'));
        }
        $result = array();
        $where = array('goods_commonid' => $common_id, 'store_id' => $this->store_info['store_id']);
        $goodscommon_info['goods_storage'] = $goods_model->getGoodsSum($where, 'goods_storage');
        $goodscommon_info['spec_name'] = unserialize($goodscommon_info['spec_name']);
        if ($goodscommon_info['mobile_body'] != '') {
            $goodscommon_info['mb_body'] = unserialize($goodscommon_info['mobile_body']);
            if (is_array($goodscommon_info['mb_body'])) {
                $mobile_body = '[';
                foreach ($goodscommon_info['mb_body'] as $val) {
                    $mobile_body .= '{"type":"' . $val['type'] . '","value":"' . $val['value'] . '"},';
                }
                $mobile_body = rtrim($mobile_body, ',') . ']';
            }
            $goodscommon_info['mobile_body'] = $mobile_body;
        }
        $goodscommon_info['goods_image_url'] = goods_thumb($goodscommon_info, 240);
        $area = model('area')->getAreaInfo(array('area_id' => $goodscommon_info['areaid_2'] ? $goodscommon_info['areaid_2'] : $goodscommon_info['areaid_1']));
        $result['area'] = $area;


        $type_model = model('type');

        // 取得商品规格的输入值
        $goods_array = $goods_model->getGoodsList($where, 'goods_id,goods_marketprice,goods_price,goods_weight,goods_storage,goods_serial,goods_storage_alarm,goods_spec,color_id,virtual_content');

        $sp_value = array();
        if (is_array($goods_array) && !empty($goods_array)) {
            $goodscommon_info['goods_weight'] = $goods_array[0]['goods_weight'];
            switch($goodscommon_info['virtual_type']){
                case 1:
                    $goodscommon_info['virtual_type_text']='卡券商品';
                    $goodscommon_info['vc_card'] = $goods_array[0]['virtual_content'];
                    if($goodscommon_info['vc_card']){
                        $card_list=explode("\r\n",$goodscommon_info['vc_card']);
                        $goodscommon_info['card_num'] = count($card_list);
                    }
                    break;
                case 2:
                    $goodscommon_info['virtual_type_text']='网盘商品';
                    $goodscommon_info['vc_pan'] = $goods_array[0]['virtual_content'];
                    break;
                case 3:
                    $goodscommon_info['virtual_type_text']='下载商品';
                    $goodscommon_info['vc_file'] = $goods_array[0]['virtual_content'];
                    break;
                default:
                    $goodscommon_info['virtual_type_text']='核销商品';
            }
            // 取得已选择了哪些商品的属性
            $attr_checked_l = $type_model->typeRelatedList('goodsattrindex', array(
                'goods_id' => intval($goods_array[0]['goods_id'])
                    ), 'attrvalue_id');
            $attr_checked = array();
            if (is_array($attr_checked_l) && !empty($attr_checked_l)) {
                foreach ($attr_checked_l as $val) {
                    $attr_checked [] = $val ['attrvalue_id'];
                }
            }
            $result['attr_checked'] = $attr_checked;

            $spec_checked = array();
            foreach ($goods_array as $k => $v) {
                $a = unserialize($v['goods_spec']);
                if (!empty($a)) {
                    foreach ($a as $key => $val) {
                        $spec_checked[$key]['id'] = $key;
                        $spec_checked[$key]['name'] = addslashes($val);
                    }
                    $matchs = array_keys($a);
                    sort($matchs);
                    $id = str_replace(',', '', implode(',', $matchs));
                    $sp_value[$id] = array(
                        'sp_value' => $a,
                        'label' => implode('|', array_values($a)),
                        'color' => $v['color_id'],
                        'marketprice' => $v['goods_marketprice'],
                        'price' => $v['goods_price'],
                        'id' => $v['goods_id'],
                        'goods_weight' => $v['goods_weight'],
                        'stock' => $v['goods_storage'],
                        'alarm' => $v['goods_storage_alarm'],
                        'sku' => $v['goods_serial'],
                    );
                    switch($goodscommon_info['virtual_type']){
                        case 1:
                            $sp_value[$id]['vc_card'] = $v['virtual_content'];
                            if($sp_value[$id]['vc_card']){
                                $card_list=explode("\r\n",$sp_value[$id]['vc_card']);
                                $sp_value[$id]['vc_card']['card_num'] = count($card_list);
                            }
                            break;
                        case 2:
                            $sp_value[$id]['vc_pan'] = $v['virtual_content'];
                            break;
                        case 3:
                            $sp_value[$id]['vc_file'] = $v['virtual_content'];
                            break;
                    }
                }
            }
            $result['spec_checked'] = $spec_checked;
        }
        $goodscommon_info['goodsvideo_url'] = goods_video($goodscommon_info['goodsvideo_name']);
        $result['goods'] = $goodscommon_info;
        $result['sp_value'] = $sp_value;

        // 实例化店铺商品分类模型
        $store_goods_class = model('storegoodsclass')->getClassTree(array('store_id' => $this->store_info['store_id'], 'storegc_state' => '1'));

        //处理商品所属分类
        $store_goods_class_tmp = array();
        if (!empty($store_goods_class)) {
            foreach ($store_goods_class as $k => $v) {
                $store_goods_class_tmp[$v['storegc_id']] = $v;
                if (isset($v['child'])) {
                    foreach ($v['child'] as $son_k => $son_v) {
                        $store_goods_class_tmp[$son_v['storegc_id']] = $son_v;
                    }
                }
            }
        }
        $result['store_goods_class'] = $store_goods_class_tmp;
        $goodscommon_info['goods_stcids'] = trim($goodscommon_info['goods_stcids'], ',');
        $goods_stcids = empty($goodscommon_info['goods_stcids']) ? array() : explode(',', $goodscommon_info['goods_stcids']);
        $goods_stcids_tmp = $goods_stcids_new = array();
        if (!empty($goods_stcids)) {
            foreach ($goods_stcids as $k => $v) {
                if (isset($store_goods_class_tmp[$v])) {
                    $storegc_parent_id = $store_goods_class_tmp[$v]['storegc_parent_id'];
                } else {
                    $storegc_parent_id = 0;
                }
                //分类进行分组，构造为array('1'=>array(5,6,8));
                if ($storegc_parent_id > 0) {//如果为二级分类，则分组到父级分类下
                    $goods_stcids_tmp[$storegc_parent_id][] = $v;
                } elseif (empty($goods_stcids_tmp[$v])) {//如果为一级分类而且分组不存在，则建立一个空分组数组
                    $goods_stcids_tmp[$v] = array();
                }
            }
            foreach ($goods_stcids_tmp as $k => $v) {
                if (!empty($v) && count($v) > 0) {
                    $goods_stcids_new = array_merge($goods_stcids_new, $v);
                } else {
                    $goods_stcids_new[] = $k;
                }
            }
        }
        $result['store_class_goods'] = $goods_stcids_new;



        // F码
        if ($goodscommon_info['is_goodsfcode'] == 1) {
            $fcode_array = model('goodsfcode')->getGoodsfcodeList(array('goods_commonid' => $goodscommon_info['goods_commonid']));
            $result['fcode_array'] = $fcode_array;
        }
        ds_json_encode(10000, '', $result);
    }

    /**
     * @api {POST} api/Sellergoods/video_upload 上传商品视频
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {File} refund_pic 图片
     * @apiParam {String} name 文件表单名
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {String} result.path  文件名
     * @apiSuccess {String} result.url  文件链接
     */
    public function video_upload() {
        $store_id = $this->store_info['store_id'];
        $save_name = $store_id . '_' . date('YmdHis') . rand(10000, 99999) . '.mp4';

        $file_name = input('post.name');
        $upload_path = ATTACH_GOODS . DIRECTORY_SEPARATOR . $store_id;

        $res = ds_upload_pic($upload_path, $file_name, $save_name, 'mp4');
        if ($res['code']) {
            $save_name = $res['data']['file_name'];
            $data = array();
            $data ['url'] = goods_video($save_name);
            $data ['name'] = $save_name;

            $goods_model = model('goods');
            $goods_model->addGoodsVideo(array(
                'store_id' => $store_id,
                'store_name' => $this->store_info['store_name'],
                'goodsvideo_name' => $save_name,
                'goodsvideo_add_time' => TIMESTAMP
            ));
            ds_json_encode(10000, '', array('url' => goods_video($save_name), 'path' => $save_name));
        } else {
            ds_json_encode(10001, $res['msg']);
        }
    }

    /**
     * @api {POST} api/Sellergoods/image_upload 上传商品图片
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {File} refund_pic 图片
     * @apiParam {String} name 文件表单名
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {String} result.path  文件名
     * @apiSuccess {String} result.url  文件链接
     */
    public function image_upload() {
        // 判断图片数量是否超限
        $album_model = model('album');
        $album_limit = $this->store_grade['storegrade_album_limit'];
        if ($album_limit > 0) {
            $album_count = $album_model->getCount(array('store_id' => $this->store_info['store_id']));

            if ($album_count >= $album_limit) {
                ds_json_encode(10001, lang('store_goods_album_climit'));
            }
        }
        $class_info = $album_model->getOne(array('store_id' => $this->store_info['store_id'], 'aclass_isdefault' => 1), 'albumclass');


        $store_id = $this->store_info['store_id'];
        /**
         * 上传图片
         */
        $time=TIMESTAMP;
        //上传文件保存路径
        $upload_path = ATTACH_GOODS . '/' . $store_id . '/' . date('Ymd',$time);
        $save_name = $this->store_info['store_id'] . '_' . date('YmdHis',$time) . rand(10000, 99999);
        $file_name = input('post.name');

        $result = upload_albumpic($upload_path, $file_name, $save_name);
        if ($result['code'] == '10000') {
            $img_path = $result['result'];
            list($width, $height, $type, $attr) = getimagesize($img_path);
            $img_path = substr(strrchr($img_path, "/"), 1);
        } else {
            //未上传图片或出错不做后面处理
            ds_json_encode(10001, lang('ds_common_op_fail'));
        }

        // 存入相册
        $insert_array = array();
        $insert_array['apic_name'] = $img_path;
        $insert_array['apic_tag'] = '';
        $insert_array['aclass_id'] = $class_info['aclass_id'];
        $insert_array['apic_cover'] = $img_path;
        $insert_array['apic_size'] = intval($_FILES[$file_name]['size']);
        $insert_array['apic_spec'] = $width . 'x' . $height;
        $insert_array['apic_uploadtime'] = $time;
        $insert_array['store_id'] = $store_id;
        $result = model('album')->addAlbumpic($insert_array);



        // 整理为json格式
        ds_json_encode(10000, '', array('url' => goods_cthumb($img_path, 480, $this->store_info['store_id']), 'path' => $img_path));
    }

    /**
     * @api {POST} api/Sellergoods/add_spec 新增规格值
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {String} name 规格值
     * @apiParam {Int} gc_id 商品分类ID
     * @apiParam {Int} sp_id 规格名ID
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Int} result.value_id  规格值id
     */
    public function add_spec() {
        $name = trim(input('param.name'));
        $gc_id = intval(input('param.gc_id'));
        $sp_id = intval(input('param.sp_id'));
        if ($name == '' || $gc_id <= 0 || $sp_id <= 0) {
            ds_json_encode(10000, lang('param_error'));
        }
        $insert = array(
            'spvalue_name' => $name, 'sp_id' => $sp_id, 'gc_id' => $gc_id, 'store_id' => $this->store_info['store_id'],
            'spvalue_color' => null, 'spvalue_sort' => 0,
        );
        $value_id = model('spec')->addSpecvalue($insert);
        if ($value_id) {
            ds_json_encode(10000, '', array('value_id' => $value_id));
        } else {
            ds_json_encode(10001, lang('ds_common_op_fail'));
        }
    }

    /**
     * @api {POST} api/Sellergoods/save_goods 保存商品信息
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} commonid 商品公共ID
     * @apiParam {Int} class_id 商品分类ID
     * @apiParam {Object} goods 商品信息
     * @apiParam {String} goods.goods_name 商品名称
     * @apiParam {String} goods.goods_advword 商品广告
     * @apiParam {Int} goods.brand_id 商品品牌ID
     * @apiParam {String} goods.brand_name 商品品牌名称
     * @apiParam {String} goods.goods_image 商品图片
     * @apiParam {Float} goods.goods_price 商品价格
     * @apiParam {Float} goods.goods_marketprice 商品市场价
     * @apiParam {Float} goods.goods_costprice 商品成本价
     * @apiParam {Int} goods.goods_discount 商品折扣
     * @apiParam {String} goods.goods_serial 商品货号
     * @apiParam {Int} goods.goods_storage 商品库存
     * @apiParam {Int} goods.goods_storage_alarm 商品库存预警值
     * @apiParam {Int} goods.goods_commend 商品推荐（0否1是）
     * @apiParam {Int} goods.goods_state 商品状态（0下架1上架）
     * @apiParam {Int} goods.goods_shelftime 上架时间（unix时间戳）
     * @apiParam {Int} goods.goods_vat 是否开增值税发票（0否1是）
     * @apiParam {Int} goods.areaid_1 省ID
     * @apiParam {Int} goods.areaid_2 市ID
     * @apiParam {Int} goods.transport_id 售卖地区ID
     * @apiParam {String} goods.transport_title 售卖地区名称
     * @apiParam {Float} goods.goods_freight 商品运费
     * @apiParam {Int} goods.is_virtual 是否虚拟商品（0否1是）
     * @apiParam {Int} goods.virtual_indate 虚拟商品有效期（unix时间戳）
     * @apiParam {Int} goods.virtual_limit 虚拟商品购买上限（1-10）
     * @apiParam {Int} goods.virtual_invalid_refund 是否支持过期退款（0否1是）
     * @apiParam {Int} goods.is_goodsfcode 是否F码商品（0否1是）
     * @apiParam {Int} goods.is_appoint 是否预约商品（0否1是）
     * @apiParam {Int} goods.appoint_satedate 发售时间（unix时间戳）
     * @apiParam {Int[]} sgcate_id 店铺分类ID列表
     * @apiParam {Object} spec 商品规格（键为规格值id升序排列的字符串）
     * @apiParam {Int} spec.goods_id 商品ID
     * @apiParam {Float} spec.goods_price 商品价格
     * @apiParam {Float} spec.goods_marketprice 商品市场价
     * @apiParam {Int} spec.goods_storage 商品库存
     * @apiParam {Int} spec.goods_storage_alarm 库存预警值
     * @apiParam {String[]} spec.sp_value 商品规格值列表
     * @apiParam {Int} spec.color 颜色规格值ID
     * @apiParam {Int[]} attr 属性ID列表
     * @apiParam {Object[]} goods_body  商品详情
     * @apiParam {String} goods_body.mb_body.type  商品详情类型（image图片text文字）
     * @apiParam {String} goods_body.mb_body.value  商品详情值
     * @apiParam {String} result.goods.mb_body.value_url  商品详情图片链接
     * @apiParam {Object} sp_name （键为规格名id，值为规格名）
     * @apiParam {Object} sp_val （键为规格名id，值中的键为规格值id，值中的值为规格值）
     * @apiParam {Int} g_fccount F码数量
     * @apiParam {String} g_fcprefix F码前缀
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     */
    public function save_goods() {
        $common_id = intval(input('param.commonid'));
        $if_add = $common_id ? false : true;
        $gc_id = intval(input('post.class_id'));

        // 验证商品分类是否存在且商品分类是否为最后一级
        $data = model('goodsclass')->getGoodsclassForCacheModel();
        if (!isset($data[$gc_id]) || isset($data[$gc_id]['child']) || isset($data[$gc_id]['childchild'])) {
            ds_json_encode(10001, lang('store_goods_index_again_choose_category1'));
        }

        // 三方店铺验证是否绑定了该分类
        if (!check_platform_store()) {
            //商品分类 提供批量显示所有分类插件
            $storebindclass_model = model('storebindclass');
            $goods_class = model('goodsclass')->getGoodsclassForCacheModel();
            $condition = array();
            $condition[] = array('store_id', '=', $this->store_info['store_id']);
            $class_2 = isset($goods_class[$gc_id]['gc_parent_id']) ? $goods_class[$gc_id]['gc_parent_id'] : 0;
            $class_1 = isset($goods_class[$class_2]['gc_parent_id']) ? $goods_class[$class_2]['gc_parent_id'] : 0;
            $condition_class_1 = array(array('class_1', '=', ($class_1 > 0) ? $class_1 : (($class_2 > 0) ? $class_2 : $gc_id)));
            $condition_class_2 = array(array('class_2', '=', ($class_1 > 0) ? $class_2 : (($class_2 > 0) ? $gc_id : 0)));
            $condition_class_3 = array(array('class_3', '=', ($class_1 > 0 && $class_2 > 0) ? $gc_id : 0));
            $bind_info = $storebindclass_model->getStorebindclassInfo(array_merge($condition, $condition_class_1, $condition_class_2, $condition_class_3));
            if (empty($bind_info)) {
                $condition_class_3 = array(array('class_3', '=', 0));
                $bind_info = $storebindclass_model->getStorebindclassInfo(array_merge($condition, $condition_class_1, $condition_class_2, $condition_class_3));
                if (empty($bind_info)) {
                    $condition_class_2 = array(array('class_2', '=', 0));
                    $condition_class_3 = array(array('class_3', '=', 0));
                    $bind_info = $storebindclass_model->getStorebindclassInfo(array_merge($condition, $condition_class_1, $condition_class_2, $condition_class_3));
                    if (empty($bind_info)) {
                        $condition_class_1 = array(array('class_1', '=', 0));
                        $condition_class_2 = array(array('class_2', '=', 0));
                        $condition_class_3 = array(array('class_3', '=', 0));
                        $bind_info = $storebindclass_model->getStorebindclassInfo(array_merge($condition, $condition_class_1, $condition_class_2, $condition_class_3));
                        if (empty($bind_info)) {
                            ds_json_encode(10001, lang('store_goods_index_again_choose_category2'));
                        }
                    }
                }
            }
        }
        // 分类信息
        $goods_class = model('goodsclass')->getGoodsclassLineForTag(intval($gc_id));
        $goods_model = model('goods');

        $update_common = array();
        $update_common['goods_name'] = input('post.goods.goods_name');
        $update_common['goods_advword'] = input('post.goods.goods_advword');
        $update_common['gc_id'] = $gc_id;
        $update_common['gc_id_1'] = isset($goods_class['gc_id_1']) ? intval($goods_class['gc_id_1']) : 0;
        $update_common['gc_id_2'] = isset($goods_class['gc_id_2']) ? intval($goods_class['gc_id_2']) : 0;
        $update_common['gc_id_3'] = isset($goods_class['gc_id_3']) ? intval($goods_class['gc_id_3']) : 0;
        $update_common['gc_name'] = $goods_class['gctag_name'];
        $update_common['brand_id'] = input('post.goods.brand_id');
        $update_common['brand_name'] = input('post.goods.brand_name');
        $update_common['type_id'] = $goods_class['type_id'];
        $update_common['goods_image'] = input('post.goods.goods_image');
        $update_common['goodsvideo_name'] = input('post.goods.goodsvideo_name');
        $update_common['goods_price'] = floatval(input('post.goods.goods_price'));
        $update_common['goods_marketprice'] = floatval(input('post.goods.goods_marketprice'));
        $update_common['goods_costprice'] = floatval(input('post.goods.goods_costprice'));
        $update_common['goods_discount'] = floatval(input('post.goods.goods_discount'));
        $update_common['goods_serial'] = input('post.goods.goods_serial', '');
        $update_common['goods_storage_alarm'] = intval(input('post.goods.goods_storage_alarm'));
        $update_common['goods_attr'] = !empty(input('post.attr/a')) ? serialize(input('post.attr/a')) : '';
        // 序列化保存手机端商品描述数据
        $mobile_body = serialize(input('post.goods_body/a'));

        $update_common['mobile_body'] = $mobile_body;
        $update_common['goods_commend'] = intval(input('post.goods.goods_commend'));
        $update_common['goods_state'] = ($this->store_info['store_state'] != 1) ? 0 : intval(input('post.goods.goods_state'));            // 店铺关闭时，商品下架
        $update_common['goods_shelftime'] = input('post.goods.goods_shelftime', 0);
        $update_common['goods_verify'] = (config('ds_config.goods_verify') == 1) ? 10 : 1;
        $update_common['spec_name'] = !empty(input('post.spec/a')) ? serialize(input('post.sp_name/a')) : serialize(null);
        $update_common['spec_value'] = !empty(input('post.spec/a')) ? serialize(input('post.sp_val/a')) : serialize(null);
        $update_common['goods_vat'] = intval(input('post.goods.goods_vat'));
        $update_common['areaid_1'] = intval(input('post.goods.areaid_1'));
        $update_common['areaid_2'] = intval(input('post.goods.areaid_2'));
        $update_common['transport_id'] = intval(input('post.goods.transport_id')); // 售卖区域
        $update_common['transport_title'] = input('post.goods.transport_title');
        $update_common['goods_freight'] = floatval(input('post.goods.goods_freight'));




        //查询店铺商品分类
        $goods_stcids_arr = array();
        $sgcate_id_array = input('post.sgcate_id/a'); #获取数组
        if (!empty($sgcate_id_array)) {
            $sgcate_id_arr = array();
            foreach ($sgcate_id_array as $k => $v) {
                if ($v) {
                    $sgcate_id_arr[] = intval($v);
                }
            }
            if (!empty($sgcate_id_arr)) {
                $sgcate_id_arr = array_unique($sgcate_id_arr);
                $store_goods_class = model('storegoodsclass')->getStoregoodsclassList(array(array('store_id', '=', $this->store_info['store_id']), array('storegc_id', 'in', $sgcate_id_arr), array('storegc_state', '=', '1')));
                if (!empty($store_goods_class)) {
                    foreach ($store_goods_class as $k => $v) {
                        if ($v['storegc_id'] > 0) {
                            $goods_stcids_arr[] = $v['storegc_id'];
                        }
                        if ($v['storegc_parent_id'] > 0) {
                            $goods_stcids_arr[] = $v['storegc_parent_id'];
                        }
                    }
                    $goods_stcids_arr = array_unique($goods_stcids_arr);
                    sort($goods_stcids_arr);
                }
            }
        }
        if (empty($goods_stcids_arr)) {
            $update_common['goods_stcids'] = '';
        } else {
            $update_common['goods_stcids'] = ',' . implode(',', $goods_stcids_arr) . ',';
        }
        $update_common['is_virtual'] = intval(input('post.goods.is_virtual'));
        $update_common['virtual_type'] = $update_common['is_virtual']?intval(input('post.goods.virtual_type')):0;
        $update_common['virtual_indate'] = input('post.goods.virtual_indate');  // 当天的最后一秒结束
        $update_common['virtual_limit'] = intval(input('post.goods.virtual_limit')) > 10 || intval(input('post.goods.virtual_limit')) < 0 ? 10 : intval(input('post.goods.virtual_limit'));
        $update_common['virtual_invalid_refund'] = intval(input('post.goods.virtual_invalid_refund'));
        $update_common['is_goodsfcode'] = $update_common['is_virtual'] ? 0 : intval(input('post.goods.is_goodsfcode'));
        $update_common['is_appoint'] = $update_common['is_virtual'] ? 0 : intval(input('post.goods.is_appoint'));     // 只有库存为零的商品可以预约
        $update_common['appoint_satedate'] = $update_common['is_appoint'] == 1 ? input('post.goods.appoint_satedate') : '';   // 预约商品的销售时间
        $update_common['is_platform_store'] = in_array($this->store_info['store_id'], model('store')->getOwnShopIds()) ? 1 : 0;

        if ($update_common['is_virtual']) {
            if (!$update_common['virtual_indate'] && $update_common['virtual_type']==0) {
                ds_json_encode(10001, lang('prompt_information9'));
            }
            if (!$update_common['virtual_limit'] || $update_common['virtual_limit'] < 1 || $update_common['virtual_limit'] > 10) {
                ds_json_encode(10001, lang('virtual_goods_instructions5'));
            }
        }
        if ($update_common['is_appoint']) {
            if (!$update_common['appoint_satedate']) {
                ds_json_encode(10001, lang('prompt_information9'));
            }
        }

        if (!$if_add) {//编辑
            $sellergoodsonline_validate = ds_validate('sellergoodsonline');
            if (!$sellergoodsonline_validate->scene('edit_save_goods')->check($update_common)) {
                ds_json_encode('10001', $sellergoodsonline_validate->getError());
            }
        } else {

            // 保存数据
            $update_common['store_id'] = $this->store_info['store_id'];
            $update_common['store_name'] = $this->store_info['store_name'];
            $update_common['goods_addtime'] = TIMESTAMP;
            $goods_validate = ds_validate('sellergoodsadd');
            if (!$goods_validate->scene('save_goods')->check($update_common)) {
                ds_json_encode(10001, $goods_validate->getError());
            }
        }
        // 开始事务
        Db::startTrans();
        try {
            $goods_model->lock=true;
            if ($if_add) {
                $common_id = $goods_model->addGoodsCommon($update_common);
                if (!$common_id) {
                    throw new \think\Exception(lang('store_goods_index_goods_add_fail'), 10006);
                }
            }
            $goodsgift_model = model('goodsgift');
            // 清除原有规格数据
            $type_model = model('type');
            $type_model->delGoodsAttr(array('goods_commonid' => $common_id));





            // 更新商品规格
            $goodsid_array = array();
            $colorid_array = array();
            $spec_array = input('post.spec/a'); #获取数组
            if (is_array($spec_array) && !empty($spec_array)) {
                foreach ($spec_array as $value) {
                    if ($value) {
                        $value['goods_price'] = abs(floatval($value['goods_price']));
                        $value['goods_marketprice'] = isset($value['goods_marketprice']) ? abs(floatval($value['goods_marketprice'])) : 0;
                        $value['goods_weight'] = isset($value['goods_weight']) ? abs(floatval($value['goods_weight'])) : 0;
                        $value['goods_storage'] = abs(intval($value['goods_storage']));
                        $value['goods_storage_alarm'] = abs(intval($value['goods_storage_alarm']));
                        if (!$value['goods_price']) {
                            throw new \think\Exception(lang('store_goods_index_goods_price_null'), 10006);
                        }
                        if ($value['goods_price'] > $value['goods_marketprice'] && $value['goods_marketprice'] > 0) {
                            throw new \think\Exception(lang('not_higher_than'), 10006);
                        }
                        $goods_info = $goods_model->getGoodsInfo(array('goods_id' => $value['goods_id'], 'goods_commonid' => $common_id, 'store_id' => $this->store_info['store_id']), 'goods_id');
                        if (!empty($goods_info)) {
                            $goods_id = $goods_info['goods_id'];
                            $update = array();
                            $update['goods_commonid'] = $common_id;
                            $update['goods_name'] = $update_common['goods_name'] . ' ' . implode(' ', $value['sp_value']);
                            $update['goods_advword'] = $update_common['goods_advword'];
                            $update['store_id'] = $this->store_info['store_id'];
                            $update['store_name'] = $this->store_info['store_name'];
                            $update['gc_id'] = $update_common['gc_id'];
                            $update['gc_id_1'] = $update_common['gc_id_1'];
                            $update['gc_id_2'] = $update_common['gc_id_2'];
                            $update['gc_id_3'] = $update_common['gc_id_3'];
                            $update['brand_id'] = $update_common['brand_id'];
                            $update['goods_price'] = $value['goods_price'];
                            $update['goods_marketprice'] = (!isset($value['goods_marketprice']) || $value['goods_marketprice'] == 0) ? $update_common['goods_marketprice'] : $value['goods_marketprice'];
                            $update['goods_serial'] = isset($value['goods_serial']) ? $value['goods_serial'] : '';
                            $update['goods_storage_alarm'] = isset($value['goods_storage_alarm']) ? intval($value['goods_storage_alarm']) : 0;
                            $update['goods_spec'] = serialize($value['sp_value']);
                            $update['goods_storage'] = $value['goods_storage'];
                            $update['goods_weight'] = isset($value['goods_weight']) ? $value['goods_weight'] : 0;
                            $update['goods_state'] = $update_common['goods_state'];
                            $update['goods_verify'] = $update_common['goods_verify'];
                            $update['goods_edittime'] = TIMESTAMP;
                            $update['areaid_1'] = $update_common['areaid_1'];
                            $update['areaid_2'] = $update_common['areaid_2'];
                            $update['color_id'] = isset($value['color']) ? intval($value['color']) : '';
                            $update['transport_id'] = $update_common['transport_id'];
                            $update['goods_freight'] = $update_common['goods_freight'];
                            $update['goods_vat'] = $update_common['goods_vat'];
                            $update['goods_commend'] = $update_common['goods_commend'];
                            $update['goods_stcids'] = $update_common['goods_stcids'];
                            $update['is_virtual'] = $update_common['is_virtual'];
                            $update['virtual_indate'] = $update_common['virtual_indate'];
                            $update['virtual_limit'] = $update_common['virtual_limit'];
                            $update['virtual_invalid_refund'] = $update_common['virtual_invalid_refund'];
                            $update['is_goodsfcode'] = $update_common['is_goodsfcode'];
                            $update['is_appoint'] = $update_common['is_appoint'];
                        switch($update_common['virtual_type']){
                                case 1:
                                    $update['virtual_content'] = $value['vc_card'];
                                    $res=$goods_model->getAvailableGoodsCard(array_merge($update,array('goods_id'=>$goods_info['goods_id'])));
                                    if($res['code']){
                                        $update['goods_storage'] = $res['data']['card_num'];
                                    }else{
                                        $update['goods_storage'] = 0;
                                    }
                                    break;
                                case 2:
                                    $update['virtual_content'] = $value['vc_pan'];
                                    $update['goods_storage'] = 1;
                                    break;
                                case 3:
                                    $update['virtual_content'] = $value['vc_file'];
                                    $update['goods_storage'] = 1;
                                    break;
                                default:
                                    $update['virtual_content'] = '';
                            }
                            // 虚拟商品不能有赠品
                            if ($update_common['is_virtual'] == 1) {
                                $update['is_have_gift'] = 0;
                                $goodsgift_model->delGoodsgift(array('goods_id' => $goods_id));
                            }

                            $goods_model->editGoodsById($update, $goods_id);
                        } else {
                            $insert = array();
                            $insert['goods_commonid'] = $common_id;
                            $insert['goods_name'] = $update_common['goods_name'] . ' ' . implode(' ', $value['sp_value']);
                            $insert['goods_advword'] = $update_common['goods_advword'];
                            $insert['store_id'] = $this->store_info['store_id'];
                            $insert['store_name'] = $this->store_info['store_name'];
                            $insert['gc_id'] = $update_common['gc_id'];
                            $insert['gc_id_1'] = $update_common['gc_id_1'];
                            $insert['gc_id_2'] = $update_common['gc_id_2'];
                            $insert['gc_id_3'] = $update_common['gc_id_3'];
                            $insert['brand_id'] = $update_common['brand_id'];
                            $insert['goods_price'] = $value['goods_price'];
                            $insert['goods_promotion_price'] = $value['goods_price'];
                            $insert['goods_marketprice'] = (!isset($value['goods_marketprice']) || $value['goods_marketprice'] == 0) ? $update_common['goods_marketprice'] : $value['goods_marketprice'];
                            $insert['goods_serial'] = isset($value['goods_serial']) ? $value['goods_serial'] : '';
                            $insert['goods_storage_alarm'] = isset($value['goods_storage_alarm']) ? intval($value['goods_storage_alarm']) : 0;
                            $insert['goods_spec'] = serialize($value['sp_value']);
                            $insert['goods_storage'] = $value['goods_storage'];
                            $insert['goods_weight'] = isset($value['goods_weight']) ? $value['goods_weight'] : 0;
                            $insert['goods_image'] = $update_common['goods_image'];
                            $insert['goods_state'] = $update_common['goods_state'];
                            $insert['goods_verify'] = $update_common['goods_verify'];
                            $insert['goods_addtime'] = TIMESTAMP;
                            $insert['goods_edittime'] = TIMESTAMP;
                            $insert['areaid_1'] = $update_common['areaid_1'];
                            $insert['areaid_2'] = $update_common['areaid_2'];
                            $insert['color_id'] = isset($value['color']) ? intval($value['color']) : '';
                            $insert['transport_id'] = $update_common['transport_id'];
                            $insert['goods_freight'] = $update_common['goods_freight'];
                            $insert['goods_vat'] = $update_common['goods_vat'];
                            $insert['goods_commend'] = $update_common['goods_commend'];
                            $insert['goods_stcids'] = $update_common['goods_stcids'];
                            $insert['is_virtual'] = $update_common['is_virtual'];
                            $insert['virtual_indate'] = $update_common['virtual_indate'];
                            $insert['virtual_limit'] = $update_common['virtual_limit'];
                            $insert['virtual_invalid_refund'] = $update_common['virtual_invalid_refund'];
                            $insert['is_goodsfcode'] = $update_common['is_goodsfcode'];
                            $insert['is_appoint'] = $update_common['is_appoint'];
                            $insert['is_platform_store'] = $update_common['is_platform_store'];
                        switch($update_common['virtual_type']){
                                case 1:
                                    $insert['virtual_content'] = $value['vc_card'];
                                    $card_list=explode("\r\n",$insert['virtual_content']);
                                    $insert['goods_storage'] = count($card_list);
                                    break;
                                case 2:
                                    $insert['virtual_content'] = $value['vc_pan'];
                                    $insert['goods_storage'] = 1;
                                    break;
                                case 3:
                                    $insert['virtual_content'] = $value['vc_file'];
                                    $insert['goods_storage'] = 1;
                                    break;
                                default:
                                    $insert['virtual_content'] = '';
                            }
                            $goods_id = $goods_model->addGoods($insert);
                        }
                        $goodsid_array[] = intval($goods_id);
                        $colorid_array[] = isset($value['color']) ? intval($value['color']) : '';
                        $type_model->addGoodsType($goods_id, $common_id, array('cate_id' => $gc_id, 'type_id' => $goods_class['type_id'], 'attr' => input('post.attr/a')));
                    }
                }
            } else {
                $goods_info = $goods_model->getGoodsInfo(array('goods_spec' => serialize(null), 'goods_commonid' => $common_id, 'store_id' => $this->store_info['store_id']), 'goods_id');
                if (!empty($goods_info)) {
                    $goods_id = $goods_info['goods_id'];
                    $update = array();
                    $update['goods_commonid'] = $common_id;
                    $update['goods_name'] = $update_common['goods_name'];
                    $update['goods_advword'] = $update_common['goods_advword'];
                    $update['store_id'] = $this->store_info['store_id'];
                    $update['store_name'] = $this->store_info['store_name'];
                    $update['gc_id'] = $update_common['gc_id'];
                    $update['gc_id_1'] = $update_common['gc_id_1'];
                    $update['gc_id_2'] = $update_common['gc_id_2'];
                    $update['gc_id_3'] = $update_common['gc_id_3'];
                    $update['brand_id'] = $update_common['brand_id'];
                    $update['goods_price'] = $update_common['goods_price'];
                    $update['goods_marketprice'] = $update_common['goods_marketprice'];
                    $update['goods_serial'] = $update_common['goods_serial'];
                    $update['goods_storage_alarm'] = $update_common['goods_storage_alarm'];
                    $update['goods_spec'] = serialize(null);
                    $update['goods_storage'] = intval(input('post.goods.goods_storage'));
                    $update['goods_weight'] = floatval(input('post.goods.goods_weight'));
                    $update['goods_state'] = $update_common['goods_state'];
                    $update['goods_verify'] = $update_common['goods_verify'];
                    $update['goods_edittime'] = TIMESTAMP;
                    $update['areaid_1'] = $update_common['areaid_1'];
                    $update['areaid_2'] = $update_common['areaid_2'];
                    $update['color_id'] = 0;
                    $update['transport_id'] = $update_common['transport_id'];
                    $update['goods_freight'] = $update_common['goods_freight'];
                    $update['goods_vat'] = $update_common['goods_vat'];
                    $update['goods_commend'] = $update_common['goods_commend'];
                    $update['goods_stcids'] = $update_common['goods_stcids'];
                    $update['is_virtual'] = $update_common['is_virtual'];
                    $update['virtual_indate'] = $update_common['virtual_indate'];
                    $update['virtual_limit'] = $update_common['virtual_limit'];
                    $update['virtual_invalid_refund'] = $update_common['virtual_invalid_refund'];
                    $update['is_goodsfcode'] = $update_common['is_goodsfcode'];
                    $update['is_appoint'] = $update_common['is_appoint'];
                    switch($update_common['virtual_type']){
                                case 1:
                                    $update['virtual_content'] = input('post.goods.vc_card');
                                    $res=$goods_model->getAvailableGoodsCard(array_merge($update,array('goods_id'=>$goods_info['goods_id'])));
                                    if($res['code']){
                                        $update['goods_storage'] = $res['data']['card_num'];
                                    }else{
                                        $update['goods_storage'] = 0;
                                    }
                                    break;
                                case 2:
                                    $update['virtual_content'] = input('post.goods.vc_pan');
                                    $update['goods_storage'] = 1;
                                    break;
                                case 3:
                                    $update['virtual_content'] = input('post.goods.vc_file');
                                    $update['goods_storage'] = 1;
                                    break;
                                default:
                                    $update['virtual_content'] = '';
                            }
                    if ($update_common['is_virtual'] == 1) {
                        $update['is_have_gift'] = 0;
                        $goodsgift_model->delGoodsgift(array('goods_id' => $goods_id));
                    }

                    $goods_model->editGoodsById($update, $goods_id);
                } else {
                    $insert = array();
                    $insert['goods_commonid'] = $common_id;
                    $insert['goods_name'] = $update_common['goods_name'];
                    $insert['goods_advword'] = $update_common['goods_advword'];
                    $insert['store_id'] = $this->store_info['store_id'];
                    $insert['store_name'] = $this->store_info['store_name'];
                    $insert['gc_id'] = $update_common['gc_id'];
                    $insert['gc_id_1'] = $update_common['gc_id_1'];
                    $insert['gc_id_2'] = $update_common['gc_id_2'];
                    $insert['gc_id_3'] = $update_common['gc_id_3'];
                    $insert['brand_id'] = $update_common['brand_id'];
                    $insert['goods_price'] = $update_common['goods_price'];
                    $insert['goods_promotion_price'] = $update_common['goods_price'];
                    $insert['goods_marketprice'] = $update_common['goods_marketprice'];
                    $insert['goods_serial'] = $update_common['goods_serial'];
                    $insert['goods_storage_alarm'] = $update_common['goods_storage_alarm'];
                    $insert['goods_spec'] = serialize(null);
                    $insert['goods_storage'] = intval(input('post.goods.goods_storage'));
                    $insert['goods_weight'] = floatval(input('post.goods.goods_weight'));
                    $insert['goods_image'] = $update_common['goods_image'];
                    $insert['goods_state'] = $update_common['goods_state'];
                    $insert['goods_verify'] = $update_common['goods_verify'];
                    $insert['goods_addtime'] = TIMESTAMP;
                    $insert['goods_edittime'] = TIMESTAMP;
                    $insert['areaid_1'] = $update_common['areaid_1'];
                    $insert['areaid_2'] = $update_common['areaid_2'];
                    $insert['color_id'] = 0;
                    $insert['transport_id'] = $update_common['transport_id'];
                    $insert['goods_freight'] = $update_common['goods_freight'];
                    $insert['goods_vat'] = $update_common['goods_vat'];
                    $insert['goods_commend'] = $update_common['goods_commend'];
                    $insert['goods_stcids'] = $update_common['goods_stcids'];
                    $insert['is_virtual'] = $update_common['is_virtual'];
                    $insert['virtual_indate'] = $update_common['virtual_indate'];
                    $insert['virtual_limit'] = $update_common['virtual_limit'];
                    $insert['virtual_invalid_refund'] = $update_common['virtual_invalid_refund'];
                    $insert['is_goodsfcode'] = $update_common['is_goodsfcode'];
                    $insert['is_appoint'] = $update_common['is_appoint'];
                    $insert['is_platform_store'] = $update_common['is_platform_store'];
                    switch($update_common['virtual_type']){
                                case 1:
                                    $insert['virtual_content'] = input('post.goods.vc_card');
                                    $card_list=explode("\r\n",$insert['virtual_content']);
                                    $insert['goods_storage'] = count($card_list);
                                    break;
                                case 2:
                                    $insert['virtual_content'] = input('post.goods.vc_pan');
                                    $insert['goods_storage'] = 1;
                                    break;
                                case 3:
                                    $insert['virtual_content'] = input('post.goods.vc_file');
                                    $insert['goods_storage'] = 1;
                                    break;
                                default:
                                    $insert['virtual_content'] = '';
                            }
                    $goods_id = $goods_model->addGoods($insert);
                }
                $goodsid_array[] = intval($goods_id);
                $colorid_array[] = 0;
                $type_model->addGoodsType($goods_id, $common_id, array('cate_id' => $gc_id, 'type_id' => $goods_class['type_id'], 'attr' => input('post.attr/a')));
            }



            // 清理商品数据
            $goods_model->delGoods(array(array('goods_id', 'not in', $goodsid_array), array('goods_commonid', '=', $common_id), array('store_id', '=', $this->store_info['store_id'])));

            // 清理商品图片表
            $colorid_array = array_unique($colorid_array);
            $goods_model->delGoodsImages(array(array('goods_commonid', '=', $common_id), array('color_id', 'not in', $colorid_array)));
            // 更新商品默认主图
            $default_image_list = $goods_model->getGoodsImageList(array('goods_commonid' => $common_id, 'goodsimage_isdefault' => 1), 'color_id,goodsimage_url');
            if (!empty($default_image_list)) {
                foreach ($default_image_list as $val) {
                    $goods_model->editGoods(array('goods_image' => $val['goodsimage_url']), array('goods_commonid' => $common_id, 'color_id' => $val['color_id']));
                }
            }

            // 商品加入上架队列
            if (!empty(input('post.goods.goods_shelftime'))) {
                $selltime = input('post.goods.goods_shelftime');
                if ($selltime > TIMESTAMP) {
                    $this->addcron(array('cron_exetime' => $selltime, 'cron_value' => serialize(intval($common_id)), 'cron_type' => 'editProducesOnline'), true);
                }
            }
            // 添加操作日志
            $this->recordSellerlog('编辑商品，平台货号：' . $common_id);

            if ($update_common['is_virtual'] == 1 || $update_common['is_goodsfcode'] == 1) {
                // 如果是特殊商品清理促销活动，抢购、秒杀、组合销售
                model('cron')->addCron(array('cron_exetime'=>TIMESTAMP,'cron_type'=>'clearSpecialGoodsPromotion','cron_value'=>serialize(array('goods_commonid' => $common_id, 'goodsid_array' => $goodsid_array))));
            } else {
                // 更新商品促销价格
                model('cron')->addCron(array('cron_exetime'=>TIMESTAMP,'cron_type'=>'updateGoodsPromotionPriceByGoodsCommonId','cron_value'=>serialize($common_id)));
            }

            // 生成F码
            if ($update_common['is_goodsfcode'] == 1) {
                model('goodsfcode')->createGoodsfcode(array('goods_commonid' => $common_id, 'goodsfcode_count' => intval(input('post.g_fccount')), 'goodsfcode_prefix' => input('post.g_fcprefix')));
            }
            if (!$if_add) {
                $return = $goods_model->editGoodsCommon($update_common, array('goods_commonid' => $common_id, 'store_id' => $this->store_info['store_id']));
            }
        } catch (\Exception $e) {
            Db::rollback();
            ds_json_encode(10001, $e->getMessage());
        }
        Db::commit();
        ds_json_encode(10000, lang('ds_common_op_succ'), array('commonid' => $common_id));
    }

    /**
     * @api {POST} api/Sellergoods/edit_image 获取商品图片
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} commonid 商品公共ID
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Object} result.spec_value  规格列表（键为规格名id，值中的键为规格值id，值中的值为规格值）
     * @apiSuccess {Object} result.img  图片列表（键为规格值id，值为图片列表）
     * @apiSuccess {String} result.img.goodsimage_full_url  图片链接
     * @apiSuccess {Int} result.img.goodsimage_isdefault  是否默认（0否1是）
     * @apiSuccess {String} result.img.goodsimage_url  图片名称
     * @apiSuccess {Object[]} result.value_array  规格值列表
     * @apiSuccess {Int} result.value_array.spvalue_id  规格值id
     * @apiSuccess {String} result.value_array.spvalue_name  规格值
     */
    public function edit_image() {
        $result = array();
        $common_id = intval(input('param.commonid'));
        if ($common_id <= 0) {
            ds_json_encode(10001, lang('param_error'));
        }
        $goods_model = model('goods');
        $common_list = $goods_model->getGoodsCommonInfoByID($common_id);
        if ($common_list['store_id'] != $this->store_info['store_id'] || $common_list['goods_lock'] == 1) {
            ds_json_encode(10001, lang('goods_not_exist_or_lock'));
        }

        $spec_value = unserialize($common_list['spec_value']);
        $result['spec_value'] = $spec_value;

        $image_list = $goods_model->getGoodsImageList(array('goods_commonid' => $common_id));
        $image_list = array_under_reset($image_list, 'color_id', 2);

        $img_array = $goods_model->getGoodsList(array('goods_commonid' => $common_id), '*', 'color_id');
        $image_array = array();
        // 整理，更具id查询颜色名称
        if (!empty($img_array)) {
            foreach ($img_array as $val) {
                if (isset($image_list[$val['color_id']])) {
                    $image_array[$val['color_id']] = $image_list[$val['color_id']];
                    foreach ($image_array[$val['color_id']] as $k => $v) {
                        $image_array[$val['color_id']][$k]['goodsimage_full_url'] = goods_cthumb($v['goodsimage_url'], 240);
                    }
                } else {
                    $image_array[$val['color_id']][0]['goodsimage_url'] = $val['goods_image'];
                    $image_array[$val['color_id']][0]['goodsimage_full_url'] = goods_cthumb($val['goods_image'], 240);
                    $image_array[$val['color_id']][0]['goodsimage_isdefault'] = 1;
                }
                $colorid_array[] = $val['color_id'];
            }
        }
        $result['img'] = $image_array;


        $spec_model = model('spec');
        $value_array = $spec_model->getSpecvalueList(array(array('spvalue_id', 'in', $colorid_array), array('store_id', '=', $this->store_info['store_id'])), 'spvalue_id,spvalue_name');
        if (empty($value_array)) {
            $value_array[] = array('spvalue_id' => '0', 'spvalue_name' => lang('no_color'));
        }
        $result['value_array'] = $value_array;
        ds_json_encode(10000, '', $result);
    }

    /**
     * @api {POST} api/Sellergoods/save_image 保存商品图片
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * @apiParam {Int} commonid 商品公共ID
     * @apiParam {Object[]} img 图片列表
     * @apiParam {String} img.goodsimage_full_url  图片链接
     * @apiParam {Int} img.goodsimage_isdefault  是否默认（0否1是）
     * @apiParam {String} img.goodsimage_url  图片名称
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * 
     */
    public function save_image() {
        $common_id = intval(input('param.commonid'));
        $img_array = input('post.img/a'); #获取数组
        if ($common_id <= 0 || empty($img_array)) {
            ds_json_encode(10001, lang('param_error'));
        }
        $goods_model = model('goods');
        $common_list = $goods_model->getGoodsCommonInfoByID($common_id);
        if ($common_list['store_id'] != $this->store_info['store_id'] || $common_list['goods_lock'] == 1) {
            ds_json_encode(10001, lang('goods_not_exist_or_lock'));
        }
        // 删除原有图片信息
        $goods_model->delGoodsImages(array('goods_commonid' => $common_id, 'store_id' => $this->store_info['store_id']));
        // 保存
        $insert_array = array();
        foreach ($img_array as $key => $value) {
            $k = 0;
            foreach ($value as $v) {
                if ($v['goodsimage_url'] == '') {
                    continue;
                }
                // 商品默认主图
                $update_array = array();        // 更新商品主图
                $condition = array();
                $update_array['goods_image'] = $v['goodsimage_url'];
                $condition[] = array('goods_commonid', '=', $common_id);
                $condition[] = array('store_id', '=', $this->store_info['store_id']);
                $condition[] = array('color_id', '=', $key);
                if ($k == 0) {
                    $update_array['goods_image'] = $v['goodsimage_url'];
                    $condition[] = array('goods_commonid', '=', $common_id);
                    $condition[] = array('store_id', '=', $this->store_info['store_id']);
                    $condition[] = array('color_id', '=', $key);
                    // 更新商品主图
                    $goods_model->editGoods($update_array, $condition);
                }
                $tmp_insert = array();
                $tmp_insert['goods_commonid'] = $common_id;
                $tmp_insert['store_id'] = $this->store_info['store_id'];
                $tmp_insert['color_id'] = $key;
                $tmp_insert['goodsimage_url'] = $v['goodsimage_url'];
                $tmp_insert['goodsimage_sort'] = $k;
                $tmp_insert['goodsimage_isdefault'] = ($k == 0) ? 1 : 0;
                $insert_array[] = $tmp_insert;
                $k++;
            }
        }
        if (!empty($insert_array)) {
            $rs = $goods_model->addGoodsImagesAll($insert_array);
            if ($rs) {
                // 添加操作日志
                $this->recordSellerlog('编辑商品，平台货号：' . $common_id);
                ds_json_encode(10000, lang('ds_common_op_succ'));
            } else {
                ds_json_encode(10001, lang('ds_common_op_fail'));
            }
        } else {
            ds_json_encode(10000, lang('ds_common_op_succ'));
        }
    }

    /**
     * @api {POST} api/Sellergoods/goods_class 获取经营分类
     * @apiVersion 1.0.0
     * @apiGroup Sellergoods
     *
     * @apiHeader {String} X-DS-KEY 卖家授权token
     *
     * 
     * @apiSuccess {String} code 返回码,10000为成功
     * @apiSuccess {String} message  返回消息
     * @apiSuccess {Object} result  返回数据
     * @apiSuccess {Int} result.bind_all 是否绑定全部分类（0否1是）
     * @apiSuccess {Object[]} result.class_list  商品分类列表
     * @apiSuccess {Int} result.class_list.id  分类ID
     * @apiSuccess {String} result.class_list.value  分类名称
     * @apiSuccess {Object[]} result.class_list.children  子分类列表
     * 
     */
    public function goods_class() {
        $bind_all = false;
        $store_bind_class_list = array();
        if ($this->store_info['is_platform_store'] && $this->store_info['bind_all_gc']) {
            $bind_all = true;
        } else {
            $storebindclass_model = model('storebindclass');
            if ($storebindclass_model->getStorebindclassInfo(array(array('class_1&class_2&class_3', '=', 0), array('store_id', '=', $this->store_info['store_id']), array('storebindclass_state', 'in', array(1, 2))))) {
                $bind_all = true;
            } else {
                $temp = $storebindclass_model->getStorebindclassList(array(array('store_id', '=', $this->store_info['store_id']), array('storebindclass_state', 'in', array(1, 2))), null);
                $class_1_ids = array();
                $class_2_ids = array();
                $class_3_ids = array();
                foreach ($temp as $class_info) {
                    if ($class_info['class_3'] == 0) {
                        if ($class_info['class_2'] == 0) {
                            $class_1_ids[] = $class_info['class_1'];
                        } else {
                            $class_2_ids[] = $class_info['class_2'];
                        }
                    } else {
                        $class_3_ids[] = $class_info['class_3'];
                    }
                }
                $goodsclass_list = array();
                if (!empty($class_1_ids)) {
                    $class_1_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $class_1_ids)));
                    $goodsclass_list = array_merge($goodsclass_list, $class_1_list);
                    $temp_2 = Db::name('goodsclass')->where(array(array('gc_parent_id', 'in', $class_1_ids)))->column('gc_id');
                    if (!empty($temp_2)) {
                        $class_2_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $temp_2)));
                        $goodsclass_list = array_merge($goodsclass_list, $class_2_list);
                        $temp_3 = Db::name('goodsclass')->where(array(array('gc_parent_id', 'in', $temp_2)))->column('gc_id');
                        if (!empty($temp_3)) {
                            $class_3_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $temp_3)));
                            $goodsclass_list = array_merge($goodsclass_list, $class_3_list);
                        }
                    }
                }
                if (!empty($class_2_ids)) {
                    $temp_1 = Db::name('goodsclass')->where(array(array('gc_id', 'in', $class_2_ids)))->column('gc_parent_id');
                    $class_1_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $temp_1)));
                    $goodsclass_list = array_merge($goodsclass_list, $class_1_list);
                    $class_2_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $class_2_ids)));
                    $goodsclass_list = array_merge($goodsclass_list, $class_2_list);
                    $temp_3 = Db::name('goodsclass')->where(array(array('gc_parent_id', 'in', $class_2_ids)))->column('gc_id');
                    if (!empty($temp_3)) {
                        $class_3_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $temp_3)));
                        $goodsclass_list = array_merge($goodsclass_list, $class_3_list);
                    }
                }
                if (!empty($class_3_ids)) {
                    $class_3_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $class_3_ids)));
                    $goodsclass_list = array_merge($goodsclass_list, $class_3_list);
                    $temp_2 = Db::name('goodsclass')->where(array(array('gc_id', 'in', $class_3_ids)))->column('gc_parent_id');
                    $class_2_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $temp_2)));
                    $goodsclass_list = array_merge($goodsclass_list, $class_2_list);
                    $temp_1 = Db::name('goodsclass')->where(array(array('gc_id', 'in', $temp_2)))->column('gc_parent_id');
                    $class_1_list = model('goodsclass')->getGoodsclassList(array(array('gc_id', 'in', $temp_1)));
                    $goodsclass_list = array_merge($goodsclass_list, $class_1_list);
                }
                if (!empty($goodsclass_list)) {
                    $tree = new \mall\Tree();
                    $tree->setTree($goodsclass_list, 'gc_id', 'gc_parent_id', 'gc_name');
                    $result['class_list'] = $tree->getArrayList();
                    $store_bind_class_list = $result['class_list'];
                }
            }
        }

        ds_json_encode(10000, '', array('goods_class' => $store_bind_class_list, 'bind_all' => $bind_all));
    }

}
