<?php
/**
 * Created by PhpStorm.
 * User: ywl
 * Date: 2017/4/14
 * Time: 11:38
 */

namespace App\Web\Services;

use App\Common\Facades\UploadFileFacade;
use App\Common\Services\PinYinService;
use App\Exceptions\ApiException;
use App\Services\CommonUserBaseService;
use App\Web\Facades\WebFacade;
use App\Web\Models\ProductModel;
use App\Web\Models\ProductTagModel;
use App\Web\Models\ProductTagRelationModel;
use App\Web\Models\ProductTypeModel;
use App\Web\Models\ProductTypeRelationModel;
use Illuminate\Support\Facades\DB;

class ProductService extends CommonUserBaseService
{
    protected $cache = true;

    protected $cacheBucket = 'Product:';

    protected $productTypeModel;
    protected $productTypeRelationModel;
    protected $productTagModel;
    protected $productTagRelationModel;

    /**
     * ProductService construct
     * @param ProductModel $model
     * @param ProductTypeModel $productTypeModel
     * @param ProductTagRelationModel $productTagRelationModel
     * @param ProductTagModel $productTagModel
     * @param ProductTypeRelationModel $productTypeRelationModel
     * */
    public function __construct(ProductModel $model,
                                ProductTypeModel $productTypeModel,
                                ProductTagRelationModel $productTagRelationModel,
                                ProductTagModel $productTagModel,
                                ProductTypeRelationModel $productTypeRelationModel
    ){
        $this->model=$model;
        $this->productTypeModel=$productTypeModel;
        $this->productTypeRelationModel=$productTypeRelationModel;
        $this->productTagModel=$productTagModel;
        $this->productTagRelationModel=$productTagRelationModel;
    }

    /**
     * 获取产品类型列表
     * */
    public function getProductTypeList($params){
        $retData= $this->productTypeModel->getProductTypeList($params);
        if(!empty($retData['data'])){
            $typeIds=array_column($retData['data'],'id');
            $productCounts=$this->productTypeRelationModel->getProductTypeCount($typeIds);
            foreach ($retData['data'] as &$productItem){
                $productItem['product_count'] = $productCounts[$productItem['id']] ?? 0;
                $productItem['expand_content'] = empty($productItem['expand_content'])?[]:json_decode($productItem['expand_content'],true);
            }
        }
        return $retData;
    }

    public function getTreeProductList($params){
        $list= $this->productTypeModel->getTreeProductList($params);
        if(!empty($list)){
            $typeIds=array_column($list,'id');
            $productCounts=$this->productTypeRelationModel->getProductTypeCount($typeIds);
            $pCountData=[];
            $descData=array_reverse($list);
            foreach ($descData as $descProductItem){
               $tempCount=  $productCounts[$descProductItem['id']] ?? 0;
                if(empty($pCountData[$descProductItem['p_id']])){
                    $pCountData[$descProductItem['p_id']]=$tempCount;
                }else{
                    $pCountData[$descProductItem['p_id']]=$pCountData[$descProductItem['p_id']]+$tempCount;
                }
                if(!empty($tempCount)&&!empty($pCountData[$descProductItem['id']])){
                    $pCountData[$descProductItem['id']]=$pCountData[$descProductItem['id']]+$tempCount;
                }
            }
            foreach ($list as &$productItem){
                $productItem['product_count'] = $productCounts[$productItem['id']] ?? 0;
                $productItem['expand_content'] = empty($productItem['expand_content'])?[]:json_decode($productItem['expand_content'],true);
                $productItem['expand_array'] = $this->transformArrayToKeyValue($productItem['expand_content']);
                if(!empty($pCountData[$productItem['id']])){
                    $productItem['product_count']=$pCountData[$productItem['id']];
                }
            }
        }

        $list=listToTree($list,0,'id','p_id','children');
        return $list;
    }

    public function transformArrayToKeyValue($array) {
        $result = [];
        foreach ($array as $item) {
            if (isset($item['key']) && isset($item['value'])) {
                $result[$item['key']] = $item['value'];
            }
        }
        return $result;
    }

    public function sortTypes($types){
        $retData= $this->productTypeModel->sortTypes($types);
        return $retData;
    }
    /**
     * 根据Admin类型id 获取产品列表
     * */
    public function getAdminProductByTypeIds($params) {
        $retData= $this->model->getAdminProductData($params);
        if(!empty($retData['data'])) {
            $newestProductIds=array_column($retData['data'],'id');
            $newestTypeAndTagData=$this->getTypeAndTagDataByProductId($newestProductIds);
            foreach ($retData['data'] as &$productItem){
                if(!empty($newestTypeAndTagData[$productItem['id']]['type_items'])){
                    $productItem['type_items']=$newestTypeAndTagData[$productItem['id']]['type_items'];
                }else{
                    $productItem['type_items']=[];
                }
                if(!empty($newestTypeAndTagData[$productItem['id']]['tag_items'])){
                    $productItem['tag_items']=$newestTypeAndTagData[$productItem['id']]['tag_items'];
                }else{
                    $productItem['tag_items']=[];
                }
            }
        }
        return $retData;
    }
    /**
     * 根据类型id 获取产品列表
     * */
    public function getProductByTypeIds($params) {
        $retData= $this->model->getProductByTypeIds($params);
        if(!empty($retData['data'])) {
            $newestProductIds=array_column($retData['data'],'id');
            $newestTypeAndTagData=$this->getTypeAndTagDataByProductId($newestProductIds);
            foreach ($retData['data'] as &$productItem){
                if(!empty($newestTypeAndTagData[$productItem['id']]['type_items'])){
                    $productItem['type_items']=$newestTypeAndTagData[$productItem['id']]['type_items'];
                }else{
                    $productItem['type_items']=[];
                }
                if(!empty($newestTypeAndTagData[$productItem['id']]['tag_items'])){
                    $productItem['tag_items']=$newestTypeAndTagData[$productItem['id']]['tag_items'];
                }else{
                    $productItem['tag_items']=[];
                }
            }
        }
        return $retData;
    }

