<?php


namespace App\Web\Models;



use App\Models\BaseModel;


class DictFunctionModel extends BaseModel
{

    /**
     * 状态字段
     */
    const DELETED_AT = 'status';
    /**
     * @var string
     */
    protected $table = 'dict_function';

    /**
     * 获取功能列表
     * */
    public function getFunctionList($params,$fields=''){
        if (empty($fields)) {
            $fields = 'a.*';
        }
        list($pageSize, $page, $skip) = $this->getPaginatorParams($params);
        $where=[];
        if(isset($params['status'])){
            $where[]=['a.status','=',$params['status']];
        }else{
            $where[]=['a.status','<',2];
        }
        $query= $this->newInstance()->alias('a')->where($where);
        if (!empty($params['keyword'])) {
            $keyword = $params['keyword'];
            $query->where('a.name', 'like', "%" . $keyword . "%");
        }
        $totalCount = $query->count();
        $list= $query->skip($skip)
            ->limit($pageSize)
            ->selectRaw($fields)
            ->get();
        if(!empty($list)){
            $list=$list->toArray();
        }else{
            $list=[];
        }
        $result = $this->buildPaginator($list, $skip, $page, $pageSize, $totalCount);
        return $result;
    }


    /**
     * 功能保存
     * @param array $data
     * */
    public function saveFunctionData($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 checkFunctionNameUnique($name,$id=0){
        $where=[];
        if(!empty($id)){
            $where[]=['id', '<>', $id];
        }
        $where[]=['status', '<', 2];
        $where[]=['name', '=', trim($name)];
        return $this->checkFieldUnique('name',$where);
    }


    /**
     * 获取功能详情
     * @param array $params
     * */
    public function getFunctionInfo($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 [];
        }
    }

    /**
     * 获取标签基本列表
     * */
    public function getBaseFunctionList($params,$fields='a.*'){
        $where=[];
        $where['a.status']=0;
        $query= $this->newInstance()->alias('a')
            ->where($where);
        $pageSize = $this->getPageSize($params);
        $list= $query->limit($pageSize)
            ->selectRaw($fields)
            ->get();
        if(!empty($list)){
            $list=$list->toArray();
        }else{
            $list=[];
        }
        return $list;
    }

}
