<?php


namespace App\Web\Models;



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


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

    /**
     * 产品类型关系保存
     * */
    public function typeRelationSave($params,$userId=0){
        $meetingId=$params['meeting_id'];
        $typeIds=$params['type_ids'];
        $time=nowTime();
        if(!empty($typeIds)){
            //获取要保留下来的权限
            $remainedIds= $this->newInstance()
                ->where('meeting_id',$meetingId)
                ->where('status',0)
                ->whereIn('type_id',$typeIds)
                ->pluck('type_id')->toArray();
            $addTypeIds=array_diff($typeIds,$remainedIds);//获取要新增的权限
            $insertData=[];
            foreach ($addTypeIds as $value){
                $insertData[]=[
                    'type_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('type_id',$typeIds)
                ->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 addByTypeId($typeId, $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.type_id','=',$typeId)
            ->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,
                'type_id' => $typeId
            ];
        }
        if(!empty($saveData)){
            $this->insert($saveData);
        }
        return true;
    }

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

        $data = [];
        foreach ($rst as $v) {
            $data[$v['type_id']] = $v['tmp_count'];
        }
        return $data;
    }

    /**
     * 根据类型id 获取产品列表
     * */
    public function getMeetingByTypeIds($params){
        list($pageSize, $page, $skip) = $this->getPaginatorParams($params);
        $typeId = $params['type_id'] ?? '';
        $where=[];
        if(isset($params['status'])){
            $where[]=['b.status','=',$params['status']];
        }else{
            $where[]=['b.status','<',2];
        }
        $where[]=['a.status','=',0];
        if(!empty($typeId)){
            if(is_array($typeId)){
                $query= $this->newInstance()->alias('a')
                    ->leftJoin('meeting as b','a.meeting_id','=','b.id')
                    ->where($where)
                    ->whereIn('a.type_id',$typeId);
            }else{
                $where[]=['a.type_id','=',$typeId];
                $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 delTypeRelation($typeId, $meetingIds)
    {
        $ret=$this->newInstance()
            ->where('status','=',0)
            ->where('type_id','=',$typeId)
            ->whereIn('meeting_id',$meetingIds)
            ->update(['update_time'=>nowTime(),'status'=>2]);
        return $ret;
    }

    /**
     * 获取产品类型ids
     * */
    public function getTypeIds($meetingId){
        $typeIds= $this->newInstance()
            ->where('meeting_id','=',$meetingId)
            ->where('status','=',0)
            ->pluck('type_id')->toArray();
        return $typeIds;
    }

    /**
     * 根据产品id列表返回标签列表
     * */
    public function getTypeListByMeetingIds($meetingIds){
        $typeList= $this->newInstance()->alias('a')
            ->leftJoin('meeting_type as b','a.type_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.type_id,b.type_name,c.urla')->get();
        if(!empty($typeList)){
            $typeList=$typeList->toArray();
        }else{
            $typeList=[];
        }
        return $typeList;
    }

    public function addByMeetingId($meetingId, $typeIds, $userId = 0)
    {
        $types = $this->getByMeetingId($meetingId);
        $hadTypeIds = array_column($types, 'type_id');
        $delTypeIds = array_values(array_diff($hadTypeIds, $typeIds));
        $typeIds = array_values(array_diff($typeIds, $hadTypeIds));
        //删除数据
        if ($delTypeIds) {
            $this->newInstance()
                ->where('meeting_id', $meetingId)
                ->whereIn('type_id', $delTypeIds)
                ->update(['status' => 2]);
        }
        if (empty($typeIds)) {
            return 0;
        }
        $saveData = [];
        foreach ($typeIds as $typeId) {
            if (empty($typeId)) {
                continue;
            }
            $saveData[] = [
                'user_id' => $userId,
                'meeting_id' => $meetingId,
                'type_id' => $typeId,
                '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;
    }
}