    /**
     * 根据标签id 获取产品列表
     * */
    public function getProductByTagIds($params){
        $retData= $this->productTagRelationModel->getProductByTagIds($params);
        return $retData;
    }
    public function getProductIdByTagIds($params){
        $retData= $this->productTagRelationModel->getProductIdByTagIds($params);
        return $retData;
    }
    /**
     * 产品类型保存
     * */
    public function saveProductType($params){
        $saveData=[];
        $nowTime=nowTime();
        $saveData['update_time']=$nowTime;
        $userId=$this->getAuthUserId();

        if (!empty($params['seo_data'])) {
            $urlaUnique = WebFacade::checkUrlaUnique($params['seo_data']['urla'], $params['seo_id']);
            if (!$urlaUnique) {
                throw new ApiException(10019, ['name' => $params['seo_data']['urla']]);
            }
        }
        if(!empty($params['id'])){
            $saveData['id']=$params['id'];
            if(isset($params['type_name'])){
                $nameUnique =$this->productTypeModel->checkTypeNameUnique($params['type_name'],$params['id']);
                if (!$nameUnique) {
                    throw new ApiException(10018, ['name' => $params['type_name']]);
                }
                $saveData['type_name']=$params['type_name'];
            }
            if(isset($params['description'])){
                $saveData['description']=empty($params['description'])?'':$params['description'];
            }
            if(isset($params['p_id'])){
                $saveData['p_id']=empty($params['p_id'])?0:$params['p_id'];
            }
            if(isset($params['status'])){
                $saveData['status']=$params['status'];
            }
            if(isset($params['sort'])){
                $saveData['sort']=$params['sort'];
            }
            if(isset($params['expand_content'])){
                $saveData['expand_content']=!empty($params['expand_content'])?json_encode($params['expand_content']):'';
            }
        }else{
            $nameUnique =$this->productTypeModel->checkTypeNameUnique($params['type_name']);
            if (!$nameUnique) {
                throw new ApiException(10018, ['name' => $params['type_name']]);
            }
            $saveData['user_id']=$userId;
            $saveData['type_name']=$params['type_name'];
            $saveData['description']=empty($params['description'])?'':$params['description'];
            $saveData['expand_content']=!empty($params['expand_content'])?json_encode($params['expand_content']):'';
            $saveData['sort']=empty($params['sort'])?0:$params['sort'];
            $saveData['p_id']=empty($params['p_id'])?0:$params['p_id'];
            $saveData['create_time']=$nowTime;
        }
        $id = $this->productTypeModel->saveTypeData($saveData);
        $parentId = empty($params['parent_id']) ?0:$params['parent_id'];
        if ($parentId) {
            $relations = $this->productTypeRelationModel->getByTypeId($parentId);
            $productIds = array_column($relations, 'product_id');
            $this->productTypeRelationModel->deleteByTypeId($parentId);
            $this->productTypeRelationModel->addByTypeId($id,$productIds,$userId);
        }
        if (!empty($id) && isset($params['seo_data'])) {
            $seoParams = [
                'relation_table' => WebService::RELATION_TABLE_PRODUCT_TYPE,
                'relation_id' => $id,
                'urla' => $params['seo_data']['urla'],
                'seo_title' => $params['seo_data']['seo_title'],
                'seo_keyword' => $params['seo_data']['seo_keyword'],
                'seo_describe' => $params['seo_data']['seo_describe']
            ];

            if (empty($params['seo_id'])) {
                $seoParams['user_id'] = $userId;
                $urlaId = WebFacade::saveSeoData($seoParams);
                $this->productTypeModel->newInstance()->where('id','=',$id)->update(['seo_id' => $urlaId]);
            } else {
                $seoParams['id'] = $params['seo_id'];
                $urlaId = WebFacade::saveSeoData($seoParams);
            }
            $allPath=$this->getProductAllPath($id);
            if($allPath){
                $this->productTypeModel->where('id', $id)->update(['path'=>$allPath['path'],'path_name'=>$allPath['path_name']]);
                $this->updateSubAllPath($id);
            }

        }
        if(!empty($saveData['status'])&&$saveData['status']==2){
            //移除对应seo
            $delSeoParams=[];
            $delSeoParams['relation_table']=WebService::RELATION_TABLE_PRODUCT_TYPE;
            $delSeoParams['relation_id']=$id;
            $ret = WebFacade::delSeoByRelation($delSeoParams);
        }
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $id;
    }

    /**
     * 获取功能/菜单的全路径
     * */
    public function getProductAllPath($id){
        $ret=['path'=>'','path_name'=>''];
        $info= $this->productTypeModel->alias('a')
            ->leftJoin($this->productTypeModel->getTable().' as b', 'a.p_id', '=', 'b.id')
            ->where('a.id',$id)
            ->where('a.status',0)
            ->selectRaw("b.id as p_id,b.type_name as 'p_name',a.id,a.type_name")
            ->first();
        if($info){
            $info=$info->toArray();
            if(!empty($info['p_id'])){
                $pRet=$this->getProductAllPath($info['p_id']);
                $ret['path']=$pRet['path'].','.$info['id'];
                $ret['path_name']=$pRet['path_name'].','.$info['type_name'];
            }else{
                $ret['path']= $info['id'];
                $ret['path_name']= $info['type_name'];
            }

        }
        return $ret;

    }

    /**
     * 更新子集的全路径
     * */
    public function updateSubAllPath($id){
        if($id>0){
            $list= $this->productTypeModel->alias('a')
                ->where('a.p_id',$id)
                ->where('a.status',0)
                ->get();
            if(!empty($list)){
                $list=$list->toArray();
                foreach ($list as $value){
                    $allPath=$this->getProductAllPath($value['id']);
                    if($allPath){
                        $this->productTypeModel->where('id', $value['id'])->update(['path'=>$allPath['path'],'path_name'=>$allPath['path_name']]);
                        $this->updateSubAllPath($value['id']);
                    }
                }
            }
        }
    }

