<?php


namespace App\Web\Models;



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


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

    /**
     * 文章类型关系保存
     * */
    public function typeRelationSave($params,$userId=0){
        $helpId=$params['help_id'];
        $typeIds=$params['type_ids'];
        $time=nowTime();
        if(!empty($typeIds)){
            //获取要保留下来的权限
            $remainedIds= $this->newInstance()
                ->where('help_id',$helpId)
                ->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,
                    '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('type_id',$typeIds)
                ->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 addByTypeId($typeId, $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.type_id','=',$typeId)
            ->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,
                'type_id' => $typeId
            ];
        }
        if(!empty($saveData)){
            $this->insert($saveData);
        }
        return true;
    }

    /**
     * 文章类型对应的文章数量
     * */
    public function getHelpTypeCount($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 getHelpByTypeIds($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];
        $where[]=['a.type_id','=',$typeId];

        $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 delTypeRelation($typeId, $helpIds)
    {
        $ret=$this->newInstance()
            ->where('status','=',0)
            ->where('type_id','=',$typeId)
            ->whereIn('help_id',$helpIds)
            ->update(['update_time'=>nowTime(),'status'=>2]);
        return $ret;
    }

    /**
     * 获取文章类型ids
     * */
    public function getTypeIds($helpId){
        $typeIds= $this->newInstance()
            ->where('help_id','=',$helpId)
            ->where('status','=',0)
            ->pluck('type_id')->toArray();
        return $typeIds;
    }

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