<?php


namespace App\Web\Models;



use App\Models\BaseModel;


class ProductPlateModel extends BaseModel
{


    /**
     * 状态字段
     */
    const DELETED_AT = 'status';

    /**
     * @var string
     */
    protected $table = 'product_plate';

    /**
     * 获取产品板块
     * */
    public function getProductPlateList($params,$fields=''){
        list($pageSize, $page, $skip) = $this->getPaginatorParams($params);
        $where=[];
        if(isset($params['status'])){
            $where[]=['a.status','=',$params['status']];
        }else{
            $where[]=['a.status','<',2];
        }
        if(empty($fields)){
            $fields='a.*,b.urla,b.seo_title,b.seo_keyword,b.seo_describe';
        }
        $query= $this->newInstance()->alias('a')
            ->leftJoin('web_seo as b', 'a.seo_id', '=', 'b.id')
            ->where($where);
        if (!empty($params['keyword'])) {
            $keyword = $params['keyword'];
            $query->where('a.plate_name', 'like', "%" . $keyword . "%");
        }
        $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;
    }


    /**
     * 产品类型保存
     * @param array $data
     * */
    public function savePlateData($data){
        if (!empty($data['id'])) {
            $id = $data['id'];
            $this->newInstance()->where('id', $data['id'])->update($data);
        } else {
            $id = $this->newInstance()->insertGetId($data);
        }
        return $id;
    }

    /**
     * 检查 名称是否唯一
     * */
    public function checkPlateNameUnique($name,$id=0){
        $where=[];
        if(!empty($id)){
            $where[]=['id', '<>', $id];
        }
        $where[]=['status', '<', 2];
        $where[]=['plate_name', '=', trim($name)];
        return $this->checkFieldUnique('plate_name',$where);
    }


    /**
     * 获取板块详情
     * @param array $params
     * */
    public function getProductPlateInfo($params=[]){
        if(empty($params)){
            return [];
        }
        $where=[];
        $where[]=['status','<',2];
        if(!empty($params['id'])){
            $where['id']=$params['id'];
        }
        $info= $this->newInstance()->where($where)->first();
        if(!empty($info)){
            return $info->toArray();
        }else{
            return [];
        }
    }

}
