docDir = $this->request->server('DOCUMENT_ROOT'); $this->rootDir = $this->request->root(); $this->basePath = $this->docDir . $this->rootDir . '/uploads'; $this->saveDirectory = 'temp'; error_reporting(E_ERROR | E_WARNING); Config::set('url_common_param', true); header("Content-Type: text/html; charset=utf-8"); } public function index() { $this->redirect('/admin/product/lists'); } private function init_search(&$search) { $search['name'] = ''; $search['brand_id'] = ''; $search['timebegin'] = ''; $search['timeend'] = ''; $search['is_show'] = ''; } public function lists() { $data = $this->request->param(); // tiaoshi($data);die; $arg_where = [ 'a.siteid' => $this->siteid, 'a.country_code' => $this->country_code, ]; $cid = isset($data['cid']) ? intval($data['cid']) : 0; if ($cid > 0) { $arg_where['a.cid'] = $cid; } $search = []; $this->init_search($search); if (isset($data['name']) && $data['name'] != '') { $arg_where['a.name'] = ['like', "%$data[name]%"]; $search['name'] = $data['name']; } if (isset($data['is_show']) && $data['is_show'] != '') { $arg_where['a.is_show'] = $data['is_show']; $search['is_show'] = (int) $data['is_show']; } if (isset($data['brand_id']) && $data['brand_id'] != '') { $arg_where['a.brand_id'] = ['like', "%$data[brand_id]%"]; $search['brand_id'] = $data['brand_id']; } if ((isset($data['timebegin']) && $data['timebegin'] != '') || (isset($data['timeend']) && $data['timeend'] != '')) { // 时间有一个不为空就初始化 $arg_where['a.createtime'] = []; if (isset($data['timebegin']) && $data['timebegin'] != '') { $time = strtotime($data['timebegin']); array_push($arg_where['a.createtime'], ['>=', $time]); $search['timebegin'] = $data['timebegin']; } if (isset($data['timeend']) && $data['timeend'] != '') { $time = strtotime($data['timeend']); array_push($arg_where['a.createtime'], ['<=', $time]); $search['timeend'] = $data['timeend']; } } $arg_order = ['a.id' => 'desc']; $arg_field = ['a.*', 'c.id' => 'categoryid', 'c.name' => 'categoryname']; $argc_where = array('pid' => 0, 'stat' => 0, 'country_code' => $this->country_code); $argc_order = array('sort' => 'asc', 'id' => 'asc'); $argc_field = array('id', 'pid', 'haschild', 'name', 'sort'); $dataObject = model('product')->getProductLists($arg_where, $arg_order, $arg_field, 12); $categoryOptions = model('product_category')->getCategoryOptions($cid, $argc_where, $argc_order, $argc_field, 100); $value = [ 'categoryOptions' => $categoryOptions, 'list' => $dataObject->isEmpty() ? null : $dataObject->items(), 'page' => $dataObject->render(), 'search' => $search, 'cid' => $cid ]; //echo "
=="; print_r($dataObject);
        $this->assign($value);
        return $this->fetch();
    }

    public function clear_search_cache()
    {
        if ($this->country_code == 'ZH')
            $suffix = 'index';
        else
            $suffix = strtolower($this->country_code);
        $cache_name = 'product_filter_' . $suffix;
        $this->cacheDelete($cache_name);

        return $this->success(Lang::get('operation successed'));
    }

    public function copy_data()
    {
        $data = $this->request->post();
        // tiaoshi($data);die;
        if (empty($data) || !is_array($data))
        {
            return $this->json(-1, '数据错误');
        }

        $arr_product = $data['product_ids'];
        $arr_country = $data['country'];

 
        if(sizeof($arr_country))  {
            
            foreach ($arr_country as $key => $value)
            {
                    //当前参数语言
                    $country_code = $value;
                    
                    foreach ($arr_product as $k => $v)
                    {
                        //  -----------复制基本信息begin------------
                        $product_info = model('product')->where(['id' => $v, 'country_code' => $this->country_code])->find()->toArray();
        
                        unset($product_info['id']);
                        unset($product_info['url_tm']);
                        unset($product_info['url_jd']);
                        unset($product_info['url_dg_amazon']);
                        unset($product_info['seo_title']);
                        unset($product_info['seo_description']);
                        unset($product_info['seo_keyword']);
                        $category_info       = model('product_category')->where(['id' => $product_info['cid']])->find();
                        $unique_id           = $category_info['unique_id'];
                        $new_category_info   = model('product_category')->where(['unique_id' => $unique_id, 'country_code' => $country_code])->find();
       

     
                        $product_info['cid']          = $new_category_info['id'];
                        $product_info['country_code'] = $country_code;
          
                        $new_product_info = model('product')->where(['stat' => 0, 'country_code' => $country_code, 'brand_id' => $product_info['brand_id']])->find();

        
                        $new_product_id = model('product')->insertGetId($product_info);
                       
                        
                        if (!$new_product_id) {
                            return $this->json(-2, "id为$v的产品添加到$country_code失败");
                        } 
                            
                        //  -----------复制基本信息e n d------------
        
                        //  -----------复制下载信息begin------------
                        $product_dl = model('product_dl')->where(['product_id' => $v, 'country_code' => $this->country_code])->select();
                        if (!empty($product_dl))
                        {
                            foreach ($product_dl as $index => $item)
                            {
                                $item = json_decode(json_encode($item), true);
                                unset($item['id']);
                                $item['product_id']   = $new_product_id;
                                $item['country_code'] = $country_code;
                                model('product_dl')->insert($item);
                            }
                        }
                        //  -----------复制下载信息e n d------------
        
                        //  -----------复制附加图片begin------------
                        $product_image = model('product_image')->where(['product_id' => $v, 'country_code' => $this->country_code])->select();
                        if (!empty($product_image))
                        {
                            foreach ($product_image as $index => $item)
                            {
                                $item = json_decode(json_encode($item), true);
                                unset($item['id']);
                                $item['product_id']   = $new_product_id;
                                $item['country_code'] = $country_code;
                                model('product_image')->insert($item);
                            }
                        }
                        //  -----------复制附加图片e n d------------
        
                        //  -----------复制相关产品begin------------
                        $product_related = model('product_related')->where(['stat' => 0, 'country_code' => $this->country_code, 'product_id' => $v])->select();
                        if (!empty($product_related))
                        {
                            foreach ($product_related as $index => $item) {
                                $item = json_decode($item, true);
                                $related_product_info = model('product')->where(['stat' => 0, 'country_code' => $this->country_code, 'id' => $item['related_product_id']])->find();
                                if (empty($related_product_info))
                                    continue;
        
                                $new_related_info = model('product')->where(['stat' => 0, 'country_code' => $country_code, 'brand_id' => $related_product_info['brand_id']])->find();
                                if (empty($new_related_info))
                                    continue;
        
                                $new_related_id = $new_related_info['id'];
                                unset($item['id']);
                                $item['product_id']         = $new_product_id;
                                $item['related_product_id'] = $new_related_id;
                                $item['country_code']       = $country_code;
                                model('product_related')->insert($item);
                            }
                        }
                        //  -----------复制相关产品e n d------------
        
                        //  -----------复制二级列表图begin------------
                        $product_two_img = model('product_two_img')->where(['stat' => 0, 'country_code' => $this->country_code, 'product_id' => $v])->select();
                        if (!empty($product_two_img))
                        {
                            foreach ($product_two_img as $index => $item) {
                                $item = json_decode($item, true);
                                unset($item['id']);
                                $item['product_id']    = $new_product_id;
                                $item['country_code']  = $country_code;
                                model('product_two_img')->insert($item);
                            }
                        }
                        //  -----------复制二级列表图e n d------------
                    }                    
               

            }
            return $this->json(200, '复制完毕');
        }
        else{
            return $this->json(-100, '复制错误');
        }

        
    }

    public function add_sku()
    {
        $data = $this->request->param();
        if (empty($data['id']))
        {
            return $this->error('id不能为空');
        }

        $sku_list = model('product_sku')->where(['product_id' => $data['id'], 'stat' => 0])->select();

        $this->assign('sku_list', $sku_list);
        $this->assign('product_id', $data['id']);
        return view();
    }

    public function update_sku()
    {
        $data = $this->request->post();
        // tiaoshi($data);die;
        if (empty($data['id']))
            return $this->error('id不能为空');

        $product = model('product')->where(['id' => $data['id']])->find();
        if (empty($product))
            return $this->error('产品不存在');

        $old_sku = model('product_sku')->where(['product_id' => $data['id']])->find();
        if (!empty($old_sku))
            model('product_sku')->where(['product_id' => $data['id']])->update(['stat' => 1]);

        $sku        = $data['sku'];
        $version    = $data['version'];
        $interface  = $data['interface'];
        $color      = $data['color'];
        $length     = $data['length'];
        $regulatory = $data['regulatory'];
        $package    = $data['package'];
        foreach ($sku as $key => $value) {
            if ($value == '')
                continue;

            $insert_data = [
                'product_id'    => $data['id'],
                // 'brand_id'      => $product['brand_id'],
                'sku'           => trim($value),
                'version'       => trim($version[$key]),
                'interface'     => trim($interface[$key]),
                'color'         => trim($color[$key]),
                'length'        => trim($length[$key]),
                'regulatory'    => trim($regulatory[$key]),
                'package'       => trim($package[$key]),
                'stat'          => 0
            ];
            $result = model('product_sku')->where(['product_id' => $data['id']])->insert($insert_data);
            if (!$result)
                return $this->error('添加sku失败');
        }

        model('product')->where(['id' => $data['id']])->update(['update_status' => 1]);

        return $this->success('添加sku成功', url('/admin/product/lists'));
    }

    public function get_country() {
        $country = model('country')->where(['stat' => 0])->select();
        $data = [
            'country'   => $country,
        ];

        return $this->json(200, 'ok', $data);
    }

    public function get_cate()
    {
        $country_code = $this->request->param('country_code');

        $categoryOptions = model('product_category')->getCategoryOptions(0, ['country_code' => $country_code], ['id' => 'asc'], null, 100);
        $data = [
            'cate_list' => $categoryOptions
        ];
        
        return $this->json(200, 'ok', $data);
    }

    public function catlists($cid = 0) {
        $cid = is_numeric($cid) ? intval($cid) : 0;
        $arg_where = ['a.cid' => $cid, 'a.siteid' => $this->siteid, 'a.country_code' => $this->country_code];
        $arg_order = ['a.id' => 'desc'];
        $arg_field = ['a.*', 'c.id' => 'categoryid', 'c.name' => 'categoryname'];
        $dataObject = model('product')->getProductLists($arg_where, $arg_order, $arg_field, 12);
        $argc_where = array('pid' => 0, 'stat' => 0, 'country_code' => $this->country_code);
        $argc_order = array('sort' => 'asc', 'id' => 'asc');
        $argc_field = array('id', 'pid', 'haschild', 'name', 'sort');
        $categoryOptions = model('product_category')->getCategoryOptions(0, $argc_where, $argc_order, $argc_field, 100);
        $value = [
            'categoryOptions' => $categoryOptions,
            'list' => $dataObject->isEmpty() ? null : $dataObject->items(), //$dataObject->getCollection()->toArray()
            'page' => $dataObject->render(),
        ];
        $this->assign($value);
        return $this->fetch('lists');
    }

    private function check_format($product_id)
    {
        if ($product_id < 0)
        {
            return ['code' => -1, 'msg' => '产品id错误'];
        }
        
        $product_info = model('product')->where(['id' => $product_id, 'stat' => 0])->find();
        if (empty($product_info))
        {
            return ['code' => -2, 'msg' => '没有该产品信息'];
        }
        if ($product_info['description'] = '')
        {
            return ['code' => -3, 'msg' => '产品描述不能为空'];
        }
        /*if ($product_info['product_view'] == 'a:0:{}')
        {
            return ['code' => -4, 'msg' => '产品参数不能为空'];
        }*/

        $where = ['product_id' => $product_id, 'stat' => 0];
        $product_image = model('product_image')->where($where)->find();
        if (empty($product_image))
        {
            return ['code' => -5, 'msg' => '产品附加图片不能为空'];
        }

        // $product_related = model('product_related')->where($where)->find();
        // if (empty($product_related))
        // {
        //     return ['code' => -6, 'msg' => '相关产品不能为空'];
        // }

        $product_two_img = model('product_two_img')->where($where)->find();
        if (empty($product_two_img))
        {
            return ['code' => -7, 'msg' => '产品二级列表图不能为空'];
        }

        return ['code' => 200, 'msg' => 'ok'];
    }

    public function shangjia()
    {
        $product_id = $this->request->param('product_id');

        $result = $this->check_format($product_id);
        if ($result['code'] < 0)
        {
            return $this->json($result['code'], $result['msg']);
        }

        $ok = model('product')->where(['id' => $product_id, 'stat' => 0, 'is_show' => -1])->update(['is_show' => 0]);
        if ($ok) {
            $platforms = Db::name('product_purchase_link_platforms')->where('country_code', '=', $this->country_code)->select();
            foreach ($platforms as $platform) {
                $id = Db::name('product_purchase_links')
                    ->where('product_id', '=', $product_id)
                    ->where('platform_id', '=', $platform['id'])
                    ->where('country_code', '=', $this->country_code)
                    ->value('id');
                if (empty($id)) {
                    Db::name('product_purchase_links')->insert([
                        'product_id'   => $product_id,
                        'platform_id'  => $platform['id'],
                        'country_code' => $this->country_code,
                    ]);
                }
            }
        }
        return $this->json(200, 'ok');
    }

    public function xiajia()
    {
        $product_id = $this->request->param('product_id');
        if ($product_id < 0)
        {
            return $this->json(-1, '产品id错误');
        }

        model('product')->where(['id' => $product_id, 'stat' => 0, 'is_show' => 0])->update(['is_show' => -1]);
        return $this->json(200, 'ok');
    }

    public function create($cid = 0) {
        $cid = is_numeric($cid) ? intval($cid) : 0;
        $argc_where = array('pid' => 0, 'stat' => 0, 'country_code' => $this->country_code, 'isshow' => 1);
        $argc_order = array('sort' => 'asc', 'id' => 'asc');
        $argc_field = array('id', 'pid', 'haschild', 'name', 'sort');
        $categoryOptions = model('product_category')->getCategoryOptions($cid, $argc_where, $argc_order, $argc_field, 100);

        $value['supplierOption'] = '';
        $value['typeOption'] = '';
        $value['brandOption'] = '';
        $value ['categoryOptions'] = $categoryOptions;
        
        $value['filepath'] = 'product';
        if(session('cit') == 'us') {
            $value['filepath'] = 'uk/product';
        }
        
        $this->assign($value);
        return $this->fetch();
    }

    public function save() {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // tiaoshi($data);die;
            if (empty($data) || !is_array($data)) {
                return $this->error(Lang::get('incorrect operation'));
            }
            $validaterule = ['name' => 'require', 'cid' => 'number|between:0,2147483647',];
            $validatemsg = ['name.require' => '名称不能为空', 'cid.between' => '所属上级值无效',];
            $valid_result = $this->validate($data, $validaterule, $validatemsg);
            if (true !== $valid_result) {
                // 验证失败 输出错误信息
                return $this->error($valid_result);
            }
            $sort = intval($data['sort']);

            /* 产品描述 start */
            $product_desc = [];
            if (isset($data['product_desc'])) {
                foreach ($data['product_desc'] as $desc) {
                    if ($desc['desc_title']) {
                        $product_desc[] = $desc;
                    }
                }
            }
            /* 产品描述 end */

            /*其它信息*/
            $product_view = [];
            if (isset($data['product_view']) && $data['product_view'] != '') {
                $arr_product_view = [];
                $str_product_view = trim(trim($data['product_view']), '#');
                $tmp_product_view = explode("#", $str_product_view);
                
                foreach ($tmp_product_view as $key => $value) {
                    $tmp = explode(":", $value, 2);
                    if (!is_array($tmp) || !isset($tmp[0]) || !isset($tmp[1]))
                    {
                        return $this->error('参数格式错误');
                    }
                    $arr_product_view[$key]['desc_title'] = trim($tmp[0]);
                    $arr_product_view[$key]['desc_desc'] = trim($tmp[1]);
                }

                foreach ($arr_product_view as $desc) {
                    if ($desc['desc_title']) {
                        $product_view[] = $desc;
                    }
                }
            }

            $keyword = '';
            if (isset($data['keyword']))
            {
                $str_keyword = trim(trim($data['keyword']), '#');
                $arr_keyword = explode("#", $str_keyword);
                foreach ($arr_keyword as $key => $value) {
                    $keyword .= trim($value) . ',';
                }
                $keyword = trim($keyword, ',');
            }
            
            
            //属性
            $product_attr= isset($data['product_attr']) ? json_encode($data['product_attr']) : '';
            

            /*其它信息 end*/
            //dump($data);die;
            $set = array(
                'cid' => $data['cid'],
                'siteid' => $this->siteid,
                'brand_id' => trim($data['brand_id']),
                'name' => trim($data['name']),
                'shortname' => trim($data['shortname']),
                'description' => isset($data['description']) ? $data['description'] : '',
                'product_attr' => $product_attr,
                'updatetime' => time(),
                'sort' => $sort < 2147483647 ? $sort : 2147483647,
                'isnew' => $data['isnew'],
                'ishot' => $data['ishot'],
                'isfeatured' => isset($data['isfeatured']) ? $data['isfeatured'] : 0,
                'recommend' => isset($data['recommend']) ? $data['recommend'] : 0,
                'videopath' => $data['videopath'],
                'ld_md_content' => $data['ld_md_content'],
                'stock_quantity' => isset($data['stock_quantity']) ? intval($data['stock_quantity']) : 10,
                'seo_title' => $data['seo_title'],
                'seo_keyword' => $data['seo_keyword'],
                'seo_description' => $data['seo_description'],
                'tags' => isset($data['tags']) ? $data['tags'] : '',
                'url_tm' => isset($data['url_tm']) ? $data['url_tm'] : '',
                'url_jd' => isset($data['url_jd']) ? $data['url_jd'] : '',
                'type_id' => isset($data['type_id']) ? $data['type_id'] : 0,
                'cpyanse' => isset($data['cpyanse']) ? $data['cpyanse'] : 0,
                'user_id' => $this->user_id,
                'product_desc' => serialize($product_desc),
                'onelist' => $data['onelist'],/*是否显示1级列表*/
                'list_bk_img' => $data['list_bk_img'],/*1级列表主图*/
                'product_view' => serialize($product_view),
                'rmimg'=>isset($data['rmimg']) ? $data['rmimg']: '',
                'plid' =>isset($data['tbpl']) ? $data['tbpl']: '',
                'is_show'   => -1,
                'keyword'   => $keyword,
                'country_code' => $this->country_code,
                'update_status' => 1
            );
            $productModel = model('product');
            $model = $productModel->insertRow($set);
            $last_insert_id = $model->getData('id');
            if (!$last_insert_id) {
                return $this->error(Lang::get('operation failed'));
            }
            /*淘宝评论
            if(isset($data['tbpl'])){
                $tlpl = Loader::model('Tbpl');
                $where = ['id'=>$data['tbpl']];
                $arr = ['product_id'=>$last_insert_id];
                $updat = $tlpl->updateRow($arr,$where);
            }*/
            /* 相关图片 start */
            // if (isset($data['product_image'])) {
            //     $imageModel = model('product_image');
            //     foreach ($data['product_image'] as $product_image) {
            //         if (empty($product_image['image_url']))
            //             break;
            //         $image = array(
            //             'product_id' => $last_insert_id,
            //             'image_url' => $product_image['image_url'],
            //             'image_sort' => is_numeric($product_image['image_sort']) ? intval($product_image['image_sort']) : 0,
            //             'image_desc' => $product_image['image_desc'],
            //             'image_color' => $product_image['image_color'],
            //             'original_url' => $product_image['image_url'],
            //             'country_code'  => $this->country_code
            //         );
            //         $imageModel->insertRow($image);
            //     }
            // }

            //附加图、相册图
            if (isset($data['product_image']) && isset($data['arr_product_img']))
            {
               $productAttr = array();
                foreach($data['product_image'] as $km => $feeds) {
                   // echo "
*****"; print_r($feeds);
                    
                    $groups = array(
                        'type' =>     isset($feeds['type']) ? $feeds['type'] : '',
                        'sort' =>     isset($feeds['sort']) ? $feeds['sort'] : '',
                        'sku' =>      isset($feeds['sku']) ? $feeds['sku'] : '',
                    );
                    $productAttr[] = $groups;
                }                
                
                $data['product_image']      = array_merge($data['product_image']);
                $data['arr_product_img']    = array_merge($data['arr_product_img']);   
                foreach ($data['arr_product_img'] as $key => $value) {
                    if (empty($value))
                        continue;
                    $images['product_id']   = $last_insert_id;
                    //$images['image_color']  = isset($data['product_image'][$key]) ? $data['product_image'][$key]['image_color'] : '';
                   // $images['image_sort']   = isset($data['product_image'][$key]) ? $data['product_image'][$key]['image_sort'] : '';
                    $images['sku']   = isset($productAttr[$key]['sku']) ? $productAttr[$key]['sku'] : '';
                    $images['country_code'] = $this->country_code;
            
                    $images['image_url'] = json_encode($value);
                    
                    $arrribute = array();
                    
                    
                    if(isset($data['product_attr']) && is_array($data['product_attr'])){
                        //$poductAttr = $data['product_image'][$key]; 
                        //echo $key."
----"; print_r($productAttr);
                        
                        
                         foreach($productAttr[$key]['type'] as $kt => $attrValue ) {
                                //echo $attrValue."
*****"; print_r($productAttr[$key]['sort']);
                                $arrribute[$kt] = array(
                                        $data['product_attr'][$kt] => trim($attrValue),
                                        'sort'=> isset($productAttr[$key]['sort'][$kt]) ? $productAttr[$key]['sort'][$kt]: ''
                                );                                
                           
                        }

                        
                    }
                    $images['image_color']   = json_encode($arrribute);
                    //echo "
=="; print_r($images); die;
                  
                    model('product_image')->insert($images);
                }
            }
            
            
            /*if (isset($data['product_image']) && isset($data['arr_product_img']))
            {
                $data['product_image']      = array_merge($data['product_image']);
                $data['arr_product_img']    = array_merge($data['arr_product_img']);   
                foreach ($data['arr_product_img'] as $key => $value) {
                    if (empty($value))
                        continue;
                    $images['product_id']   = $last_insert_id;
                    $images['image_color']  = $data['product_image'][$key]['image_color'];
                    $images['image_sort']   = $data['product_image'][$key]['image_sort'];
                    $images['image_desc']   = $data['product_image'][$key]['image_desc'];
                    $images['country_code'] = $this->country_code;

                    foreach ($value as $k => $v) {
                        $images['image_url'] = $v;
                        model('product_image')->insert($images);
                    }
                }
            }*/
            /* 相关图片 end */
            /* 二级列表主图片 start */
            if (isset($data['product_product'])) {
                $imageModel = model('product_two_img');
                foreach ($data['product_product'] as $product_image) {
                    if (empty($product_image['image_url']))
                        break;
                    $image = array(
                        'product_id' => $last_insert_id,
                        'image_url' => isset($product_image['image_url']) ? $product_image['image_url'] : '',
                        'image_bk_color' => isset($product_image['image_bkcolor']) ? $product_image['image_bkcolor'] : '',
                        'image_color' => isset($product_image['image_color']) ? trim($product_image['image_color']) : '',
                        'original_url' => isset($product_image['image_url']) ? $product_image['image_url'] : '',
                        'country_code'  => $this->country_code
                    );
                    $imageModel->insertRow($image);
                }
            }
            /* 二级列表主图片 end */
            /* 爆款主图片 start 
            if (isset($data['bkimg_row'])) {
                $imageModel = model('product_bk_img');
                foreach ($data['bkimg_row'] as $product_image) {
                    if (empty($product_image['image_url']))
                        break;
                    $image = array(
                        'product_id' => $last_insert_id,
                        'image_url' => $product_image['image_url'],
                        'image_bk_color' => $product_image['image_bkcolor'],
                        'image_color' => $product_image['image_color'],
                        'original_url' => $product_image['image_url'],
                        'country_code'  => $this->country_code
                    );
                    $imageModel->insertRow($image);
                }
            }*/
            /* 爆款主图片 end */
            /* 相关产品 start */
            if (isset($data['product_related'])) {
                $relatedModel = model('product_related');
                foreach ($data['product_related'] as $product_related) {
                    if (empty($product_related['related_product_id']))
                        break;
                    $related = array(
                        'product_id' => $last_insert_id,
                        'related_product_id' => $product_related['related_product_id'],
                        'related_sort' => is_numeric($product_related['related_sort']) ? intval($product_related['related_sort']) : 0,
                        'related_desc' => $product_related['related_desc'],
                        'country_code'  => $this->country_code
                    );
                    $relatedModel->insertRow($related);
                }
            }
            
            //$arrtibutes = array['color', 'length'];
            
            /* 相关产品 end */
            /* 相关下载 start */
            if (isset($data['product_dl'])) {
                $dlModel = model('product_dl');
                foreach ($data['product_dl'] as $product_dl) {
                    if (empty($product_dl['dl_url']))
                        break;
                    $dl = array(
                        'product_id' => $last_insert_id,
                        'dl_url' => $product_dl['dl_url'],
                        'dl_sort' => is_numeric($product_dl['dl_sort']) ? intval($product_dl['dl_sort']) : 0,
                        'dl_desc' => isset($product_dl['dl_desc']) ? $product_dl['dl_desc'] : '',
                        'dl_type' => $product_dl['dl_type'],
                        'dl_name' => $product_dl['dl_name'],
                        'country_code'  => $this->country_code
                    );
                    $dlModel->insertRow($dl);
                }
            }
            /* 相关下载 end */
            if ($model && $aid = $model->getData('id')) {
                return $this->redirect(url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }

        }
        return $this->error(Lang::get('incorrect operation'));
    }

    public function edit($id = 0) {
        $productModel = model('product');
        $id = intval($id);
        if ($id > 0) {
            $product = $productModel->getRow($id);
            if (!$product && !is_array($product)) {
                return $this->error('数据有误,请检查后再操作');
            }
            $value['product'] = $product;
        } else {
            return $this->error('数据有误,请检查后再操作');
        }
        $cid = isset($product['cid']) ? $product['cid'] : 0;
        $argc_where = array('pid' => 0, 'stat' => 0, 'country_code' => $this->country_code, 'isshow' => 1);
        $argc_order = array('sort' => 'asc', 'id' => 'asc');
        $argc_field = array('id', 'pid', 'haschild', 'name', 'sort');
        $categoryOptions = model('product_category')->getCategoryOptions($cid, $argc_where, $argc_order, $argc_field, 100);
        $value['supplierOption'] = '';
        $value['typeOption'] = '';
        $value['brandOption'] = '';
        $value['categoryOptions'] = $categoryOptions;
        $value['cid'] = $cid;
        $value['product_attr'] = is_null(json_decode($product['product_attr'])) ?  $product['product_attr'] : json_decode($product['product_attr']);
        //$attr_content = $this->build_attr_htmls($product['type_id'], $product['id']);
        //$value['attr_content'] = $attr_content;
        $tmp_product_images = model('product_image')->getList(array('product_id' => $product['id']), ['image_sort' => 'asc', 'id' => 'asc',]);

        $product_images = [];
        $productImages = [];
        $count = 0;
        foreach ($tmp_product_images as $k => &$v) {
            $count++;
            
            //echo "
******"; print_r(json_decode($v['image_url']));    
            if (is_string($v['image_url']) && json_decode($v['image_url'])) {
                $v['image_url'] = json_decode($v['image_url']);
                $productImages[] = $v;
                
            }
           

            else{
                $productImages[$v['image_color']][] = $v;
            }
            
          
           
        }
              
        foreach($productImages as $color => $att_item) {
            $product_images[] = $att_item;
        }


        unset($tmp_product_images);

        // tiaoshi($product_images);die;
        $value['image_row'] = $count;
        $value['product_images'] = $product_images;

        $value['product_two_img'] = model('product_two_img')->getList(array('product_id'=> $product['id']),['id' => 'asc',]);//print_r($value['product_product']);die;
        //$value['product_bkimg'] = model('product_bk_img')->getList(array('product_id'=> $product['id']),['id' => 'asc',]);
        $value['product_dls'] = model('product_dl')->getList(array('product_id' => $product['id']), ['dl_sort' => 'asc', 'id' => 'asc',]);
        $value['product_relateds'] = model('product')->getRelatedProductList(array('pr.product_id' => $product['id']), ['pr.related_sort' => 'asc', 'pr.id' => 'asc',], ['p.id' => 'id', 'p.name', 'pr.id' => 'related_id', 'pr.related_product_id', 'pr.related_sort', 'pr.related_desc']);
        // tiaoshi($value['product_images']);die;
        
        $value['filepath'] = 'product/'.strtoupper(str_replace('ORICO-','',$product['brand_id']));
        if(session('cit') == 'us') {
            $value['filepath'] = 'uk/product/'.strtoupper(str_replace('ORICO-','',$product['brand_id']));
        }
        
        
        $this->assign($value);
        return $this->fetch();
    }

    public function update() {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            // tiaoshi($data);die;
            if (empty($data) || !is_array($data)) {
                return $this->error(Lang::get('incorrect operation'));
            }
            $validaterule = ['name' => 'require', 'cid' => 'number|between:0,2147483647',];
            $validatemsg = ['name.require' => '名称不能为空', 'cid.between' => '所属上级值无效',];
            $valid_result = $this->validate($data, $validaterule, $validatemsg);
            if (true !== $valid_result) {
                // 验证失败 输出错误信息
                return $this->error($valid_result);
            }
            $sort = intval($data['sort']);
            /* 产品描述 start */
            $product_desc = [];
            if (isset($data['product_desc'])) {
                foreach ($data['product_desc'] as $desc) {
                    if ($desc['desc_title']) {
                        $product_desc[] = $desc;
                    }
                }
            }

            /* 产品描述 end */
            /*其它信息*/
            $product_view = [];
            if (isset($data['product_view']) && $data['product_view'] != '') {
                $arr_product_view = [];
                $str_product_view = trim(trim($data['product_view']), '#');

                $tmp_product_view = explode("#", $str_product_view);

                foreach ($tmp_product_view as $key => $value) {
                    $tmp = explode(":", $value, 2);

                    if (!is_array($tmp) || !isset($tmp[0]) || !isset($tmp[1]))
                    {
                        return $this->error('参数格式错误');
                    }
                    $arr_product_view[$key]['desc_title'] = trim($tmp[0]);
                    $arr_product_view[$key]['desc_desc'] = trim($tmp[1]);
                }

                foreach ($arr_product_view as $desc) {
                    if ($desc['desc_title']) {
                        $product_view[] = $desc;
                    }
                }
            }

            $keyword = '';
            if (isset($data['keyword']))
            {
                $str_keyword = trim(trim($data['keyword']), '#');
                $arr_keyword = explode("#", $str_keyword);
                foreach ($arr_keyword as $key => $value) {
                    $keyword .= trim($value) . ',';
                }
                $keyword = trim($keyword, ',');
            }
            
            //属性
            $product_attr= isset($data['product_attr']) ? json_encode($data['product_attr']) : '';

            
            /*其它信息 end*/
            $set = array(
                'id' => $data['id'],
                //'tags' => $data['tags'],
                'cid' => $data['cid'],
                 'brand_id' => $data['brand_id'],
                'name' => $data['name'],
                'shortname' => isset($data['shortname']) ? $data['shortname'] : '',
                'description' => isset($data['description']) ? $data['description'] : '',
                'product_attr' => $product_attr,
                'updatetime' => time(),
                'sort' => $sort < 2147483647 ? $sort : 2147483647,
                'isnew' => $data['isnew'],
                'ishot' => $data['ishot'],
                'isfeatured' => isset($data['isfeatured']) ? $data['isfeatured'] : 0,
                'recommend' => isset($data['recommend']) ? $data['recommend'] : 0,
                'videopath' => $data['videopath'],
                'ld_md_content' => $data['ld_md_content'],
                'stock_quantity' => isset($data['stock_quantity']) ? intval($data['stock_quantity']) : 10,
                'cpyanse' => isset($data['cpyanse']) ? $data['cpyanse']*20 : 0,
                'seo_title' => $data['seo_title'],
                'seo_keyword' => $data['seo_keyword'],
                'seo_description' => $data['seo_description'],
                'tags' => isset($data['tags']) ? $data['tags'] : '',
                'url_tm' => isset($data['url_tm']) ? $data['url_tm'] : '',
                'url_jd' => isset($data['url_jd']) ? $data['url_jd'] : '',
                'type_id' => isset($data['type_id']) ? $data['type_id'] : 0,
                'product_desc' => serialize($product_desc),
                'onelist' => $data['onelist'],
                'list_bk_img' => $data['list_bk_img'],
                'product_view' => isset($data['product_view']) ?  serialize($product_view)  :"",
                'rmimg'=>isset($data['rmimg']) ? $data['rmimg'] : '',
                'plid'=>isset($data['plid']) ? $data['plid'] : 0,
                'keyword' => $keyword,
                'update_status' => 1
            );
            $productModel = model('product');
            $model = $productModel->updateRow($set);
            $last_update_id = $model->getData('id');
            if (!$last_update_id) {
                return $this->error(Lang::get('operation failed'));
            }
            /*淘宝评论*/
            /*if(isset($data['tbpl'])){
                $tlpl = Loader::model('Tbpl');
                $where = ['id'=>$data['tbpl']];
                $arr = ['product_id'=>$data['id']];
                $updat = $tlpl->updateRow($arr,$where);
            }*/
            /* 相关图片 start */
            // if (isset($data['product_image'])) {
            //     $imageModel = model('product_image');
                // $product_images = $imageModel->getList(array('product_id' => $last_update_id));
                // // 取得原有的值
                // $product_image_list = array();
                // foreach ($product_images as $imgRow) {
                //     $product_image_list[$imgRow['id']] = array('sign' => 'delete', 'where' => array('id' => $imgRow['id']), 'data' => array());
                // }
            //     //$imageModel->updateRow(['stat' => -1], ['product_id' => $last_update_id, 'stat' => 0]);
            //     foreach ($data['product_image'] as $product_image_id => $product_image) {
            //         if (isset($product_image_list[$product_image_id])) {
            //             $product_image_list[$product_image_id] = array('sign' => 'update', 'where' => array('id' => $product_image_id), 'data' => array(
            //                 'product_id' => $last_update_id,
            //                 'image_url' => $product_image['image_url'],
            //                 'image_sort' => is_numeric($product_image['image_sort']) ? intval($product_image['image_sort']) : 0,
            //                 'image_desc' => $product_image['image_desc'],
            //                 'image_color' => $product_image['image_color'],
            //                 'original_url' => $product_image['image_url']
            //             ));
            //         } else {
            //             $product_image_list[$product_image_id] = array('sign' => 'insert', 'where' => [], 'data' => array(
            //                 'product_id' => $last_update_id,
            //                 'image_url' => $product_image['image_url'],
            //                 'image_sort' => is_numeric($product_image['image_sort']) ? intval($product_image['image_sort']) : 0,
            //                 'image_desc' => $product_image['image_desc'],
            //                 'image_color' => $product_image['image_color'],
            //                 'original_url' => $product_image['image_url']
            //             ));
            //         }
            //         //$imageModel->insertRow($image);
            //     }
            //     foreach ($product_image_list as $product_image_id => $image) {
            //         if ($image['sign'] == 'insert') {  
            //             $imageModel->insertRow($image['data']);
            //         } elseif ($image['sign'] == 'update') {
            //             $imageModel->updateRow($image['data'], $image['where']);
            //         } else {
            //             $imageModel->deleteRow($image['where']);
            //         }
            //     }
            // }

            model('product_image')->where(['product_id' => $last_update_id])->update(['stat' => -1]);
            if (isset($data['product_image']) && isset($data['arr_product_img']))
            {
                
               $productAttr = array();
                foreach($data['product_image'] as $km => $feeds) {
                    $groups = array(
                        'type' =>     $feeds['type'],
                        'sort' =>     $feeds['sort'],
                        'sku' =>     $feeds['sku'],
                    );
                    $productAttr[] = $groups;
                }
                //$data['product_image']      = array_merge($data['product_image']);
                $data['arr_product_img']    = array_merge($data['arr_product_img']);   
                 //echo "
=="; print_r($productAttr);
                foreach ($data['arr_product_img'] as $key => $value) {
                    
                    
                    if (empty($value))
                        continue;
                    $images['product_id']   = $last_update_id;
                    //$images['image_color']  = isset($data['product_image'][$key]) ? $data['product_image'][$key]['image_color'] : '';
                   // $images['image_sort']   = isset($data['product_image'][$key]) ? $data['product_image'][$key]['image_sort'] : '';
                    $images['sku']   = isset($productAttr[$key]['sku']) ? $productAttr[$key]['sku'] : '';
                    $images['country_code'] = $this->country_code;
            
                    $newImage = array_filter($value, function($img){
                       return $img!= '/uploads/nopic.jpg'; 
                    });
                    $images['image_url'] = json_encode($newImage);
                    
                    $arrribute = array();
                    
                    
                    if(is_array($data['product_attr'])){
                        //$poductAttr = $data['product_image'][$key]; 
                        //echo $key."
=="; print_r($productAttr);
                        
                        
                         foreach($productAttr[$key]['type'] as $kt => $attrValue ) {
                                $arrribute[$kt] = array(
                                        $data['product_attr'][$kt] => trim($attrValue),
                                        'sort'=> isset($productAttr[$key]['sort']) ? $productAttr[$key]['sort'][$kt]: ''
                                );                                
                           
                        }

                        
                    }
                   
                    $images['image_color']   = json_encode($arrribute);
                    
                    //echo "
=="; print_r($images) ;die;
                     
                    model('product_image')->insert($images);
                   
                }
            }
            
            /* 相关图片 end */

            /* 二级列表主图片 start */
            if (isset($data['product_product'])) {
                $imageModel = model('product_two_img');
                $product_images = $imageModel->getList(array('product_id' => $last_update_id));
                // 取得原有的值
                $product_image_list = array();
                foreach ($product_images as $imgRow) {
                    $product_image_list[$imgRow['id']] = array('sign' => 'delete', 'where' => array('id' => $imgRow['id']), 'data' => array());
                }
                //$imageModel->updateRow(['stat' => -1], ['product_id' => $last_update_id, 'stat' => 0]);
                foreach ($data['product_product'] as $product_image_id => $product_image) {
                    if (isset($product_image_list[$product_image_id])) {
                        $product_image_list[$product_image_id] = array('sign' => 'update', 'where' => array('id' => $product_image_id), 'data' => array(
                            'product_id' => $last_update_id,
                            'image_url' => $product_image['image_url'],
                            'image_bk_color' => isset($product_image['image_bkcolor']) ? $product_image['image_bkcolor'] : '',
                            'image_color' => isset($product_image['image_color']) ? trim($product_image['image_color']) : '',
                            'original_url' => $product_image['image_url'],
                        ));
                    } else {
                        $product_image_list[$product_image_id] = array('sign' => 'insert', 'where' => [], 'data' => array(
                            'product_id' => $last_update_id,
                            'image_url' => $product_image['image_url'],
                            'image_bk_color' => isset($product_image['image_bkcolor']) ? $product_image['image_bkcolor'] : '',
                            'image_color' => isset($product_image['image_color']) ? trim($product_image['image_color']) : '',
                            'original_url' => $product_image['image_url'],
                        ));
                    }
                    //$imageModel->insertRow($image);
                }

                foreach ($product_image_list as $product_image_id => $image) {
                    if ($image['sign'] == 'insert') {
                        $imageModel->insertRow($image['data']);
                    } elseif ($image['sign'] == 'update') {
                        $imageModel->updateRow($image['data'], $image['where']);
                    } else {
                        $imageModel->deleteRow($image['where']);
                    }
                }
            } else {
                model('product_two_img')->deleteRow(['product_id' => $last_update_id]);
            }
            /* 二级列表主图片 end */


            /* 爆款主图片 start */
            /*if (isset($data['bkimg_row'])) {
                $imageModel = model('product_bk_img');
                $product_images = $imageModel->getList(array('product_id' => $last_update_id));
                // 取得原有的值
                $product_image_list = array();
                foreach ($product_images as $imgRow) {
                    $product_image_list[$imgRow['id']] = array('sign' => 'delete', 'where' => array('id' => $imgRow['id']), 'data' => array());
                }
                //$imageModel->updateRow(['stat' => -1], ['product_id' => $last_update_id, 'stat' => 0]);
                foreach ($data['bkimg_row'] as $product_image_id => $product_image) {
                    if (isset($product_image_list[$product_image_id])) {
                        $product_image_list[$product_image_id] = array('sign' => 'update', 'where' => array('id' => $product_image_id), 'data' => array(
                            'product_id' => $last_update_id,
                            'image_url' => $product_image['image_url'],
                            'image_bk_color' => $product_image['image_bkcolor'],
                            'image_color' => $product_image['image_color'],
                            'original_url' => $product_image['image_url'],
                        ));
                    } else {
                        $product_image_list[$product_image_id] = array('sign' => 'insert', 'where' => [], 'data' => array(
                            'product_id' => $last_update_id,
                            'image_url' => $product_image['image_url'],
                            'image_bk_color' => $product_image['image_bkcolor'],
                            'image_color' => $product_image['image_color'],
                            'original_url' => $product_image['image_url'],
                        ));
                    }
                    //$imageModel->insertRow($image);
                }
                foreach ($product_image_list as $product_image_id => $image) {
                    if ($image['sign'] == 'insert') {
                        $imageModel->insertRow($image['data']);
                    } elseif ($image['sign'] == 'update') {
                        $imageModel->updateRow($image['data'], $image['where']);
                    } else {
                        $imageModel->deleteRow($image['where']);
                    }
                }
            }else{
                $imageModel = model('product_bk_img');
                $where = ['product_id' => $last_update_id,];
                $stat = ['stat'=>-1];/*print_r($data);die;*/
                //$updata = $imageModel->updateRow($stat,$where);//print_r($updata);die;
            //}*/
            /* 爆款主图片 end */


            /* 相关产品 start */
            if (isset($data['product_related'])) {

                $relatedModel = model('product_related');
                $product_relateds = $relatedModel->getList(array('product_id' => $last_update_id));
                // 取得原有的值
                $product_related_list = array();
                foreach ($product_relateds as $imgRow) {
                    $product_related_list[$imgRow['id']] = array('sign' => 'delete', 'where' => array('id' => $imgRow['id']), 'data' => array());
                }

                // $relatedModel->updateRow(['stat' => -1], ['product_id' => $last_update_id, 'stat' => 0]);
                foreach ($data['product_related'] as $product_related_id => $product_related) {
                    if (isset($product_related_list[$product_related_id])) {
                        $product_related_list[$product_related_id] = array('sign' => 'update', 'where' => array('id' => $product_related_id), 'data' => array(
                            //'product_id' => $last_update_id,
                            'related_product_id' => $product_related['related_product_id'],
                            'related_sort' => is_numeric($product_related['related_sort']) ? intval($product_related['related_sort']) : 0,
                            'related_desc' => $product_related['related_desc'],
                        ));
                    } else {
                        $product_related_list[$product_related_id] = array('sign' => 'insert', 'where' => [], 'data' => array(
                            'product_id' => $last_update_id,
                            'related_product_id' => $product_related['related_product_id'],
                            'related_sort' => is_numeric($product_related['related_sort']) ? intval($product_related['related_sort']) : 0,
                            'related_desc' => $product_related['related_desc'],
                        ));
                    }
                    //$relatedModel->insertRow($related);
                }
                // tiaoshi($product_related_list);die;
                foreach ($product_related_list as $product_related_id => $related) {
                    if ($related['sign'] == 'insert') {
                        $relatedModel->insertRow($related['data']);
                    } elseif ($related['sign'] == 'update') {
                        $relatedModel->updateRow($related['data'], $related['where']);
                    } else {
                        $relatedModel->deleteRow($related['where']);
                    }
                }
            } else {
                $relatedModel = model('product_related');
                $product_relateds = $relatedModel->getList(array('product_id' => $last_update_id));
                foreach ($product_relateds as $key => $value) {
                    $relatedModel->deleteRow(['id' => $value['id']]);
                }
            }
            /* 相关产品 end */

            /* 相关下载 start */
            $dlModel = model('product_dl');
            $product_dls = $dlModel->getList(array('product_id' => $last_update_id));
            if (isset($data['product_dl'])) {

                $dlModel = model('product_dl');
                $product_dls = $dlModel->getList(array('product_id' => $last_update_id));
                // 取得原有的值
                $product_dl_list = array();
                foreach ($product_dls as $dlRow) {
                    $product_dl_list[$dlRow['id']] = array('sign' => 'delete', 'where' => array('id' => $dlRow['id']), 'data' => array());
                }
                //$dlModel->updateRow(['stat' => -1], ['product_id' => $last_update_id, 'stat' => 0]);
                foreach ($data['product_dl'] as $product_dl_id => $product_dl) {
                    if (isset($product_dl_list[$product_dl_id])) {
                        $product_dl_list[$product_dl_id] = array('sign' => 'update', 'where' => array('id' => $product_dl_id), 'data' => array(
                            //'product_id' => $last_update_id,
                            'dl_url' => $product_dl['dl_url'],
                            'dl_sort' => is_numeric($product_dl['dl_sort']) ? intval($product_dl['dl_sort']) : 0,
                            'dl_desc' => isset($product_dl['dl_desc']) ? $product_dl['dl_desc'] : '',
                            'dl_type' => $product_dl['dl_type'],
                            'dl_name' => $product_dl['dl_name'],
                        ));
                    } else {
                        $product_dl_list[$product_dl_id] = array('sign' => 'insert', 'where' => [], 'data' => array(
                            'product_id' => $last_update_id,
                            'dl_url' => $product_dl['dl_url'],
                            'dl_sort' => is_numeric($product_dl['dl_sort']) ? intval($product_dl['dl_sort']) : 0,
                            'dl_desc' => isset($product_dl['dl_desc']) ? $product_dl['dl_desc'] : '',
                            'dl_type' => $product_dl['dl_type'],
                            'dl_name' => $product_dl['dl_name'],
                        ));
                    }
                    //$dlModel->insertRow($dl);
                }

                foreach ($product_dl_list as $product_dl_id => $dl) {
                    if ($dl['sign'] == 'insert') {
                        $dlModel->insertRow($dl['data']);
                    } elseif ($dl['sign'] == 'update') {
                        $dlModel->updateRow($dl['data'], $dl['where']);
                    } else {
                        $dlModel->deleteRow($dl['where']);
                    }
                }
            }else{
                $dlModel->deleteRow(array('product_id' => $last_update_id));
            }


            /* 相关下载 end */
            if ($model && $model->getData('id')) {
                return $this->redirect(url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }
        }
        return $this->error(Lang::get('incorrect operation'));
    }

    public function content() {
        $aid = $this->request->param('id', 0);
        $aid = intval($aid);
        if ($aid > 0) {
            $addproduct = Loader::model('ProductAddition')->getRow(['aid' => $aid], ['id', 'aid', 'content']);
            if (empty($addproduct)) {
                return $this->error(Lang::get('incorrect operation'));
            }
            $value = [
                'addproduct' => $addproduct,
            ];
            $this->assign($value);
            $this->view->engine(['type' => 'php', 'view_suffix' => 'html']);
            return $this->fetch();
        }
        return $this->error(Lang::get('incorrect operation'));
    }

    public function modallists() {
        $inputid = $this->request->param('inputid', '', 'urldecode');
        $titleid = $this->request->param('titleid', '', 'urldecode');
        $callback = $this->request->param('callback', '', 'urldecode');
        $filter_name = $this->request->param('filter_name', '', 'urldecode');
        $arg_where = array('stat' => 0, 'country_code' => $this->country_code);
        $arg_order = array('sort' => 'asc', 'id' => 'desc');
        $arg_field = array('id', 'name', 'item_number', 'tags', 'list_bk_img',);
        if (!empty($filter_name)) {
            $arg_where['brand_id|name'] = ['like', '%' . trim($filter_name) . '%'];
            //$arg_where['brand_id'] = ['like', '%' . trim($filter_name) . '%'];
        }
        Config::set('url_common_param', true);
        Config::set('paginate.query', array_filter(['inputid' => $inputid, 'titleid' => $titleid, 'callback' => $callback, 'filter_name' => $filter_name])); //分页参数
        $dataObject = model('product')->getPageList($arg_where, $arg_order, $arg_field, 12, false);
        $value = [
            'list' => $dataObject->isEmpty() ? null : $dataObject->items(), //$dataObject->getCollection()->toArray()
            'page' => $dataObject->render(),
            'total' => $dataObject->total(),
            'inputid' => $inputid,
            'titleid' => $titleid,
            'callback' => $callback,
            'filter_name' => $filter_name,
        ];
        $this->assign($value);
        Config::set('default_ajax_return', 'html');
        $this->view->engine(['type' => 'php', 'view_suffix' => 'html']);
        return $this->fetch();
    }

    public function updatesort() {
        $id = $this->request->param('id', 0);
        $sort = $this->request->param('sort', 0);
        $sort = intval($sort);
        $id = intval($id);
        if ($id > 0 && $sort < 2147483647) {
            $model = model('product')->updateRow(['id' => $id, 'sort' => $sort]);
            if ($model && $model->getData('id')) {
                return $this->success(Lang::get('operation successed'), url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }
        }
        return $this->error(Lang::get('incorrect operation'));
    }

    public function toggleisnew() {
        $id = $this->request->param('id', 0);
        $flag = $this->request->param('flag', 0);
        $id = intval($id);
        if ($id > 0) {
            $model = model('product')->updateRow(['id' => $id, 'isnew' => $flag]);
            if ($model && $model->getData('id')) {
                return $this->success(Lang::get('operation successed'), url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }
        }
        return $this->error(Lang::get('incorrect operation'));
    }

    public function toggleishot() {
        $id = $this->request->param('id', 0);
        $flag = $this->request->param('flag', 0);
        $id = intval($id);
        if ($id > 0) {
            $model = model('product')->updateRow(['id' => $id, 'ishot' => $flag]);
            if ($model && $model->getData('id')) {
                return $this->success(Lang::get('operation successed'), url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }
        }
        return $this->error(Lang::get('incorrect operation'));
    }

    public function togglerecommend() {
        $id = $this->request->param('id', 0);
        $flag = $this->request->param('flag', 0);
        $id = intval($id);
        if ($id > 0) {
            $model = model('product')->updateRow(['id' => $id, 'recommend' => $flag]);
            if ($model && $model->getData('id')) {
                return $this->success(Lang::get('operation successed'), url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }
        }
        return $this->error(Lang::get('incorrect operation'));
    }

    public function togglefeatured() {
        $id = $this->request->param('id', 0);
        $flag = $this->request->param('flag', 0);
        $id = intval($id);
        if ($id > 0) {
            $model = model('product')->updateRow(['id' => $id, 'isfeatured' => $flag]);
            if ($model && $model->getData('id')) {
                return $this->success(Lang::get('operation successed'), url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }
        }
        return $this->error(Lang::get('incorrect operation'));
    }

    public function toggleonsale() {
        $id = $this->request->get('id', 0);
        $flag = $this->request->get('flag', 0);
        $id = intval($id);
        if ($id > 0) {
            $result = model('product')->updateRow(['id' => $id, 'is_onsale' => $flag]);
            if ($result) {
                return $this->success(Lang::get('operation successed'), url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }
        }
        return $this->error(Lang::get('incorrect operation'));
    }

    public function copy($id = 0) {
        $id = intval($id);
        if ($id > 0) {
            $product = model('product')->getRow($id);
            if (empty($product)) {
                return $this->error(Lang::get('incorrect operation'));
            }
            $value['product'] = $product;
        } else {
            return $this->error(Lang::get('incorrect operation'));
        }
        $value['addproduct'] = Loader::model('ProductAddition')->getRow(['aid' => $id]);
        $cid = isset($product['cid']) ? $product['cid'] : 0;
        $arg_where = array('pid' => 0, 'stat' => 0, 'country_code' => $this->country_code);
        $arg_order = array('sort' => 'asc', 'id' => 'asc');
        $arg_field = array('id', 'pid', 'haschild', 'name', 'sort');
        $categoryOptions = model('product_category')->getCategoryOptions($cid, $arg_where, $arg_order, $arg_field, 100);
        $arg_where = array('stat' => 0);
        $arg_order = array('id' => 'asc');
        $arg_field = array('id', 'name');
        //$brandOption = Loader::model('Brand')->getOption($product['brand_id'], $arg_where, $arg_order, $arg_field, 100);
        //$typeOption = Loader::model('AttributeType')->getOption($product['type_id'], $arg_where, $arg_order, $arg_field, 100);
        //$supplierOption = Loader::model('Supplier')->getOption($product['supplier_id'], $arg_where, $arg_order, $arg_field, 100);
        $value['supplierOption'] = '';
        $value['typeOption'] = '';
        $value['brandOption'] = '';
        $value['categoryOptions'] = $categoryOptions;
        $value['cid'] = $cid;
        $this->assign($value);
        return $this->fetch();
    }

    public function movecategory() {
        $cid = $this->request->post('cid', 0);
        $ids = $this->request->post('ids');
        $cid = intval($cid);
        if ($this->request->isPost() && $cid && $ids) {
            $result = model('product')->updateRows(['cid' => $cid], ['id' => ['in', $ids]]);
            if ($result) {
                return $this->success(Lang::get('operation successed'), url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }
        }
        return $this->error(Lang::get('incorrect operation'));
    }

    public function recommends() {
        $ids = $this->request->post('ids');
        if ($this->request->isPost() && $ids) {
            $result = model('product')->updateRows(['recommend' => 1], ['id' => ['in', $ids]]);
            if ($result) {
                return $this->success(Lang::get('operation successed'), url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }
        }
        return $this->error(Lang::get('incorrect operation'));
    }

    public function featureds() {
        $ids = $this->request->post('ids');
        if ($this->request->isPost() && $ids) {
            $result = model('product')->updateRows(['isfeatured' => 1], ['id' => ['in', $ids]]);
            if ($result) {
                return $this->success(Lang::get('operation successed'), url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }
        }
        return $this->error(Lang::get('incorrect operation'));
    }

    public function delete($id = 0) {
        $id = intval($id);
        if ($id > 0) {
            $result = model('product')->deleteRow($id);
            if ($result) {
                return $this->success(Lang::get('operation successed'), url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }
        }
        return $this->error(Lang::get('incorrect operation'));
    }

    public function deletes() {
        $ids = $this->request->post('ids');
        if ($this->request->isPost() && $ids) {
            $result = model('product')->deleteRows($ids);
            if ($result) {
                return $this->success(Lang::get('operation successed'), url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }
        }
        return $this->error(Lang::get('incorrect operation'));
    }

    public function recycle() {
        $skeyword = $this->request->get('skeyword', '', 'urldecode');
        $arg_where = ['a.stat' => -1, 'a.siteid' => $this->siteid, 'a.country_code' => $this->country_code];
        $arg_order = ['a.id' => 'desc'];
        $arg_field = ['a.*', 'c.id' => 'categoryid', 'c.name' => 'categoryname'];
        if (!empty($skeyword)) {
            $skeyword = trim($skeyword);
            $arg_where['a.name|a.brand_id'] = ['like', '%' . $skeyword . '%'];
            $search['skeyword'] = $skeyword;
            Config::set('paginate.query', ['skeyword' => $skeyword]); //分页参数
        } else {
            $search['skeyword'] = '';
        }
        $dataObject = model('product')->getRecycleLists($arg_where, $arg_order, $arg_field, 12);
        $argc_where = array('pid' => 0, 'stat' => 0);
        $argc_order = array('sort' => 'asc', 'id' => 'asc');
        $argc_field = array('id', 'pid', 'haschild', 'name', 'sort');
        $categoryOptions = model('product_category')->getCategoryOptions(0, $argc_where, $argc_order, $argc_field, 100);
        $value = [
            'categoryOptions' => $categoryOptions,
            'list' => $dataObject->isEmpty() ? null : $dataObject->items(), //$dataObject->getCollection()->toArray()
            'page' => $dataObject->render(),
            'search' => $search,
        ];
        $this->assign($value);
        return $this->fetch();
    }

    public function recovery($id = 0) {
        $id = intval($id);
        if ($id > 0) {
            $model = model('product')->updateRow(['id' => $id, 'stat' => 0]);
            if ($model && $model->getData('id')) {
                return $this->success(Lang::get('operation successed'), url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }
        }
        return $this->error(Lang::get('incorrect operation'));
    }

    public function recoverys() {
        $ids = $this->request->post('ids');
        if ($this->request->isPost() && $ids) {
            $result = model('product')->updateRows(['stat' => 0], ['id' => ['in', $ids]]);
            if ($result) {
                return $this->success(Lang::get('operation successed'), url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }
        }
        return $this->error(Lang::get('incorrect operation'));
    }


    public function destroy($id = 0) {
        $id = intval($id);
        if ($id > 0) {
            $result = model('product')->destroyRow($id);
            if ($result) {
                return $this->success(Lang::get('operation successed'), url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }
        }
        return $this->error(Lang::get('incorrect operation'));
    }

    public function destroys() {
        $ids = $this->request->post('ids');
        if ($this->request->isPost() && $ids) {
            $result = model('product')->destroyRows($ids);
            if ($result) {
                return $this->success(Lang::get('operation successed'), url('/admin/product/lists'));
            } else {
                return $this->error(Lang::get('operation failed'));
            }
        }
        return $this->error(Lang::get('incorrect operation'));
    }
    public function cont(){
        $data = $_POST;
        $id = $data['product'];
        $arg_order = ['a.id' => 'desc'];
        $arg_field = ['a.*', 'c.id' => 'categoryid', 'c.name' => 'categoryname'];

        foreach ($id as $where) {
            $where = [
                'a.id' => $where,
                'a.stat' => 0,
                'a.country_code' => $this->country_code
            ];
            $result = model('product')->getProductLists($where, $arg_order, $arg_field, 12);
        }

        $this->assign($result);
        return $this->fetch('product/add');
    }
    public function productreated(){
        $inputid = $this->request->param('inputid', '', 'urldecode');
        $titleid = $this->request->param('titleid', '', 'urldecode');
        $callback = $this->request->param('callback', '', 'urldecode');
        $filter_name = $this->request->param('filter_name', '', 'urldecode');
        $arg_where = array('stat' => 0, 'country_code' => $this->country_code);
        $arg_order = array('sort' => 'asc', 'id' => 'desc');
        $arg_field = array('id', 'name', 'item_number', 'tags', 'picture',);
        if (!empty($filter_name)) {
            $arg_where['name'] = ['like', '%' . trim($filter_name) . '%'];
        }
        Config::set('url_common_param', true);
        Config::set('paginate.query', array_filter(['inputid' => $inputid, 'titleid' => $titleid, 'callback' => $callback, 'filter_name' => $filter_name])); //分页参数
        $dataObject = model('product')->getPageList($arg_where, $arg_order, $arg_field, 12, false);
        $value = [
            'list' => $dataObject->isEmpty() ? null : $dataObject->items(), //$dataObject->getCollection()->toArray()
            'page' => $dataObject->render(),
            'total' => $dataObject->total(),
            'inputid' => $inputid,
            'titleid' => $titleid,
            'callback' => $callback,
            'filter_name' => $filter_name,
        ];
        $this->assign($value);
        Config::set('default_ajax_return', 'html');
        $this->view->engine(['type' => 'php', 'view_suffix' => 'html']);
        return $this->fetch();
    }
    public function chickbrandid($id){
        $where = ['brand_id'=>$id, 'stat' => 0, 'country_code' => $this->country_code];
        $product = model('product')->where($where)->find();
        $direct = $this->basePath;
        
        if($product){
            echo '产品型号已经存在,无需重新添加';
        }
        else{
            $filepath = '/product/'.str_replace('ORICO-','',strtoupper($id));
            if(session('cit') == 'us') {
                $filepath = '/uk/product/'.str_replace('ORICO-','',strtoupper($id));
            }            
            //mkdir($direct.$filepath, 0777);
            //chmod($direct.$filepath, 0777);
            //@touch($direct.$filepath . '/' . 'index.html');
            
            if(!is_dir($direct.$filepath)){
                mkdir($direct.$filepath, 0777, true);
                //chmod($direct.$filepath, 0777, true);
            }
            
            echo str_replace('ORICO-','',strtoupper($id)).'目录创建成功';
            //echo "请创建图片目录".str_replace('ORICO-','',strtoupper($id)).'';
        }
        exit;
    }

    public function export() {
        $arg_where = ['a.stat' => 0, 'a.siteid' => $this->siteid, 'a.country_code' => $this->country_code];
        $data = $this->request->param();

        if (isset($data['name']) && $data['name']) {
            $arg_where['a.name'] = ['like', '%' . $data['name'] . '%'];
            $search['name'] = $data['name'];
        } else {
            $search['name'] = '';
        }
        if (isset($data['cid']) && $data['cid']) {
            $childIDArray = model('product_category')->getChildIDArray($data['cid']);
            $arg_where['a.cid'] = count($childIDArray) == 1 ? $data['cid'] : ['in', $childIDArray];
            $search['cid'] = $data['cid'];
        } else {
            $search['cid'] = 0;
        }
        if (isset($data['tags']) && $data['tags']) {
            $arg_where['a.tags'] = ['like', '%' . $data['tags'] . '%'];
            $search['tags'] = $data['tags'];
        } else {
            $search['tags'] = '';
        }
       
        $search['timebegin'] = isset($data['timebegin']) ? strtotime($data['timebegin']) : 0;
        $search['timeend'] = isset($data['timeend']) ? strtotime($data['timeend']) : 0;
        if ($search['timeend'] - $search['timebegin'] > 0) {
            $arg_where['a.createtime'] = ['between', [$search['timebegin'], $search['timeend']]];
        } else {
            if ($search['timebegin'] > 0 && empty($search['timeend'])) {
                $arg_where['a.createtime'] = ['gt', $search['timebegin']];
            }
        }

        if (!empty($data['field'])) {
            $fields = $data['field'];
        } else {
            $fields = array('id' => 'ID', 'brand_id' => '产品型号', 'url' => '产品链接', 'cid' => '所属分类', 'name' => '产品名称', 'shortname' => '副标题', 'recommend' => '是否推荐', 'ishot' => '是否热门',  'multi_color' => '是否有多颜色', 'list_bk_img' => '是否有一级列表图' , 'is_list2' => '是否有二级列表图', 'url_tm' => '天猫链接', 'url_jd' => '京东链接', 'seo_title' => 'SEO标题', 'seo_keyword' => 'SEO关键词', 'seo_description' => 'SEO描述', 'product_view' => '产品参数', 'related_product' => '关联产品', 'driver' => '是否有驱动', 'is_show' => '是否上架', 'cpyanse' => '评分', 'createtime' => '发布时间');
        }

        $argc_where = array('pid' => 0, 'stat' => 0);
        $argc_order = array('sort' => 'asc', 'id' => 'asc');
        $argc_field = array('id', 'pid', 'haschild', 'name', 'sort');
        $categoryOptions = model('product_category')->getCategoryOptions($search['cid'], $argc_where, $argc_order, $argc_field, 100);

        if (empty($data['submit'])) {
            $value = ['categoryOptions' => $categoryOptions, 'fields' => $fields];
            $this->assign($value);
            return $this->fetch();
        }

        $arg_order = ['c.sort' => 'asc', 'c.id' => 'asc'];
        $arg_field = array_map(function ($value) {
            return 'a.' . $value;
        }, array_keys($fields));
        $arg_field['c.id'] = 'categoryid';
        $arg_field['c.name'] = 'categoryname';
        $arg_field['c.pid'] = 'pid';

        set_time_limit(36000);
        ini_set('memory_limit', '512M');
        $total = model('product')->getExportSearchProductLists($arg_where, $arg_order, null, true);
        $page_size = 1000;
        $totalpage = ceil($total / $page_size);
        $sheet_size = 5 * $page_size;

        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        Loader::import('phpexcel.Classes.PHPExcel', EXTEND_PATH);
        Loader::import('phpexcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
        $objPHPExcel = new \PHPExcel();
        // Set document properties
        $objPHPExcel->getProperties()->setCreator("Call of Duty")
                ->setLastModifiedBy("Call of Duty")
                ->setTitle("Office 2007 XLSX Cod Document")
                ->setSubject("Office 2007 XLSX Cod Document")
                ->setDescription("Cod document for Office 2007 XLSX, generated using PHP classes.")
                ->setKeywords("office 2007 openxml php")
                ->setCategory("Cod result file");
        $page = 0; 
        $sheet = 0; 
        do {
            $start_index = $page * $page_size;
            $arg_order = ['a.cid' => 'asc', 'a.id' => 'asc'];
            $datainfo = model('product')->getExportSearchProductLists($arg_where, $arg_order, [$start_index, $page_size], false, $arg_field);
            
            if (!empty($datainfo)) {
                if (($start_index % $sheet_size) == 0) {
                    if ($sheet) {
                        $objPHPExcel->createSheet();
                    }
                    $sheet++;
                    $i = 0;
                    foreach ($fields as $key => $value) {
                        $objPHPExcel->setActiveSheetIndex($sheet - 1)->setCellValue($cellName[$i] . '1', $value);
                        $i++;
                    }
                    $objPHPExcel->getActiveSheet()->setTitle('sheet' . $sheet);
                    $index = 1;
                }

                foreach ($datainfo as $value) {
                    if (isset($value['cid'])) {
                        $value->data('cid', $value['categoryname']);
                    }
                    if (isset($value['list_bk_img']) && $value['list_bk_img'] != '') {
                        $value->data('list_bk_img', 1);
                    } else {
                        $value->data('list_bk_img', 0);
                    }
                    if (isset($value['createtime'])) {
                        $value->data('createtime', date('Y-m-d H:i:s', $value['createtime']));
                    }
                    if (isset($value['related_product'])) {
                        $value->data('related_product', $value['related_product']);
                    }
                    if (isset($value['product_view'])) {
                        $value->data('product_view', json_encode(unserialize($value['product_view']), JSON_UNESCAPED_UNICODE));
                    }
                    if (isset($value['driver'])) {
                        $value->data('driver', $value['driver']);
                    }
                    $index++;
                    $i = 0;
                    foreach ($fields as $key => $field) {
                        if ($key == 'picture') {
                            $image = '.' . $this->request->root() . $value['picture'];
                            if (@fopen($image, 'r')) {
                                $objDrawing = new \PHPExcel_Worksheet_Drawing();
                                $objDrawing->setPath($image);
                                $objDrawing->setHeight(50);
                                $objDrawing->setWidth(50);
                                $objDrawing->setCoordinates($cellName[$i] . $index);
                                $objDrawing->setWorksheet($objPHPExcel->getActiveSheet());
                            }
                        } else {
                            $objPHPExcel->setActiveSheetIndex($sheet - 1)->setCellValue($cellName[$i] . $index, $value[$key]);
                        }
                        $i++;
                    }
                }
                usleep(10000); 
            }
            $page++; 
            if ($page > 650) {
                break;
            }
        } while ($page < $totalpage);
        $objPHPExcel->setActiveSheetIndex(0);
        // Redirect output to a client's web browser (Excel2007)
        /*header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . date('YmdHis') . '.xlsx"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0*/
        ob_end_clean();//清除缓冲区,避免乱码
        
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");//文件流
        header("Content-Type: application/download"); //下载文件
        header('Content-Disposition: attachment;filename="' . date('YmdHis') . '.xlsx"');
        header("Content-Transfer-Encoding: binary");
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");//上一次修改时间
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache"); //不缓存页面
        $objWriter->save('php://output');
        exit;
    }

    public function import_save()
    {
        // die;
        set_time_limit(3600);
        // var_dump($_FILES["file"]);die;
        if ($_FILES["file"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "
"; exit; } else { if (file_exists("public/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " 已经存在 "; exit; } else { $file = move_uploaded_file($_FILES["file"]["tmp_name"], './attachs/' . $_FILES["file"]["name"]); $filename = $_FILES["file"]["name"]; $filepath = './attachs/' . $_FILES["file"]["name"]; $suffix = $_FILES["file"]["type"]; Loader::import('phpexcel.Classes.PHPExcel', EXTEND_PATH); Loader::import('phpexcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory'); // $excel = new \PHPExcel(); $excel = \PHPExcel_IOFactory::createReader('Excel2007')->load($filepath, $encode = 'utf-8'); $sheet = $excel->getSheet(0); $row_num = $sheet->getHighestRow();//总行 if ($row_num > 10000) { return $this->error("插入条数超过10000条,请分多次上传。"); } $col_num = $sheet->getHighestColumn();//总列 $like_find = []; $no_find = []; for ($w = 3; $w <= $row_num; $w++) { $a = trim($excel->getActiveSheet()->getCell("A" . $w)->getValue()); $b = trim($excel->getActiveSheet()->getCell("B" . $w)->getValue()); $c = trim($excel->getActiveSheet()->getCell("C" . $w)->getValue()); $d = trim($excel->getActiveSheet()->getCell("D" . $w)->getValue()); $e = trim($excel->getActiveSheet()->getCell("E" . $w)->getValue()); $f = trim($excel->getActiveSheet()->getCell("F" . $w)->getValue()); $g = trim($excel->getActiveSheet()->getCell("G" . $w)->getValue()); $h = trim($excel->getActiveSheet()->getCell("H" . $w)->getValue()); // echo $a, '
', $b, '
', $c, '
', $d, '
', $e, '
', $f, '
', $g, '
', $h;die; if ($a == '') continue; $product_info = model('product')->where(['brand_id' => $a, 'country_code' => 'ZH'])->find(); if (!empty($product_info)) { model('product')->where(['id' => $product_info['id']])->update(['update_status' => 1]); $sku = model('product_sku')->where(['product_id' => $product_info['id'], 'stat' => 0])->find(); if (!empty($sku) && $sku['id'] <= 752) { model('product_sku')->where(['product_id' => $product_info['id']])->update(['stat' => 1]); } $insert_data = [ 'product_id' => $product_info['id'], 'brand_id' => $a, 'version' => $c, 'interface' => $d, 'color' => $e, 'length' => $f, 'regulatory' => $g, 'package' => $h, 'sku' => $b, 'stat' => 0 ]; model('product_sku')->insert($insert_data); } else { $product_info = model('product')->where(['brand_id' => ['like', "$a%"], 'country_code' => 'ZH'])->find(); if (!empty($product_info)) { model('product_sku')->where(['product_id' => $product_info['id']])->update(['stat' => 1]); if (!in_array($a, $like_find)) array_push($like_find, $a); $sku = model('product_sku')->where(['product_id' => $product_info['id'], 'stat' => 0])->find(); if (!empty($sku) && $sku['id'] <= 752) { model('product_sku')->where(['product_id' => $product_info['id']])->update(['stat' => 1]); } $insert_data = [ 'product_id' => $product_info['id'], 'brand_id' => $product_info['brand_id'], 'version' => $c, 'interface' => $d, 'color' => $e, 'length' => $f, 'regulatory' => $g, 'package' => $h, 'sku' => $b, 'stat' => 0 ]; model('product_sku')->insert($insert_data); } else { if (!in_array($a, $no_find)) array_push($no_find, $a); } } } } tiaoshi($like_find); tiaoshi(count($like_find)); tiaoshi($no_find); tiaoshi(count($no_find)); exit; } } private function getTree($array, $pid, $level = 1) { static $list = []; foreach ($array as $key => $value) { if ($value['pid'] == $pid) { $value['level'] = $level; $list[] = $value; //把这个节点从数组中移除,减少后续递归消耗 unset($array[$key]); self::getTree($array, $value['id'], $level+1); } } return $list; } public function save_product_to_shop() { // die; if ($this->user_id !== 1) exit; set_time_limit(3600); // -------查官网的产品相关信息begin--------- $goods_cate = model('product_category')->where(['country_code' => 'ZH', 'stat' => 0])->order(['id' => 'asc'])->select(); $goods_cate = $this->getTree($goods_cate, 0, 1); $goods = model('product')->where(['stat' => 0, 'country_code' => 'ZH'])->order(['id' => 'asc'])->select(); foreach ($goods as $key => $value) { $product_two_img = model('product_two_img')->where(['stat' => 0, 'product_id' => $value['id']])->find(); $goods[$key]['product_two_img'] = 'http://www.orico.com.cn' . $product_two_img['image_url']; $goods_img = model('product_image')->where(['country_code' => 'ZH', 'stat' => 0, 'product_id' => $value['id']])->select(); $goods[$key]['goods_img'] = $goods_img; $goods_sku = model('product_sku')->where(['stat' => 0, 'product_id' => $value['id']])->select(); $goods[$key]['goods_sku'] = $goods_sku; } // -------查官网的产品相关信息e n d--------- // tiaoshi($goods);die; # ==============分割线=============== # header("Content-type:text/html; charset=utf-8"); $con = mysqli_connect('139.9.74.226','root','root','orico_shop'); if(!$con) return $this->json(-1, '数据库连接失败'); // --------同步商品分类begin--------- // 记录旧的cate_id和新的cate_id的映射关系,添加分类 $cate_map = []; foreach ($goods_cate as $key => $value) { $old_cat_id = $value['id']; $pc_icon = $value['picture'] != '' ? 'http://www.orico.com.cn' . $value['picture'] : ''; $sql = "INSERT INTO bao_goods_cate (`cate_name`, `parent_id`, `cate_type`, `pc_icon`, `type`) VALUES ('$value[name]', $value[pid], $value[level], '$pc_icon', 2)"; $query = mysqli_query($con, $sql); if (!$query) return $this->json(-2, $value['id'] . '---' . $value['name'] . '添加失败', ['error' => mysqli_error($con)]); $cate_map[$old_cat_id] = mysqli_insert_id($con); } // 改parent_id $sql = "SELECT * FROM bao_goods_cate"; $query = mysqli_query($con, $sql); $new_goods_cate = []; while ($row = mysqli_fetch_array($query)) $new_goods_cate[] = $row; foreach ($new_goods_cate as $key => $value) { if ($value['parent_id'] == 0) continue; $new_pid = $cate_map[$value['parent_id']]; $sql = "UPDATE bao_goods_cate SET parent_id=$new_pid WHERE cate_id=$value[cate_id]"; mysqli_query($con, $sql); } // --------同步商品分类e n d--------- echo 'ok';die; // --------同步产品begin--------- foreach ($goods as $key => $value) { if (!isset($cate_map[$value['cid']])) continue; // -----goods表begin-----z $cate_id = $cate_map[$value['cid']]; $details = str_replace('/uploads/', 'http://www.orico.com.cn/uploads/', $value['ld_md_content']); $sql = "INSERT INTO bao_goods (`title`, `intro`, `guige`, `cate_id`, `photo`, `details`, `is_new`, `is_hot`, `is_best`, `is_on_sale`, `goods_brief`, `shop_id`, `price`, `audit`, `is_mall`) VALUES ('$value[name]', '$value[shortname]', '$value[brand_id]', $cate_id, '$value[product_two_img]', '$details', $value[isnew], $value[ishot], $value[recommend], $value[is_onsale], '$value[product_view]', 0, 1, 1, 1)"; $query = mysqli_query($con, $sql); if (!$query) return $this->json(-2, $value['id'] . '---' . $value['name'] . '添加失败', ['error' => mysqli_error($con)]); $goods_id = mysqli_insert_id($con); // -----goods表e n d----- // -----wholesale表begin----- $sql = "INSERT INTO bao_wholesale (`goods_id`, `cate_id`, `photo`, `title`, `sub_title`, `intro`, `keywords`, `shop_id`) VALUES ($goods_id, $cate_id, '$value[product_two_img]', '$value[name]', '$value[shortname]', '$value[description]', '$value[seo_keyword]', 0)"; mysqli_query($con, $sql); // -----wholesale表e n d----- // -----goods_photos表begin----- foreach ($value['goods_img'] as $k => $v) { $photo = 'http://www.orico.com.cn' . $v['image_url']; $sql = "INSERT INTO bao_goods_photos (`goods_id`, `photo`) VALUES ($goods_id, '$photo')"; mysqli_query($con, $sql); } // -----goods_photos表e n d----- // -----规格&&product表begin----- foreach ($value['goods_sku'] as $k => $v) { $cat_name = ''; $map = []; if ($v['version'] != '') $cat_name .= '功能/版本_'; $map['功能/版本'] = $v['version']; if ($v['interface'] != '') $cat_name .= '接口_'; $map['接口'] = $v['interface']; if ($v['color'] != '') $cat_name .= '颜色_'; $map['颜色'] = $v['color']; if ($v['length'] != '') $cat_name .= '长度_'; $map['长度'] = $v['length']; if ($v['regulatory'] != '') $cat_name .= '安规_'; $map['安规'] = $v['regulatory']; if ($v['package'] != '') $cat_name .= '包装_'; $map['包装'] = $v['package']; $cat_name = trim($cat_name, '_'); $sql = "SELECT * FROM bao_goods_type WHERE cat_name='$cat_name' LIMIT 1"; $query = mysqli_query($con, $sql); $num = mysqli_num_rows($query); if ($num == 0) { $sql = "INSERT INTO bao_goods_type (`cat_name`, `enabled`) VALUES ('$cat_name', 1)"; mysqli_query($con, $sql); $cat_id = mysqli_insert_id($con); $sql = "UPDATE bao_goods SET cat_id='$cat_id' WHERE goods_id='$goods_id'"; mysqli_query($con, $sql); $arr_cate_name = explode('_', $cat_name); $attribute = []; foreach ($arr_cate_name as $index => $item) { $sql = "INSERT INTO bao_attribute (`cat_id`, `attr_name`, `attr_type`) VALUES ($cat_id, '$item', 2)"; mysqli_query($con, $sql); $attr_id = mysqli_insert_id($con); $attribute[] = [ 'attr_id' => $attr_id, 'cat_id' => $cat_id, 'attr_name' => $item ]; } $goods_attr = ''; foreach ($attribute as $index => $item) { $attr_value = $map[$item['attr_name']]; $sql = "INSERT INTO bao_goods_attr (`goods_id`, `attr_id`, `attr_value`) VALUES ($goods_id, $item[attr_id], '$attr_value')"; mysqli_query($con, $sql); $goods_attr .= mysqli_insert_id($con) . '|'; } $goods_attr = trim($goods_attr, '|'); $sql = "INSERT INTO bao_products (`goods_id`, `goods_attr`, `product_sn`, `product_number`) VALUES ($goods_id, '$goods_attr', '$v[sku]', 1)"; mysqli_query($con, $sql); } else { $row = mysqli_fetch_array($query); $cat_id = $row['cat_id']; $sql = "UPDATE bao_goods SET cat_id='$cat_id' WHERE goods_id='$goods_id'"; mysqli_query($con, $sql); $sql = "SELECT * FROM bao_attribute WHERE cat_id='$cat_id'"; $query = mysqli_query($con, $sql); $attribute = []; while ($row = mysqli_fetch_array($query)) $attribute[] = $row; $goods_attr = ''; foreach ($attribute as $index => $item) { $attr_value = $map[$item['attr_name']]; $sql = "SELECT * FROM bao_goods_attr WHERE goods_id=$goods_id AND attr_id=$item[attr_id] AND attr_value='$attr_value' LIMIT 1"; $query = mysqli_query($con, $sql); $num = mysqli_num_rows($query); if ($num == 0) { $sql = "INSERT INTO bao_goods_attr (`goods_id`, `attr_id`, `attr_value`) VALUES ($goods_id, $item[attr_id], '$attr_value')"; mysqli_query($con, $sql); $goods_attr_id = mysqli_insert_id($con); } else { $row = mysqli_fetch_array($query); $goods_attr_id = $row['goods_attr_id']; } $goods_attr .= $goods_attr_id . '|'; } $goods_attr = trim($goods_attr, '|'); $sql = "INSERT INTO bao_products (`goods_id`, `goods_attr`, `product_sn`, `product_number`) VALUES ($goods_id, '$goods_attr', '$v[sku]', 1)"; mysqli_query($con, $sql); } } // -----规格&&product表e n d----- } // --------同步产品e n d--------- mysqli_close($con); return $this->json(200, 'ok'); } public function update_product_to_shop() { $data = $this->request->post(); $ids = $data['ids']; set_time_limit(3600); // -------查官网的产品相关信息begin--------- if (empty($ids)) { return $this->json(-1, 'id不能为空'); } $where = [ 'id' => ['in', $ids], 'stat' => 0, 'country_code' => 'ZH' ]; $goods = model('product')->where($where)->order(['id' => 'asc'])->select(); foreach ($goods as $key => $value) { $product_two_img = model('product_two_img')->where(['stat' => 0, 'product_id' => $value['id']])->find(); $goods[$key]['product_two_img'] = 'https://www.orico.com.cn' . $product_two_img['image_url']; $goods_img = model('product_image')->where(['country_code' => 'ZH', 'stat' => 0, 'product_id' => $value['id']])->select(); $goods[$key]['goods_img'] = $goods_img; $goods_sku = model('product_sku')->where(['stat' => 0, 'product_id' => $value['id']])->select(); $goods[$key]['goods_sku'] = $goods_sku; } // -------查官网的产品相关信息e n d--------- # ==============分割线=============== # try { header("Content-type:text/html; charset=utf-8"); // $con = mysqli_connect('139.9.74.226','root','root','orico_shop') or die('商城数据库连接失败'); // svn $con = mysqli_connect('119.23.62.80','f2b211_com','PBCsFNZknbG88pcj','f2b211_com') or die('商城数据库连接失败'); // $con = mysqli_connect('119.23.62.80','orico_shop','xTJ3kBAw6MFRkXt5','orico_shop') or die('商城数据库连接失败'); // 线上 foreach ($goods as $key => $value) { $details = str_replace('/uploads/', 'https://www.orico.com.cn/uploads/', $value['ld_md_content']); $sql = "SELECT goods_id, cat_id FROM bao_goods WHERE guige='$value[brand_id]'"; $query = mysqli_query($con, $sql); $num = mysqli_num_rows($query); # 判断新增还是更新商品信息 if ($num) { # 更新 // -----goods表begin----- $goods_info = mysqli_fetch_array($query); $goods_id = $goods_info['goods_id']; $sql = "UPDATE bao_goods SET title='$value[name]', intro='$value[shortname]', photo='$value[product_two_img]', details='$details', is_new='$value[isnew]', is_hot='$value[ishot]', is_best='$value[recommend]', is_on_sale='$value[is_onsale]', goods_brief='$value[product_view]' WHERE goods_id=$goods_id"; mysqli_query($con, $sql); // -----goods表e n d----- // // -----wholesale表begin----- // $sql = "UPDATE bao_wholesale SET photo='$value[product_two_img]', title='$value[name]', sub_title='$value[shortname]', intro='$value[description]', keywords='$value[seo_keyword]' WHERE goods_id=$goods_id"; // mysqli_query($con, $sql); // // -----wholesale表e n d----- // -----goods_photos表begin----- $sql = "DELETE FROM bao_goods_photos WHERE goods_id=$goods_id"; mysqli_query($con, $sql); foreach ($value['goods_img'] as $k => $v) { $photo = 'http://www.orico.com.cn' . $v['image_url']; $sql = "INSERT INTO bao_goods_photos (`goods_id`, `photo`) VALUES ($goods_id, '$photo')"; mysqli_query($con, $sql); } // -----goods_photos表e n d----- if (!empty($value['goods_sku'])) { $sql = "DELETE FROM bao_goods_attr WHERE goods_id=$goods_id"; mysqli_query($con, $sql); $sql = "DELETE FROM bao_products WHERE goods_id=$goods_id"; mysqli_query($con, $sql); } } else { # 新增 $sql = "INSERT INTO bao_goods (`title`, `intro`, `guige`, `photo`, `details`, `is_new`, `is_hot`, `is_best`, `is_on_sale`, `goods_brief`, `shop_id`, `price`, `audit`, `is_mall`) VALUES ('$value[name]', '$value[shortname]', '$value[brand_id]', '$value[product_two_img]', '$details', $value[isnew], $value[ishot], $value[recommend], $value[is_onsale], '$value[product_view]', 0, 1, 1, 1)"; $query = mysqli_query($con, $sql); if (!$query) return $this->json(-2, $value['id'] . '---' . $value['name'] . '添加失败', ['error' => mysqli_error($con)]); $goods_id = mysqli_insert_id($con); // // -----wholesale表begin----- // $sql = "INSERT INTO bao_wholesale (`goods_id`, `photo`, `title`, `sub_title`, `intro`, `keywords`, `shop_id`) VALUES ($goods_id, '$value[product_two_img]', '$value[name]', '$value[shortname]', '$value[description]', '$value[seo_keyword]', 0)"; // mysqli_query($con, $sql); // // -----wholesale表e n d----- // -----goods_photos表begin----- foreach ($value['goods_img'] as $k => $v) { $photo = 'http://www.orico.com.cn' . $v['image_url']; $sql = "INSERT INTO bao_goods_photos (`goods_id`, `photo`) VALUES ($goods_id, '$photo')"; mysqli_query($con, $sql); } // -----goods_photos表e n d----- } $map = []; foreach ($value['goods_sku'] as $k => $v) { $cat_name = ''; if ($v['version'] != '') { $cat_name .= '功能/版本_'; if (!isset($map['功能/版本']) || !in_array($v['version'], $map['功能/版本'])) { $map['功能/版本'][] = $v['version']; } } if ($v['interface'] != '') { $cat_name .= '接口_'; if (!isset($map['接口']) || !in_array($v['interface'], $map['接口'])) { $map['接口'][] = $v['interface']; } } if ($v['color'] != '') { $cat_name .= '颜色_'; if (!isset($map['颜色']) || !in_array($v['color'], $map['颜色'])) { $map['颜色'][] = $v['color']; } } if ($v['length'] != '') { $cat_name .= '尺寸/数量_'; if (!isset($map['尺寸/数量']) || !in_array($v['length'], $map['尺寸/数量'])) { $map['尺寸/数量'][] = $v['length']; } } if ($v['regulatory'] != '') { $cat_name .= '安规_'; if (!isset($map['安规']) || !in_array($v['regulatory'], $map['安规'])) { $map['安规'][] = $v['regulatory']; } } if ($v['package'] != '') { $cat_name .= '包装_'; if (!isset($map['包装']) || !in_array($v['package'], $map['包装'])) { $map['包装'][] = $v['package']; } } $cat_name = trim($cat_name, '_'); } if (empty($value['goods_sku'])) { continue; } $sql = "SELECT * FROM bao_goods_type WHERE cat_name='$cat_name' LIMIT 1"; $query = mysqli_query($con, $sql); $num = mysqli_num_rows($query); //判断是否存在规格模板 if ($num == 0) { $sql = "INSERT INTO bao_goods_type (`cat_name`, `enabled`) VALUES ('$cat_name', 1)"; mysqli_query($con, $sql); $cat_id = mysqli_insert_id($con); $sql = "UPDATE bao_goods SET cat_id='$cat_id' WHERE goods_id='$goods_id'"; mysqli_query($con, $sql); $arr_cate_name = explode('_', $cat_name); $attribute = []; foreach ($arr_cate_name as $k => $v) { $sql = "INSERT INTO bao_attribute (`cat_id`, `attr_name`, `attr_type`) VALUES ($cat_id, '$v', 2)"; mysqli_query($con, $sql); $attr_id = mysqli_insert_id($con); $attribute[] = [ 'attr_id' => $attr_id, 'cat_id' => $cat_id, 'attr_name' => $v ]; } } else { //新增模板 $row = mysqli_fetch_array($query); $cat_id = $row['cat_id']; $sql = "UPDATE bao_goods SET cat_id='$cat_id' WHERE goods_id='$goods_id'"; mysqli_query($con, $sql); $sql = "SELECT * FROM bao_attribute WHERE cat_id='$cat_id'"; $query = mysqli_query($con, $sql); $attribute = []; while ($row = mysqli_fetch_array($query)) $attribute[] = $row; } $goods_attr = ''; foreach ($attribute as $k => $v) { $attr_value_list = $map[$v['attr_name']]; foreach ($attr_value_list as $index => $item) { $sql = "INSERT INTO bao_goods_attr (`goods_id`, `attr_id`, `attr_value`) VALUES ($goods_id, $v[attr_id], '$item')"; mysqli_query($con, $sql); } } //sku foreach ($value['goods_sku'] as $k => $v) { $goods_attr_id_comb = ''; if ($v['version'] != '') { $attr_name = '功能/版本'; $attr_value = $v['version']; $sql = "SELECT * FROM bao_attribute WHERE cat_id='$cat_id' AND attr_name='$attr_name' LIMIT 1"; $query = mysqli_query($con, $sql); $row = mysqli_fetch_array($query); if (empty($row)) { return $this->json(-1, $attr_name . '获取失败'); } $attr_id = $row['attr_id']; $sql = "SELECT * FROM bao_goods_attr WHERE goods_id='$goods_id' AND attr_id='$attr_id' AND attr_value='$attr_value' LIMIT 1"; $query = mysqli_query($con, $sql); $row = mysqli_fetch_array($query); if (empty($row)) { return $this->json(-1, $attr_name . '属性值获取失败' . $sql); } $goods_attr_id = $row['goods_attr_id']; $goods_attr_id_comb .= $goods_attr_id . '|'; } if ($v['interface'] != '') { $attr_name = '接口'; $attr_value = $v['interface']; $sql = "SELECT * FROM bao_attribute WHERE cat_id='$cat_id' AND attr_name='$attr_name' LIMIT 1"; $query = mysqli_query($con, $sql); $row = mysqli_fetch_array($query); if (empty($row)) { return $this->json(-1, $attr_name . '获取失败'); } $attr_id = $row['attr_id']; $sql = "SELECT * FROM bao_goods_attr WHERE goods_id='$goods_id' AND attr_id='$attr_id' AND attr_value='$attr_value' LIMIT 1"; $query = mysqli_query($con, $sql); $row = mysqli_fetch_array($query); if (empty($row)) { return $this->json(-1, $attr_name . '属性值获取失败'); } $goods_attr_id = $row['goods_attr_id']; $goods_attr_id_comb .= $goods_attr_id . '|'; } if ($v['color'] != '') { $attr_name = '颜色'; $attr_value = $v['color']; $sql = "SELECT * FROM bao_attribute WHERE cat_id='$cat_id' AND attr_name='$attr_name' LIMIT 1"; $query = mysqli_query($con, $sql); $row = mysqli_fetch_array($query); if (empty($row)) { return $this->json(-1, $attr_name . '获取失败'); } $attr_id = $row['attr_id']; $sql = "SELECT * FROM bao_goods_attr WHERE goods_id='$goods_id' AND attr_id='$attr_id' AND attr_value='$attr_value' LIMIT 1"; $query = mysqli_query($con, $sql); $row = mysqli_fetch_array($query); if (empty($row)) { return $this->json(-1, $attr_name . '属性值获取失败'); } $goods_attr_id = $row['goods_attr_id']; $goods_attr_id_comb .= $goods_attr_id . '|'; } if ($v['length'] != '') { $attr_name = '尺寸/数量'; $attr_value = $v['length']; $sql = "SELECT * FROM bao_attribute WHERE cat_id='$cat_id' AND attr_name='$attr_name' LIMIT 1"; $query = mysqli_query($con, $sql); $row = mysqli_fetch_array($query); if (empty($row)) { return $this->json(-1, $attr_name . '获取失败'); } $attr_id = $row['attr_id']; $sql = "SELECT * FROM bao_goods_attr WHERE goods_id='$goods_id' AND attr_id='$attr_id' AND attr_value='$attr_value' LIMIT 1"; $query = mysqli_query($con, $sql); $row = mysqli_fetch_array($query); if (empty($row)) { return $this->json(-1, $attr_name . '属性值获取失败'); } $goods_attr_id = $row['goods_attr_id']; $goods_attr_id_comb .= $goods_attr_id . '|'; } if ($v['regulatory'] != '') { $attr_name = '安规'; $attr_value = $v['regulatory']; $sql = "SELECT * FROM bao_attribute WHERE cat_id='$cat_id' AND attr_name='$attr_name' LIMIT 1"; $query = mysqli_query($con, $sql); $row = mysqli_fetch_array($query); if (empty($row)) { return $this->json(-1, $attr_name . '获取失败'); } $attr_id = $row['attr_id']; $sql = "SELECT * FROM bao_goods_attr WHERE goods_id='$goods_id' AND attr_id='$attr_id' AND attr_value='$attr_value' LIMIT 1"; $query = mysqli_query($con, $sql); $row = mysqli_fetch_array($query); if (empty($row)) { return $this->json(-1, $attr_name . '属性值获取失败'); } $goods_attr_id = $row['goods_attr_id']; $goods_attr_id_comb .= $goods_attr_id . '|'; } if ($v['package'] != '') { $attr_name = '包装'; $attr_value = $v['package']; $sql = "SELECT * FROM bao_attribute WHERE cat_id='$cat_id' AND attr_name='$attr_name' LIMIT 1"; $query = mysqli_query($con, $sql); $row = mysqli_fetch_array($query); if (empty($row)) { return $this->json(-1, $attr_name . '获取失败'); } $attr_id = $row['attr_id']; $sql = "SELECT * FROM bao_goods_attr WHERE goods_id='$goods_id' AND attr_id='$attr_id' AND attr_value='$attr_value' LIMIT 1"; $query = mysqli_query($con, $sql); $row = mysqli_fetch_array($query); if (empty($row)) { return $this->json(-1, $attr_name . '属性值获取失败'); } $goods_attr_id = $row['goods_attr_id']; $goods_attr_id_comb .= $goods_attr_id . '|'; } $goods_attr_id_comb = trim($goods_attr_id_comb, '|'); $sql = "INSERT INTO bao_products (`goods_id`, `goods_attr`, `product_sn`, `product_number`) VALUES ($goods_id, '$goods_attr_id_comb', '$v[sku]', 1)"; mysqli_query($con, $sql); } } } catch (\Exception $e) { return $this->json(-1, $e->getMessage()); } mysqli_close($con); return $this->json(200, 'ok'); } }