<?php


namespace App\Web\Models;



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


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


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

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

    /**
     * 产品类型对应的产品数量
     * */
    public function getMeetingTagCount($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 getMeetingByTagIds($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];
        if(!empty($tagId)){
            if(is_array($tagId)){
                $query= $this->newInstance()->alias('a')
                    ->leftJoin('meeting as b','a.meeting_id','=','b.id')
                    ->where($where)
                    ->whereIn('a.tag_id',$tagId);
            }else{
                $where[]=['a.tag_id','=',$tagId];
                $query= $this->newInstance()->alias('a')
                    ->leftJoin('meeting as b','a.meeting_id','=','b.id')
                    ->where($where);
            }
        }else{
            $query= $this->newInstance()->alias('a')
                ->leftJoin('meeting as b','a.meeting_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, $meetingIds)
    {
        $ret=$this->newInstance()
            ->where('status','=',0)
            ->where('tag_id','=',$tagId)
            ->whereIn('meeting_id',$meetingIds)
            ->update(['update_time'=>nowTime(),'status'=>2]);
        return $ret;
    }

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

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

    /**
     * 添加关联关系
     * @param $meetingId
     * @param $tagIds
     */
    public function addByMeetingId($meetingId, $tagIds, $userId = 0)
    {
        $hadTags = $this->getByMeetingId($meetingId);
        $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('meeting_id', $meetingId)
                ->whereIn('tag_id', $deleteTagIds)
                ->update(['status' => 2]);
        }

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

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

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