<?php


namespace App\Web\Models;



use App\Models\BaseModel;
use Illuminate\Support\Facades\DB;


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


    /**
     * 文章标签关系保存
     * */
    public function tagRelationSave($params,$userId=0){
        $helpId=$params['help_id'];
        $tagIds=$params['tag_ids'];
        $time=nowTime();
        if(!empty($tagIds)){
            //获取要保留下来的权限
            $remainedIds= $this->newInstance()
                ->where('help_id',$helpId)
                ->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,
                    'help_id'=>$helpId,
                    'user_id'=>$userId,
                    'create_time'=>$time,
                    'update_time'=>$time
                ];
            }
            //插入新增的权限
            if(!empty($insertData)){
                $this->insert($insertData);
            }
            //删除移除的权限
            $this->where('help_id',$helpId)->where('status',0)
                ->WhereNotIn('tag_id',$tagIds)
                ->update(['status'=>2,'update_time'=>$time]);
        }else{
            $this->where('help_id',$helpId)->where('status',0)
                ->update(['status'=>2,'update_time'=>$time]);
        }
        return $helpId;
    }

    /**
     *  根据文章标签 保存文章关系
     * */
    public function addByTagId($tagId, $helpIds,$userId=0)
    {
        if (empty($helpIds)) {
            return 0;
        }
        $yetHelpIds = $this->newInstance()->alias('a')
            ->leftJoin('help as b','a.help_id','=','b.id')
            ->where('a.status','=',0)
            ->where('b.status','<',2)
            ->where('a.tag_id','=',$tagId)
            ->whereIn('a.help_id',$helpIds)
            ->pluck('a.help_id')->toArray();
        $addHelpIds=$helpIds;
        if(!empty($yetHelpIds)){
            $addHelpIds=array_diff($helpIds,$yetHelpIds);//获取要新增的权限
        }
        $saveData=[];
        foreach ($addHelpIds as $helpId) {
            $saveData[] = [
                'user_id' => $userId,
                'help_id' => $helpId,
                'tag_id' => $tagId
            ];
        }
        if(!empty($saveData)){
            $this->insert($saveData);
        }
        return true;
    }

    /**
     * 文章类型对应的文章数量
     * */
    public function getHelpTagCount($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;
    }

    /**
     * 根据标签id 获取文章列表
     * */
    public function getHelpByTagIds($params){
        list($pageSize, $page, $skip) = $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];
        $where[]=['a.tag_id','=',$tagId];

        $query= $this->newInstance()->alias('a')
            ->leftJoin('help as b','a.help_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';
        $totalCount = $query->count();
        $list= $query->skip($skip)
            ->limit($pageSize)
            ->selectRaw($fields)
            ->orderBy('sort')
            ->get();
        if(!empty($list)){
            $list=$list->toArray();
        }else{
            $list=[];
        }
        $result = $this->buildPaginator($list, $skip, $page, $pageSize, $totalCount);
        return $result;
    }

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

    /**
     * 获取文章标签ids
     * */
    public function getTagIds($helpId){
        $tagIds= $this->newInstance()
            ->where('help_id','=',$helpId)
            ->where('status','=',0)
            ->pluck('tag_id')->toArray();
        return $tagIds;
    }

    /**
     * 根据文章id列表返回标签列表
     * */
    public function getTagListByHelpIds($helpIds){
        $tagList= $this->newInstance()->alias('a')
            ->leftJoin('help_tag as b','a.tag_id','=','b.id')
            ->leftJoin('web_seo as c', 'b.seo_id', '=', 'c.id')
            ->whereIn('a.help_id',$helpIds)
            ->where('a.status','=',0)
            ->where('b.status','=',0)
            ->selectRaw('a.help_id,a.tag_id,b.tag_name,c.urla')->get();
        if(!empty($tagList)){
            $tagList=$tagList->toArray();
        }else{
            $tagList=[];
        }
        return $tagList;
    }
}
