<?php


namespace App\Web\Models;



use App\Models\BaseModel;
use App\Services\CommonService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class ProductTagRelationModel extends BaseModel
{
    /**
     * 状态字段
     */
    const DELETED_AT = 'status';
    /**
     * @var string
     */
    protected $table = 'product_tag_relation';


    /**
     * 产品标签关系保存
     * */
    public function tagRelationSave($params,$userId=0){
        $productId=$params['product_id'];
        $tagIds=$params['tag_ids'];
        $time=nowTime();
        if(!empty($tagIds)){
            //获取要保留下来的权限
            $remainedIds= $this->newInstance()
                ->where('product_id',$productId)
                ->where('status',0)
                ->whereIn('tag_id',$tagIds)
                ->pluck('tag_id')->toArray();
            $addTagIds=array_diff($tagIds,$remainedIds);//获取要新增的权限
            $insertData=[];
            foreach ($addTagIds as $value){
                $insertData[]=[
                    'tag_id'=>$value,
                    'product_id'=>$productId,
                    'user_id'=>$userId,
                    'create_time'=>$time,
                    'update_time'=>$time
                ];
            }
            //插入新增的权限
            if(!empty($insertData)){
                $this->insert($insertData);
            }
            //删除移除的权限
            $this->where('product_id',$productId)->where('status',0)
                ->WhereNotIn('tag_id',$tagIds)
                ->update(['status'=>2,'update_time'=>$time]);
        }else{
            $this->where('product_id',$productId)->where('status',0)
                ->update(['status'=>2,'update_time'=>$time]);
        }
        return $productId;
    }

    /**
     *  根据产品标签 保存产品关系
     * */
    public function addByTagId($tagId, $productIds,$userId=0)
    {
        if (empty($productIds)) {
            return 0;
        }
        $yetProductIds = $this->newInstance()->alias('a')
            ->leftJoin('product as b','a.product_id','=','b.id')
            ->where('a.status','=',0)
            ->where('b.status','<',2)
            ->where('a.tag_id','=',$tagId)
            ->whereIn('a.product_id',$productIds)
            ->pluck('a.product_id')->toArray();
        $addProductIds=$productIds;
        if(!empty($yetProductIds)){
            $addProductIds=array_diff($productIds,$yetProductIds);//获取要新增的权限
        }
        $saveData=[];
        foreach ($addProductIds as $productId) {
            $saveData[] = [
                'user_id' => $userId,
                'product_id' => $productId,
                'tag_id' => $tagId,
                'create_time'=>nowTime(),
                'update_time'=>nowTime()
            ];
        }
        if(!empty($saveData)){
            $this->insert($saveData);
        }
        return true;
    }

    /**
     * 产品类型对应的产品数量
     * */
    public function getProductTagCount($tagIds){
        is_array($tagIds) && $tagIds = [['in', $tagIds]];
        $rst = $this->newInstance()->buildQuery([
            'tag_id' => $tagIds,
            'status' => 0
        ])->groupBy('tag_id')
            ->select(DB::raw('tag_id, count(*) as tmp_count'))
            ->get()
            ->toArray();

        $data = [];
        foreach ($rst as $v) {
            $data[$v['tag_id']] = $v['tmp_count'];
        }
        return $data;
    }
    public function getProductIdByTagIds($params) {
        $tagId = $params['tag_id'] ?? '';
        $where=[];
        if(isset($params['status'])){
            $where[]=['b.status','=',$params['status']];
        } else {
            $where[]=['b.status','<',2];
        }
        $where[]=['a.status','=',0];
        // 添加过滤当前产品id的条件
        if (isset($params['exclude_product_id'])) {
            $where[] = ['a.product_id', '!=', $params['exclude_product_id']];
        }
        if(!empty($tagId)){
            if(is_array($tagId)){
                $query= $this->newInstance()->alias('a')
                    ->leftJoin('product as b','a.product_id','=','b.id')
                    ->where($where)
                    ->whereIn('a.tag_id',$tagId);
            }else{
                $where[]=['a.tag_id','=',$tagId];
                $query= $this->newInstance()->alias('a')
                    ->leftJoin('product as b','a.product_id','=','b.id')
                    ->where($where);
            }
        }else{
            $query= $this->newInstance()->alias('a')
                ->leftJoin('product as b','a.product_id','=','b.id')
                ->where($where);
        }

        $fields='b.id';
        $list= $query
            ->groupBy('b.id')
            ->selectRaw($fields)->get();
        if(!empty($list)){
            $list=$list->toArray();
        }else{
            $list=[];
        }
        return $list;
    }
    /**
     * 根据标签id 获取产品列表
     * */
    public function getProductByTagIds($params){
        list($pageSize) = $this->getPaginatorParams($params);
        $tagId = $params['tag_id'] ?? '';
        $where=[];
        if(isset($params['status'])){
            $where[]=['b.status','=',$params['status']];
        }else{
            $where[]=['b.status','<',2];
        }
        $where[]=['a.status','=',0];
        // 添加过滤当前产品id的条件
        if (isset($params['exclude_product_id'])) {
            $where[] = ['a.product_id', '!=', $params['exclude_product_id']];
        }

        if(!empty($tagId)){
            if(is_array($tagId)){
                $query= $this->newInstance()->alias('a')
                    ->leftJoin('product as b','a.product_id','=','b.id')
                    ->where($where)
                    ->whereIn('a.tag_id',$tagId);
            }else{
                $where[]=['a.tag_id','=',$tagId];
                $query= $this->newInstance()->alias('a')
                    ->leftJoin('product as b','a.product_id','=','b.id')
                    ->where($where);
            }
        }else{
            $query= $this->newInstance()->alias('a')
                ->leftJoin('product as b','a.product_id','=','b.id')
                ->where($where);
        }

        $fields='b.id,b.title,b.pub_date,b.image_url,b.description,b.status,b.update_time,b.create_time';
        $list= $query
            ->limit($pageSize)
            ->groupBy('b.id')
            ->selectRaw($fields)
            ->paginate($pageSize);
        if(!empty($list)){
            $list=$list->toArray();
        }else{
            $list=[];
        }
        return $list;
    }

    /**
     * 根据标签id及产品id 删除关联关系
     * */
    public function delTagRelation($tagId, $productIds)
    {
        $ret=$this->newInstance()
            ->where('status','=',0)
            ->where('tag_id','=',$tagId)
            ->whereIn('product_id',$productIds)
            ->update(['update_time'=>nowTime(),'status'=>2]);
        return $ret;
    }

    /**
     * 获取产品标签ids
     * */
    public function getTagIds($productId){
        $tagIds= $this->newInstance()
            ->where('product_id','=',$productId)
            ->where('status','=',0)
            ->pluck('tag_id')->toArray();
        return $tagIds;
    }

    /**
     * 根据产品id列表返回标签列表
     * */
    public function getTagListByProductIds($productIds){
        $tagList= $this->newInstance()->alias('a')
            ->leftJoin('product_tag as b','a.tag_id','=','b.id')
            ->leftJoin('web_seo as c', 'b.seo_id', '=', 'c.id')
            ->whereIn('a.product_id',$productIds)
            ->where('a.status','=',0)
            ->where('b.status','=',0)
            ->selectRaw('a.product_id,a.tag_id,b.tag_name,b.type,c.urla,c.seo_title')->get();
        if(!empty($tagList)){
            $tagList=$tagList->toArray();
        }else{
            $tagList=[];
        }
        return $tagList;
    }

    /**
     * 添加关联关系
     * @param $productId
     * @param $tagIds
     */
    public function addByProductId($productId, $tagIds, $userId = 0)
    {
        $hadTags = $this->getByProductId($productId);
        $hadTagIds = array_column($hadTags, 'tag_id');
        $deleteTagIds = array_values(array_diff($hadTagIds, $tagIds));
        $tagIds = array_values(array_diff($tagIds, $hadTagIds));

        if (!empty($deleteTagIds)) {
            $this->newInstance()
                ->where('product_id', $productId)
                ->whereIn('tag_id', $deleteTagIds)
                ->update(['status' => 2]);
        }

        $saveData = [];
        foreach ($tagIds as $tagId) {
            if (empty($tagId)) {
                continue;
            }
            $saveData[] = [
                'user_id' => $userId,
                'product_id' => $productId,
                'tag_id' => $tagId,
                'create_time'=>nowTime(),
                'update_time'=>nowTime()
            ];
        }
        return $this->insert($saveData);
    }

    public function getByProductId($productId)
    {
        if (empty($productId)) {
            return [];
        }
        if(!is_array($productId)) {
            $productId = [$productId];
        }
        $rst = $this->newInstance()
            ->whereIn('product_id', $productId)
            ->get();
        return empty($rst) ? []: $rst->toArray();
    }

    public function deleteByProductId($productId)
    {
        if (!is_array($productId)) {
            $productId = [$productId];
        }
        $ret = $this->newInstance()
            ->whereIn('product_id', $productId)
            ->update(['status' => 2]);
        return $ret;
    }
}