    /**
     * 保存产品类型关系
     * */
    public function typeRelationSave($params){
        $userId=$this->getAuthUserId();
        $ret = $this->productTypeRelationModel->typeRelationSave($params,$userId);

        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 根据产品类型 保存产品关系
     * */
    public function addRelationByTypeId($typeId,$productIds){
        $userId=$this->getAuthUserId();
        $ret = $this->productTypeRelationModel->addByTypeId($typeId,$productIds,$userId);

        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 根据类型id及产品id 删除关联关系
     * */
    public function delTypeRelation($typeId, $productId)
    {
        $ret = $this->productTypeRelationModel->delTypeRelation($typeId, $productId);

        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 获取产品标签列表
     * */
    public function getProductTagList($params){
        $retData= $this->productTagModel->getProductTagList($params);
        if(!empty($retData['data'])){
            $tagIds=array_column($retData['data'],'id');
            $productCounts=$this->productTagRelationModel->getProductTagCount($tagIds);
            foreach ($retData['data'] as &$productItem){
                $productItem['product_count'] = $productCounts[$productItem['id']] ?? 0;
            }
        }
        return $retData;
    }

    /**
     * 产品标签保存
     * */
    public function saveProductTag($params){
        $saveData=[];
        $nowTime=nowTime();
        $saveData['update_time']=$nowTime;
        $userId=$this->getAuthUserId();

        if (!empty($params['seo_data'])) {
            $urlaUnique = WebFacade::checkUrlaUnique($params['seo_data']['urla'], $params['seo_id']);
            if (!$urlaUnique) {
                throw new ApiException(10019, ['name' => $params['seo_data']['urla']]);
            }
        }

        if(!empty($params['id'])){
            $saveData['id']=$params['id'];
            if(isset($params['tag_name'])){
                $nameUnique =$this->productTagModel->checkTagNameUnique($params['tag_name'],$params['id']);
                if (!$nameUnique) {
                    throw new ApiException(10018, ['name' => $params['tag_name']]);
                }
                $saveData['tag_name']=$params['tag_name'];
            }
            if(isset($params['status'])){
                $saveData['status']=$params['status'];
            }
            if(isset($params['sort'])){
                $saveData['sort']=$params['sort'];
            }
            if(isset($params['is_hot'])){
                $saveData['is_hot']=$params['is_hot'];
            }
            if(isset($params['type'])){
                $saveData['type']=empty($params['type'])?0:$params['type'];
            }
        }else{
            $nameUnique =$this->productTagModel->checkTagNameUnique($params['tag_name']);
            if (!$nameUnique) {
                throw new ApiException(10018, ['name' => $params['tag_name']]);
            }
            $saveData['user_id']=$userId;
            $saveData['tag_name']=$params['tag_name'];
            $saveData['type']=empty($params['type'])?0:$params['type'];
            $saveData['sort']=empty($params['sort'])?0:$params['sort'];
            $saveData['create_time']=$nowTime;
        }
        $id = $this->productTagModel->saveTagData($saveData);
        if (!empty($id) && isset($params['seo_data'])) {
            $seoParams = [
                'relation_table' => WebService::RELATION_TABLE_PRODUCT_TAG,
                'relation_id' => $id,
                'urla' => $params['seo_data']['urla'],
                'seo_title' => $params['seo_data']['seo_title'],
                'seo_keyword' => $params['seo_data']['seo_keyword'],
                'seo_describe' => $params['seo_data']['seo_describe']
            ];

            if (empty($params['seo_id'])) {
                $seoParams['user_id'] = $userId;
                $urlaId = WebFacade::saveSeoData($seoParams);
                $this->productTagModel->newInstance()->where('id','=',$id)->update(['seo_id' => $urlaId]);
            } else {
                $seoParams['id'] = $params['seo_id'];
                $urlaId = WebFacade::saveSeoData($seoParams);
            }
            if(!empty($saveData['status'])&&$saveData['status']==2){
                //移除对应seo
                $delSeoParams=[];
                $delSeoParams['relation_table']=WebService::RELATION_TABLE_PRODUCT_TAG;
                $delSeoParams['relation_id']=$id;
                $ret = WebFacade::delSeoByRelation($delSeoParams);
            }
        }
        return $id;
    }

    /**
     * 保存产品标签关系
     * */
    public function tagRelationSave($params){
        $userId=$this->getAuthUserId();
        $ret = $this->productTagRelationModel->tagRelationSave($params,$userId);

        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 根据产品标签 保存产品关系
     * */
    public function addRelationByTagId($tagId,$productIds){
        $userId=$this->getAuthUserId();
        $ret = $this->productTagRelationModel->addByTagId($tagId,$productIds,$userId);

        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }

    /**
     * 根据标签id及产品id 删除关联关系
     * */
    public function delTagRelation($tagId, $productId)
    {
        $ret = $this->productTagRelationModel->delTagRelation($tagId, $productId);
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $ret;
    }


    /**
     * 保存产品数据
     * */
    public function saveProduct($params){
        $saveData=$this->buildProductData($params);
//        dd($saveData);
        $userId=$this->getAuthUserId();
        $typeIds = empty($params['type_ids']) ? []: $params['type_ids'];
        $tagIds = empty($params['tag_ids']) ? []: $params['tag_ids'];
        $seoData=empty($params['seo_data'])?[]:$params['seo_data'];
        $urlaId=empty($saveData['seo_id'])?0:$saveData['seo_id'];
        if(!empty($seoData)){
            $urlaUnique = WebFacade::checkUrlaUnique($seoData['urla'],$urlaId);
            if (!$urlaUnique) {
                throw new ApiException(10019, ['name' => $seoData['urla']]);
            }
        }
        $id = $this->model->saveProductData($saveData);
        if(!empty($id)){
            if(isset($params['seo_data'])){
                $seoParams=[];
                $seoParams['relation_table']=WebService::RELATION_TABLE_PRODUCT;
                $seoParams['relation_id']=$id;
                $seoParams['urla']=$seoData['urla'];
                $seoParams['seo_title']=$seoData['seo_title'];
                $seoParams['seo_keyword']=$seoData['seo_keyword'];
                $seoParams['seo_describe']=$seoData['seo_describe'];
                if(empty($urlaId)){
                    $seoParams['user_id']=$userId;
                    $urlaId = WebFacade::saveSeoData($seoParams);
                    $this->model->newInstance()->where('id','=',$id)->update(['seo_id'=>$urlaId]);
                }else{
//                    dd($seoParams);
                    $seoParams['id']=$urlaId;
                    $urlaId= WebFacade::saveSeoData($seoParams);
                }
            }
            if(isset($params['type_ids'])){
                $productTypeParams=[];
                $productTypeParams['product_id']=$id;
                $productTypeParams['type_ids']=$typeIds;
                $this->productTypeRelationModel->typeRelationSave($productTypeParams,$userId);
            }
            if(isset($params['tag_ids'])){
                $productTagParams=[];
                $productTagParams['product_id']=$id;
                $productTagParams['tag_ids']=$tagIds;
                $this->productTagRelationModel->tagRelationSave($productTagParams,$userId);
            }

            // 获取是否需要修改排序数据
            if (isset($saveData['sort'])) {
                $getData = $this->model->selectRaw('id')
                    ->where('sort', '=', $saveData['sort'])
                    ->where('id', '<>', $id)->first();
                if (!empty($getData['id'])) {
                    $this->model->where('sort','>=',$saveData['sort'])
                        ->where('id', '<>', $id)
                        ->update(['sort' => DB::raw('sort + 1')]);
                }
            }
            if(!empty($params['id'])&&!empty($params['virtual_view'])){
                $this->updatePv($params['id'],$params['virtual_view']);
            }

            if(!empty($saveData['status'])&&$saveData['status']==2){
                //移除对应seo
                $delSeoParams=[];
                $delSeoParams['relation_table']=WebService::RELATION_TABLE_PRODUCT;
                $delSeoParams['relation_id']=$id;
                $ret = WebFacade::delSeoByRelation($delSeoParams);
            }
        }
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $id;
    }

    /**
     * 构造虚拟阅读量
     * */
    public function productUvFactory(){
        $page=1;
        $total=0;
        do{
            $where=[];
            $where['page_size']=500;
            $where['page']=$page;
            $where['status']=0;
            $where['lt_total_view']=1000;
            $productData= $this->model->getProductList($where,'a.id,a.virtual_view,a.total_view');
            if(!empty($productData)&&!empty($productData['data'])){
                $total=$productData['total'];
                $data=$productData['data'];
                $updateUvStr='';
                // 规则：小于1千数随记增加 150以内位数
                foreach ($data as $item){
                    $value=0;
                    if($item['total_view']<1000){
                        $value=  mt_rand(0, 150);
                    }
                 /*   if($item['total_view']<1000){
                        $value=  mt_rand(0, 150);
                    }else if($item['total_view']<5000){
                        $value=  mt_rand(0, 99);
                    }else{
                        $value=  mt_rand(0, 9);
                    }*/
                   $this->upProductPv($item['id'],$value);
                }
            }
            $page++;
        }while($total>($page*500));
        WebFacade::clearPageCache('urla:');
    }



    /**
     * 产品推荐设置
     * */
    public function recommendSet($params){
        $id=empty($params['id'])?0:$params['id'];
        $isRecommend=empty($params['is_recommend'])?0:$params['is_recommend'];
        $ret= $this->model->where('id', '=', $id)
            ->update(['is_recommend' => $isRecommend,'update_time'=>nowTime()]);
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $id;
    }

    /**
     * 构建产品保存数据
     * */
    private function buildProductData($params){
        $saveData=[];
        $userId=$this->getAuthUserId();
        $nowTime=nowTime();
        $saveData['update_time']=$nowTime;
        if(!empty($params['id'])){
            $saveData['id']=$params['id'];
            if (isset($params['seo_id'])) {
                $saveData['seo_id'] = $params['seo_id'];
            }
            if(isset($params['pub_date'])){
                $saveData['pub_date']=empty($params['pub_date'])?null:$params['pub_date'];;
            }
            if(isset($params['title'])){
                $nameUnique =$this->model->checkNameUnique($params['title'],$params['id']);
                if (!$nameUnique) {
                    throw new ApiException(10018, ['name' => $params['title']]);
                }
                $saveData['title']=empty($params['title'])?'':$params['title'];
            }
            if(isset($params['content'])){
                $saveData['content']=empty($params['content'])?'':$params['content'];
            }
            if(isset($params['brand'])){
                $saveData['brand']=empty($params['brand'])?'':$params['brand'];
            }
            if(isset($params['model_nb'])){
                $saveData['model_nb']=empty($params['model_nb'])?'':$params['model_nb'];
            }
            if(isset($params['package'])){
                $saveData['package']=empty($params['package'])?'':$params['package'];
            }
            if(isset($params['sku'])){
                $saveData['sku']=empty($params['sku'])?'':$params['sku'];
            }
            if(isset($params['spec'])){
                $saveData['spec']=empty($params['spec'])?'':json_encode($params['spec']) ;
            }
            if(isset($params['description'])){
                $saveData['description']=empty($params['description'])?'':$params['description'];
            }
            if(isset($params['image_url'])){
                $saveData['image_url']=empty($params['image_url'])?'':$params['image_url'];
            }
            if(isset($params['image_alt'])){
                $saveData['image_alt']=empty($params['image_alt'])?'':$params['image_alt'];
            }
            if(isset($params['main_image'])){
                $saveData['main_image']=empty($params['main_image'])?'':$params['main_image'];
            }
            if(isset($params['main_image_alt'])){
                $saveData['main_image_alt']=empty($params['main_image_alt'])?'':$params['main_image_alt'];
            }
            if(isset($params['download_url'])){
                $saveData['download_url']=empty($params['download_url'])?'':json_encode($params['download_url']);
            }
            if(isset($params['sub_image_urls'])){
                $saveData['sub_image_urls']=empty($params['sub_image_urls'])?'':json_encode($params['sub_image_urls']);
            }
            if(isset($params['gallery_imgs'])){
                $saveData['gallery_imgs']=empty($params['gallery_imgs'])?'':json_encode($params['gallery_imgs']);
            }
            if(isset($params['size_imgs'])){
                $saveData['size_imgs']=empty($params['size_imgs'])?'':json_encode($params['size_imgs']);
            }
            if(isset($params['sort'])){
                $saveData['sort']=empty($params['sort'])?0:$params['sort'];
            }
            if(isset($params['is_top'])){
                $saveData['is_top']=empty($params['is_top'])?0:$params['is_top'];
            }
            if(isset($params['status'])){
                $saveData['status']=$params['status'];
            }
            if(isset($params['score'])){
                $saveData['score']=empty($params['score'])?0:$params['score'];
            }
            if(isset($params['expand_content'])) {
                $saveData['expand_content'] = empty($params['expand_content'])?'':json_encode($params['expand_content']);
            }

        }else{
            $nameUnique =$this->model->checkNameUnique($params['title']);
            if (!$nameUnique) {
                throw new ApiException(10018, ['name' => $params['title']]);
            }
            if(empty($params['title'])){
                throw new ApiException(11002);
            }
            if(isset($params['status'])){
                $saveData['status']=$params['status'];
            }
            $saveData['user_id']=$userId;
            $saveData['pub_date']=empty($params['pub_date'])?null:$params['pub_date'];
            $saveData['title']=empty($params['title'])?'':$params['title'];
            $saveData['content']=empty($params['content'])?'':$params['content'];
            $saveData['brand']=empty($params['brand'])?'':$params['brand'];
            $saveData['model_nb']=empty($params['model_nb'])?'':$params['model_nb'];
            $saveData['package']=empty($params['package'])?'':$params['package'];
            $saveData['sku']=empty($params['sku'])?'':$params['sku'];
            $saveData['spec']=empty($params['spec'])?'':json_encode($params['spec']) ;
            $saveData['description']=empty($params['description'])?'':$params['description'];
            $saveData['image_url']=empty($params['image_url'])?'':$params['image_url'];
            $saveData['image_alt']=empty($params['image_alt'])?'':$params['image_alt'];
            $saveData['main_image']=empty($params['main_image'])?'':$params['main_image'];
            $saveData['main_image_alt']=empty($params['main_image_alt'])?'':$params['main_image_alt'];
            $saveData['sub_image_urls']=empty($params['sub_image_urls'])?'':json_encode($params['sub_image_urls']);
            $saveData['gallery_imgs']=empty($params['gallery_imgs'])?'':json_encode($params['gallery_imgs']);
            $saveData['size_imgs']=empty($params['size_imgs'])?'':json_encode($params['size_imgs']);
            $saveData['virtual_view']=empty($params['virtual_view'])?0:$params['virtual_view'];
            $saveData['total_view']=$saveData['virtual_view'];
            $saveData['download_url']=empty($params['download_url'])?'':json_encode($params['download_url']);
            $saveData['expand_content'] = empty($params['expand_content'])?'':json_encode($params['expand_content']);
            $saveData['sort']=empty($params['sort'])?0:$params['sort'];
            $saveData['create_time']=$nowTime;
            $saveData['score']=empty($params['score'])?0:$params['score'];

        }
        return $saveData;
    }

    public function updatePv($id,$newVirtualView){

        $virtualView = $this->getFieldById('virtual_view', $id);

        // 确保 $newVirtualView 是数值类型
        $newVirtualView = (float)$newVirtualView;

        // 确保 $virtualView 是数值类型
        $virtualView = (float)$virtualView;

        // 计算差值
        $value = $newVirtualView - $virtualView;

        // 执行更新操作
        $ret = $this->model->where('id', '=', $id)->increment('total_view', $value);
        $ret = $this->model->where('id', '=', $id)->increment('virtual_view', $value);
        WebFacade::clearPageCache('urla:');
      return $ret;
    }

    /**
     * 更新产品浏览量
     * */
    public function upProductPv($productId, $value=1) {
        if($value>1){
            $ret= $this->model->where('id','=',$productId)->increment('total_view',$value);
            $ret= $this->model->where('id','=',$productId)->increment('virtual_view',$value);
        }else{
            $totalView = $this->getFieldById('total_view', $productId);
            $value = (($value * -1) > $totalView) ? ($totalView * -1) : $value;
            $ret= $this->model->where('id','=',$productId)->increment('total_view',$value);
        }
       return $ret;
    }

    /**
     * 产品列表
     * */
    public function getProductList($params){
        $ret=$this->model->getProductList($params);
        $pageListData=empty($ret['data'])?[]:$ret['data'];
        if(!empty($pageListData)){
            $ids=array_column($pageListData,'seo_id');
            $seoList=[];
            if(!empty($ids)){
                $seoList=WebFacade:: getSeoListByIds($ids);
                if(!empty($seoList)){
                    $seoList=mapByKey($seoList,'id');
                }
            }
            foreach ($pageListData as &$pageItem){
                $pageItem['seo_data']=empty($seoList[$pageItem['seo_id']])?[]:$seoList[$pageItem['seo_id']];
                $pageItem['expand_content']=empty($pageItem['expand_content'])?[]:json_decode($pageItem['expand_content'],true);
            }
        }
        $ret['data']=$pageListData;
        return $ret;
    }

    /**
     * 获取产品详情
     * */
    public function getProductInfo($params){
       $productInfo= $this->model->getProductInfo($params);
       if(!empty($productInfo)){
           if(!empty($productInfo['seo_id'])){
               $productInfo['seo_data']=WebFacade::getSeoInfo(['id'=>$productInfo['seo_id']]);
           }else{
               $productInfo['seo_data'] = [
                   'seo_describe' => '',
                   'seo_keyword' => '',
                   'seo_title' => '',
                   'urla' => ''
               ];
           }
           $productInfo['spec']=empty($productInfo['spec'])?[]:json_decode($productInfo['spec'],true);
           $productInfo['type_ids']=$this->productTypeRelationModel->getTypeIds($productInfo['id']);
           $productInfo['tag_ids']=$this->productTagRelationModel->getTagIds($productInfo['id']);
           $productInfo['expand_content']=empty($productInfo['expand_content'])?[]:json_decode($productInfo['expand_content'],true);
           if(!empty($productInfo['download_url'])){
               $productInfo['download_url']=  json_decode($productInfo['download_url'],true);
           }else{
               $productInfo['download_url']=[];
           }
           if(!empty($productInfo['sub_image_urls'])){
               $productInfo['sub_image_urls']=  json_decode($productInfo['sub_image_urls'],true);
           }else{
               $productInfo['sub_image_urls']=[];
           }
           if(!empty($productInfo['gallery_imgs'])){
               $productInfo['gallery_imgs']=  json_decode($productInfo['gallery_imgs'],true);
           }else{
               $productInfo['gallery_imgs']=[];
           }
           if(!empty($productInfo['size_imgs'])){
               $productInfo['size_imgs']=  json_decode($productInfo['size_imgs'],true);
           }else{
               $productInfo['size_imgs']=[];
           }
       }

       return $productInfo;
    }

    /**
     * 获取产品分类未关联的产品
     * */
    public function getUnrelatedProductByTypeIds($params){
        $ret=$this->model->getUnrelatedProductByTypeIds($params);
        return $ret;
    }

    /**
     * 获取产品标签未关联的产品
     * */
    public function getUnrelatedProductByTagIds($params){
        $ret=$this->model->getUnrelatedProductByTagId($params);
        return $ret;
    }

    public function getProductByTypeAndChildIds($typeIds)
    {
        $dataIds = $this->productTypeModel->getProductTypeChild($typeIds);
        $ids = array_column($dataIds, 'id');
        if (!empty($ids)) {
            return array_unique(array_merge($typeIds, $ids));
        } else {
            return $typeIds;
        }
    }
    /**
     * 获取已发布的连接
     * */
    public function getPublishProductList($params,$fields='',$data_type='') {
        if(empty($fields)) {
            $fields='a.id,a.pub_date,a.title,a.description,a.main_image,a.sub_image_urls,a.main_image_alt,a.image_url,a.image_alt,a.brand,a.model_nb,a.package,a.spec,'.
                'a.score,a.is_top,a.is_recommend,a.download_url,a.expand_content,a.total_view,b.urla';
        }
        $ids=[];
        if(!empty($params['type_ids'])) {
            $params['type_ids'] = $this->getProductByTypeAndChildIds($params['type_ids']);
            $typeProductList=$this->getProductByTypeIds(['type_id'=>$params['type_ids'],'page_size'=>99999,'page'=>1]);
            if(!empty($typeProductList['data'])){
                $ids=array_column($typeProductList['data'],'id');
            }
        }
        if(!empty($params['tag_ids'])) {
            $tagProductList=$this->getProductIdByTagIds(['tag_id'=>$params['tag_ids']]);
            if(!empty($tagProductList)){
                $tagReIds=array_column($tagProductList,'id');
                //dd($ids,$tagReIds,$data_type);
                if (!empty($ids) && !empty($data_type) && $data_type === 'intersect') {
                    $ids = array_intersect($ids,$tagReIds);
                } else {
                    $ids = array_unique(array_merge($ids,$tagReIds));
                }
                /*if(!empty($ids)){
                    $ids=array_merge($ids,$tagReIds);
                }*/
            }
        }
        if(!empty($ids) || ((empty($params['type_ids']) || $params['type_ids'] == 0) && (empty($params['tag_ids']) || $params['tag_ids'] == 0))){
            $params['ids']=$ids;
        } else {
            return [
                'data' => [],
                'current_page' => $params['page'],
                'per_page' => $params['page_size'],
                'total' => 0,
                'last_page' => 0,
                'from' => null,
                'to' => null,
            ];
        }
        $productList=$this->model->getPublishProductList($params,$fields);
        if(!empty($params['is_paginate'])) {
            $productListData=$productList['data'];
        } else {
            $productListData=$productList;
        }
        $productIds=array_column($productListData,'id');
        if($productIds){
            $newestTypeAndTagData=$this->getTypeAndTagDataByProductId($productIds);
            foreach ($productListData as &$productItem){
                if(!empty($newestTypeAndTagData[$productItem['id']]['type_items'])){
                    $productItem['type_items']=$newestTypeAndTagData[$productItem['id']]['type_items'];
                }else{
                    $productItem['type_items']=[];
                }
                if(!empty($newestTypeAndTagData[$productItem['id']]['tag_items'])){
                    $productItem['tag_items']=$newestTypeAndTagData[$productItem['id']]['tag_items'];
                }else{
                    $productItem['tag_items']=[];
                }
                if(!empty($productItem['spec'])){
                    $productItem['spec']=json_decode($productItem['spec'],true);
                }else{
                    $productItem['spec']=[];
                }
                $productItem['sub_image_urls']=empty($productItem['sub_image_urls'])?[]:json_decode($productItem['sub_image_urls'],true);
                $productItem['expand_content']=empty($productItem['expand_content'])?[]:json_decode($productItem['expand_content'],true);
                $productItem['expand_content'] = mapByKey($productItem['expand_content'],'key');
            }
            if(!empty($params['is_paginate'])){
                $productList['data']=$productListData;
            }else{
                $productList=$productListData;
            }

        }
        return $productList;
    }

    /**
     * 获取产品详情渲染数据
     * */
    public function getProductRenderData($params) {
        $productInfo= $this->model->getProductInfo($params);
        if(!empty($productInfo)){
            $newestTypeAndTagData=$this->getTypeAndTagDataByProductId([$productInfo['id']]);
            if(!empty($newestTypeAndTagData[$productInfo['id']]['type_items'])) {
                $productInfo['type_items']=$newestTypeAndTagData[$productInfo['id']]['type_items'];
            } else {
                $productInfo['type_items']=[];
            }
            if(!empty($newestTypeAndTagData[$productInfo['id']]['tag_items'])){
                $productInfo['tag_items']=$newestTypeAndTagData[$productInfo['id']]['tag_items'];
            }else{
                $productInfo['tag_items']=[];
            }
            if(!empty($productInfo['spec'])){
                $productInfo['spec']=json_decode($productInfo['spec'],true);
            }else{
                $productInfo['spec']=[];
            }
            if(!empty($productInfo['sub_image_urls'])){
                $productInfo['sub_image_urls']=json_decode($productInfo['sub_image_urls'],true);
            }else{
                $productInfo['sub_image_urls']=[];
            }
            if(!empty($productInfo['gallery_imgs'])){
                $productInfo['gallery_imgs']=json_decode($productInfo['gallery_imgs'],true);
            }else{
                $productInfo['gallery_imgs']=[];
            }
            if(!empty($productInfo['size_imgs'])){
                $productInfo['size_imgs']=json_decode($productInfo['size_imgs'],true);
            }else{
                $productInfo['size_imgs']=[];
            }
            if(!empty($productInfo['download_url'])){
                $productInfo['download_url']=json_decode($productInfo['download_url'],true);
            }else{
                $productInfo['download_url']=[];
            }
            $productInfo['expand_content']=empty($productInfo['expand_content'])?[]:json_decode($productInfo['expand_content'],true);
            $productInfo['expand_content'] = mapByKey($productInfo['expand_content'],'key');
        }
        return $productInfo;
    }

    /**
     * 获取产品列表页渲染数据
     * */
    public function getProductRecentlyData($params=[]){
        $data=[
            'product_type_list'=>[],//所有已发布的产品分类
            'product_tag_list'=>[],//所有正常标签
        ];
        $typeParams=[];
        $typeParams['status']=0;
        $typeParams['page_size']=9999;
        $data['product_type_list']=$this->getProductTypeList($typeParams);
        $tagParams=[];
        $tagParams['status']=0;
        $tagParams['page_size']=9999;
        $data['product_tag_list']=$this->getProductTagList($tagParams);
        return $data;
    }

    /**
     * 获取产品列表页渲染数据
     * */
    public function getProductTagData(){
        $tagParams=[];
        $tagParams['status']=0;
        $tagParams['page_size']=9999;
        $data=$this->getProductTagList($tagParams);
        return $data;
    }

    /**
     * 获取类型详情
     * */
    public function getProductTypeRenderInfo($params=[]){

        $typeWhere=[];
        $typeWhere['status']=0;
        $typeWhere['id']=empty($params['id'])?0:$params['id'];
        $typeInfo=$this->productTypeModel->getProductTypeInfo($typeWhere);
        return $typeInfo;
    }

    /**
     * 获取标签详情
     * */
    public function getProductTagRenderInfo($params=[]){
        $tagWhere=[];
        $tagWhere['status']=0;
        $tagWhere['id']=empty($params['tag_id'])?0:$params['tag_id'];
        $tagInfo=$this->productTagModel->getProductTagInfo($tagWhere);
        return $tagInfo;
    }



    /**
     * 获取相关商品
     * */
    public function getRelevanceList($params){
        $newestListParams=[];
        $newestListParams['page_size']=empty($params['relevance_page_size'])?5:$params['relevance_page_size'];
        $newestListParams['sort']['is_top']=1;
        $newestListParams['sort']['pub_date']=1;
        $newestListParams['type_ids']=empty($params['type_ids'])?[]:$params['type_ids'];
        $newestList=$this->getPublishProductList($newestListParams);
        return $newestList;
    }

    /**
     * 热门产品列表
     * */
    public function getHotList($params){
        $hotListParams=[];
        $hotListParams['page_size']=empty($params['hot_news_size'])?4:$params['hot_news_size'];
        $hotListParams['sort']['is_hot']=1;
        $hotListParams['sort']['pub_date']=1;
        $hotList=$this->getPublishProductList($hotListParams);
        return $hotList;
    }

    /**
     * 推荐产品列表
     * */
    public function getRecommendList($params){
        $recommendListParams=[];
        $recommendListParams['page_size']=empty($params['recommend_news_size'])?4:$params['recommend_news_size'];
        $recommendListParams['sort']['is_recommend']=1;
        $recommendListParams['sort']['pub_date']=1;
        $recommendList=$this->getPublishProductList($recommendListParams);
        return $recommendList;
    }



    /**
     * 根据产品id获取产品类型及产品标签数据
     * */
    public function getTypeAndTagDataByProductId($newestProductIds){
        $resultData=[];
        $newestTypeData=$this->productTypeRelationModel->getTypeListByProductIds($newestProductIds);
        foreach ($newestTypeData as $typeItem) {
            if (!empty($typeItem['expand_content'])) {
                $typeItem['expand_content'] = json_decode($typeItem['expand_content'],true);
                $typeItem['expand_content'] = mapByKey($typeItem['expand_content'],'key');
            }
            $resultData[$typeItem['product_id']]['type_items'][]=$typeItem;
        }
        $newestTagData=$this->productTagRelationModel->getTagListByProductIds($newestProductIds);
        foreach ($newestTagData as $tagItem){
            $resultData[$tagItem['product_id']]['tag_items'][]=$tagItem;
        }
        return $resultData;
    }

    /**
     * 根据类型id获取产品
     * */
    public function getPublishProductListByTypeId($params){
        $fields='a.id,a.pub_date,a.title,a.description,a.image_url,a.image_alt,a.is_top,a.is_recommend,a.download_url,a.total_view,b.type_id,c.urla';
        $ret=$this->model->getPublishProductListByTypeId($params,$fields);
        $productData=empty($ret['data'])?[]:$ret['data'];
        if(!empty($productData)){
            $newestProductIds=array_column($productData,'id');
            $newestTypeAndTagData=$this->getTypeAndTagDataByProductId($newestProductIds);
            foreach ($productData as &$productItem){
                if(!empty($newestTypeAndTagData[$productItem['id']]['type_items'])){
                    $productItem['type_items']=$newestTypeAndTagData[$productItem['id']]['type_items'];
                }else{
                    $productItem['type_items']=[];
                }
                if(!empty($newestTypeAndTagData[$productItem['id']]['tag_items'])){
                    $productItem['tag_items']=$newestTypeAndTagData[$productItem['id']]['tag_items'];
                }else{
                    $productItem['tag_items']=[];
                }
            }
            $ret['data']=$productData;
        }

        return $ret;
    }

    /**
     * 根据标签id获取产品
     * */
    public function getPublishProductListByTagId($params){
        $fields='a.id,a.pub_date,a.title,a.description,a.image_url,a.image_alt,a.is_top,a.is_recommend,a.download_url,a.total_view,b.tag_id,c.urla';
        $ret=$this->model->getPublishProductListByTagId($params,$fields);
        $productData=empty($ret['data'])?[]:$ret['data'];
        if(!empty($productData)){
            $newestProductIds=array_column($productData,'id');
            $newestTypeAndTagData=$this->getTypeAndTagDataByProductId($newestProductIds);
            foreach ($productData as &$productItem){
                if(!empty($newestTypeAndTagData[$productItem['id']]['type_items'])){
                    $productItem['type_items']=$newestTypeAndTagData[$productItem['id']]['type_items'];
                }else{
                    $productItem['type_items']=[];
                }
                if(!empty($newestTypeAndTagData[$productItem['id']]['tag_items'])){
                    $productItem['tag_items']=$newestTypeAndTagData[$productItem['id']]['tag_items'];
                }else{
                    $productItem['tag_items']=[];
                }
            }
            $ret['data']=$productData;
        }
        return $ret;
    }

    /**
     * 搜索获取已发布的产品
     * */
    public function getSearchProductList($params){
        if(empty($fields)){
            $fields='a.id,a.title,b.urla';
        }
        $productList=$this->model->getPublishProductList($params,$fields);
        return $productList;
    }

    /**
     * 新闻排序
     */
    public function changeProductSort($productId, $sort)
    {
        $data = [];
        $getData = $this->findOneById($productId, 'id,sort');
        if ($sort == 0) { // 置顶
            $sortData = $this->findOneBy([
                'sort' => $sort,
                'id' => ['<>', $productId]
            ], 'id');
            if (empty($sortData['id'])) {
                throw new ApiException(1004, ['msg' => '当前已经是最高一行']);
            }
            if ($getData['sort'] == 0) {
                $this->incrementBy([
                    'id' => ['<>', $productId],
                ], 'sort');
            } else {
                $this->incrementBy([
                    'id' => ['<', $productId],
                ], 'sort');
            }
            $upData['sort']= $sort;
        } elseif ($sort == '-1') { // 上移
            $upSortData = $this->model->where('sort', '<', $getData['sort'])
                ->orderBy('sort', 'desc')->first();
            if (empty($upSortData)) {
                throw new ApiException(1004, ['msg' => '当前已经是最高一行']);
            } else {
                $upData = $upSortData->toArray();
            }
        } elseif ($sort == '+1') { // 下移
            $downSortData = $this->model->where('sort', '>', $getData['sort'])
                ->orderBy('sort', 'asc')->first();
            if (empty($downSortData)) {
                throw new ApiException(1004, ['msg' => '当前已经是最后一行']);
            } else {
                $upData = $downSortData->toArray();
            }
        }
        $data['sort'] = $upData['sort'];
        $this->updateBy([
            'sort' => $data['sort']
        ], [
            'sort' => $getData['sort']
        ]);
        $is_top=0;
        if($data['sort']==0){
            $is_top=1;
        }
        $rst = $this->update($productId, [
            'sort' => $data['sort'],
            'is_top'=>$is_top
        ]);
        //更新所有页面缓存
        WebFacade::clearPageCache('urla:');
        return $rst;

    }


    public function getProductByIds($ids) {
        $pageListData=$this->model->getProductByIds($ids);
        if(!empty($pageListData)){
            $ids=array_column($pageListData,'seo_id');
            $seoList=[];
            if(!empty($ids)){
                $seoList=WebFacade:: getSeoListByIds($ids);
                if(!empty($seoList)){
                    $seoList=mapByKey($seoList,'id');
                }
            }
            foreach ($pageListData as &$pageItem){
                $pageItem['type_items'] = [];
                if (!empty($pageItem['type_ids'])) {
                    foreach ($pageItem['type_ids'] as $typeId) {
                        $type_info = $this->productTypeModel->getProductTypeInfo(["id"=>$typeId]);
                        if (!empty($type_info['expand_content'])) {
                            $type_info['expand_content'] = json_decode($type_info['expand_content'],true);
                            $type_info['expand_content'] = mapByKey($type_info['expand_content'],'key');
                        }
                        $pageItem['type_items'][] = $type_info;
                    }
                }
                $pageItem['seo_data']=empty($seoList[$pageItem['seo_id']])?[]:$seoList[$pageItem['seo_id']];
            }
        }
        return $pageListData;
    }


    public function productCenterSync($params)
    {
        set_time_limit(1200);
        ignore_user_abort(true);
        $data = empty($params['list']) ? [] : $params['list'];
        $productTypeData = $params['product_type_data'];
        $productTagData = $params['product_tag_data'];
        $isReplaceOss = $params['is_replace_oss'] ?? true;
        $syncRet = ['succeed' => 0, 'error' => 0];
        $userId = $this->getAuthUserId();

        $productTypeSyncRe = $this->saveSyncProductTypeData($productTypeData, $userId);
        $productTagSyncRe = $this->saveSyncProductTagData($productTagData, $userId);

        $productData = array_column($data, 'product_data');
        $productNameList = array_column($productData, 'name');
        $productNameList = array_unique($productNameList);
        $yetProductData = $this->model->newInstance()->alias('a')
            ->where('a.status', '=', 0)
            ->whereIn('a.title', $productNameList)
            ->selectRaw('a.id,a.title AS name')
            ->get();
        if (!empty($yetProductData)) {
            $yetProductData = $yetProductData->toArray();
            $yetProductData = mapByKey($yetProductData, 'name');
        } else {
            $yetProductData = [];
        }
        foreach ($productData as $item) {
            if (!empty($yetProductData[$item['name']])) {
                $syncRet['error'] = ++$syncRet['error'];
                continue;
            }
            $productItem = [];
            $productItem['title'] = $item['name'];
            if($isReplaceOss && !empty($item['image_url'])){
                $item['image_url'] = UploadFileFacade::uploadRemoteImg($item['image_url']);
            }
            $productItem['image_url'] = $item['image_url'];
            $productItem['image_alt'] = $item['image_alt'];
            $productItem['main_image'] = $item['image_url'];
            $productItem['main_image_alt'] = $item['image_alt'];
            $productItem['brand'] = $item['brand_name'];
            $productItem['model_nb'] = $item['goods_sn'];
            if($isReplaceOss && !empty($item['content'])) {
                $item['content'] = preg_replace_callback(
                    '/https?:\/\/[^\s^\"]*/',
                    function ($matches) {
                        return UploadFileFacade::uploadRemoteImg($matches[0]);
                    },
                    $item['content']
                );
            }
            $productItem['content'] = $item['content'];
            if($isReplaceOss && !empty($item['sub_image_urls'])) {
                foreach ($item['sub_image_urls'] as &$subImage) {
                    $subImage['url'] = UploadFileFacade::uploadRemoteImg($subImage['url']);
                }
            }
            $productItem['sub_image_urls'] = !empty($item['sub_image_urls']) ? json_encode($item['sub_image_urls'], true) : '';
            $productItem['description'] = $item['description'];
            $productItem['sort'] = $item['sort'];
            $productItem['re_price'] = $item['re_price'];
            $productItem['market_price'] = $item['market_price'];
            $productItem['currency'] = $item['currency'];
            if($isReplaceOss && !empty($item['file_url'])){
                $item['file_url'] = UploadFileFacade::uploadRemoteImg($item['file_url']);
            }
            $productItem['download_url'] = $item['file_url'];
            $productItem['user_id'] = $userId;
            $productItem['create_time'] = nowTime();
            $productItem['update_time'] = nowTime();
            $productItem['pub_date'] = nowTime();
            $newProductId = $this->model->insertGetId($productItem);

            $this->addWebSeo($newProductId, $userId, $item['name'],
                WebService::RELATION_TABLE_PRODUCT, $this->model);

            if (!empty($item['cat_id']) && !empty($productTypeSyncRe[$item['cat_id']])) {
                //分类处理
                $this->productTypeRelationModel->addByProductId($newProductId, [$productTypeSyncRe[$item['cat_id']]]);
            }
            //分类标签
            if (!empty($productTagSyncRe[$item['id']])) {
                $this->productTagRelationModel->addByProductId($newProductId, $productTagSyncRe[$item['id']]);
            }
            $syncRet['succeed'] = ++$syncRet['succeed'];
        }
        $messageTitle = '产品中心同步商品至' . config('app.name') . '完成';
        $messageContent = '成功同步商品：' . $syncRet['succeed'];
        if (!empty($syncRet['error'])) {
            $messageContent .= ';' . '商品名称重复导入失败：' . $syncRet['error'];
        }
        $syncRet['message'] = $messageTitle.$messageContent;
        return $syncRet;
    }

    /**
     * 保存同步产品类型数据
     * */
    public function saveSyncProductTypeData($productTypeData, $userId)
    {
        $productTypeSyncRe = [];
        $syncProductTypeSourceData = [];
        // 同步产品类型数据
        foreach ($productTypeData as $subItem) {
            if (empty($syncProductTypeSourceData[$subItem['id']])) {
                $tempItem = [];
                $tempItem['type_name'] = $subItem['type_name'];
                $tempItem['parent_name'] = $subItem['parent_name'] ?? '';
                $tempItem['grand_name'] = $subItem['grand_name'] ?? '';
                $tempItem['level'] = $subItem['level'];
                $tempItem['user_id'] = $userId;
                $syncProductTypeSourceData[$subItem['id']] = $tempItem;
            }
        }
        $nameList = array_column($syncProductTypeSourceData, 'type_name');
        $yetData = [];
        $insertData = [];
        if (!empty($nameList)) {
            $yetData = $this->productTypeModel->alias('a')
                ->leftJoin('product_type as b', 'a.p_id', '=', 'b.id')
                ->leftJoin('product_type as c', 'b.p_id', '=', 'c.id')
                ->where('a.status', '=', 0)
                ->whereIn('a.type_name', $nameList)
                ->selectRaw('a.*,b.type_name AS parent_name,c.type_name AS grand_name')
                ->get()->toArray();
        }
        if (!empty($yetData)) {
            $yetData = mapByKey($yetData, 'type_name');
            foreach ($syncProductTypeSourceData as $typeId => $item) {
                if (!empty($yetData[$item['type_name']]) &&
                    $yetData[$item['type_name']]['parent_name'] == $item['parent_name'] &&
                    $yetData[$item['type_name']]['grand_name'] == $item['grand_name']
                ) {
                    $productTypeSyncRe[$typeId] = $yetData[$item['type_name']]['id'];
                } else {
                    $insertData[] = $item;
                }
            }
        } else {
            $insertData = $syncProductTypeSourceData;
        }
        foreach ($insertData as $typeId => $item) {
            if ($item['level'] == 1) {
                $newId = $this->insertProductType($userId, 0, 1, '', $item['type_name']);
            } else if ($item['level'] == 2) {
                $pId = $this->insertProductType($userId, 0, 1, '', $item['parent_name']);
                $newId = $this->insertProductType($userId, $pId, 2, $pId, $item['type_name']);
            } else if ($item['level'] == 3) {
                $gId = $this->insertProductType($userId, 0, 1, '', $item['grand_name']);
                $pId = $this->insertProductType($userId, $gId, 2, $gId, $item['parent_name']);
                $newId = $this->insertProductType($userId, $pId, 3, $gId.','.$pId, $item['type_name']);
            } else {
                $newId = $this->insertProductType($userId, 0, 1, '', $item['type_name']);
            }
            $productTypeSyncRe[$typeId] = $newId;
        }
        return $productTypeSyncRe;
    }

    /**
     * 插入产品分类
     * @param $userId
     * @param $parentId
     * @param $level
     * @param $path
     * @param $name
     * @return mixed
     */
    public function insertProductType($userId, $parentId, $level, $path, $name)
    {
        $old = $this->productTypeModel->alias('a')
            ->where('a.status', '=', 0)
            ->where('a.type_name', '=', $name)
            ->where('a.level', '=', $level)
            ->where('a.p_id', '=', $parentId)
            ->first();
        if(!empty($old)) {
            $old = $old->toArray();
            $id = $old['id'];
        } else {
            $insertItem = [];
            $insertItem['user_id'] = $userId;
            $insertItem['p_id'] = $parentId;
            $insertItem['level'] = $level;
            $insertItem['path'] = $path;
            $insertItem['path_name'] = $name;
            $insertItem['description'] = $name;
            $insertItem['type_name'] = $name;
            $insertItem['create_time'] = nowTime();
            $insertItem['update_time'] = nowTime();
            $id = $this->productTypeModel->insertGetId($insertItem);
            //添加SEO信息
            $this->addWebSeo($id, $userId, $name,
                WebService::RELATION_TABLE_PRODUCT_TYPE, $this->productTypeModel);
        }
        return $id;
    }

    /**
     * 保存同步产品标签数据
     * */
    public function saveSyncProductTagData($productTagData, $userId)
    {
        $productTagSyncRe = [];
        $syncProductTagSourceData = [];
        // 同步产品标签数据
        $nameList = [];
        foreach ($productTagData as $goodId => $tagItem) {
            foreach ($tagItem as $subItem) {
                if (empty($syncProductTagSourceData[$goodId][$subItem['id']])) {
                    $tempItem = [];
                    $tempItem['tag_name'] = $subItem['tag_name'];
                    $tempItem['user_id'] = $userId;
                    $syncProductTagSourceData[$goodId][$subItem['id']] = $tempItem;
                    $nameList[] = $subItem['tag_name'];
                }
            }
        }
        $yetData = [];
        if (!empty($nameList)) {
            $nameList = array_unique($nameList);
            $yetData = $this->productTagModel->alias('a')
                ->where('a.status', '<', 2)
                ->whereIn('a.tag_name', $nameList)->get()->toArray();
        }
        if (!empty($yetData)) {
            $yetData = mapByKey($yetData, 'tag_name');

        }
        foreach ($syncProductTagSourceData as $goodId => $item) {
            foreach ($item as $subItem) {
                $item['user_id'] = $userId;
                if (!empty($yetData[$subItem['tag_name']])) {
                    $productTagSyncRe[$goodId][] = $yetData[$subItem['tag_name']]['id'];
                } else {
                    $newId = $this->productTagModel->insertGetId($subItem);

                    $this->addWebSeo($newId, $userId, $subItem['tag_name'],
                        WebService::RELATION_TABLE_PRODUCT_TAG, $this->productTagModel);

                    $yetData[$subItem['tag_name']] = $subItem;
                    $yetData[$subItem['tag_name']]['id'] = $newId;
                    $productTagSyncRe[$goodId][] = $newId;
                }
            }
        }
        return $productTagSyncRe;
    }

    public function addWebSeo($id, $userId, $sourceName, $table, $model)
    {
        $py = app()->make(PinYinService::class);
        $name = strtolower($py->getAllPY($sourceName));
        $nameUrl = preg_replace('/[^a-zA-Z0-9_u4e00-u9fa5]/', '-', $name);
        $seoParams = [];
        $seoParams['relation_table'] = $table;
        $seoParams['relation_id'] = $id;
        if (strlen($nameUrl) > 200) {
            $nameUrl = substr($nameUrl, 0, 200);
        }
        $urlEx = WebFacade::checkUrlaUnique($nameUrl);
        if (!$urlEx) {
            $nameUrl .= '-' . strtolower(uniqid());
        }
        $seoParams['urla'] = $nameUrl;
        $seoParams['seo_title'] = substr($sourceName, 0, 255);
        $seoParams['seo_keyword'] = substr($sourceName, 0, 255);
        $seoParams['seo_describe'] = substr($sourceName, 0, 255);
        $seoParams['user_id'] = $userId;
        $urlaId = WebFacade::saveSeoData($seoParams);
        $model->newInstance()->where('id', '=', $id)->update(['seo_id' => $urlaId]);
    }

    /**
     * 批量修改类型
     * @param $params
     * @return true
     */
    public function typePluralEdit($params)
    {
        $userId = $this->getAuthUserId();
        $ret = 1;
        foreach ($params['ids'] as $v) {
            $ret = $this->productTypeRelationModel->addByProductId($v, $params['type_ids'], $userId);
        }
        return $ret;
    }

    /**
     * 批量修改标签
     * @param $params
     * @return true
     */
    public function tagPluralEdit($params)
    {
        $userId = $this->getAuthUserId();
        $ret = 1;
        foreach ($params['ids'] as $v) {
            $ret = $this->productTagRelationModel->addByProductId($v, $params['tag_ids'], $userId);
        }
        return $ret;
    }

    /**
     * 批量删除
     * @param $params
     * @return mixed
     */
    public function batchDelete($params)
    {
        $ids = $params['ids'];
        $rst = $this->model->whereIn('id', $ids)->update(['status' => 2]);
        //删除处理
        if ($rst) {
            $this->productTypeRelationModel->deleteByProductId($ids);
            $this->productTagRelationModel->deleteByProductId($ids);
        }
        return $rst;
    }

    /**
     * 批量修改状态
     * @param $params
     * @return mixed
     */
    public function batchStatus($params)
    {
        $ids = $params['ids'];
        $status = $params['status'];
        $rst = $this->model->whereIn('id', $ids)->update(['status' => $status]);
        return $rst;
    }


}
