<?php
/**
 * Author: luzheng.liu
 * Time: 2020/10/19 22:42
 */

namespace app\index\model;


use app\common\until\Until;
use think\Model;

class BaseModel extends Model {

    private $where = [];
    private $page = 1;
    private $pageSize = 10;
    private $sort = false;
    private $sortWhere = '';

    /**
     * @param Model $objectModel
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getPageList(BaseModel $objectModel) {
        $count = $objectModel::where($this->getWhere())->count();
        if ($count) {
            $order = [];
            if ($this->isSort()) {
                $order['sort'] = 'desc';
            }
            if (empty($this->sortWhere)){
                $order['id'] =  'desc';
            }else {
                $order[$this->getSortWhere()] = 'desc';
            }


            $list = $objectModel::where($this->getWhere())->order($order)->page($this->getPage(), $this->getPageSize())->select();
            $list = Until::modelToArray($list);
        }

        return [
            'count'     => $count,
            'pageCount' => $count ? ceil($count / $this->getPageSize()) : 0,
            'page'      => $this->getPage(),
            'pageSize'  => $this->getPageSize(),
            'list'      => $count ? $list : []
        ];
    }

    /**
     * @return array
     */
    public function getWhere(): array {
        return $this->where;
    }

    /**
     * @param array $where
     */
    public function setWhere(array $where) {
        $this->where = $where;
    }

    /**
     * @return int
     */
    public function getPage(): int {
        return $this->page;
    }

    /**
     * @param int $page
     */
    public function setPage(int $page) {
        $this->page = $page;
    }

    /**
     * @return int
     */
    public function getPageSize(): int {
        return $this->pageSize;
    }

    /**
     * @param int $pageSize
     */
    public function setPageSize(int $pageSize) {
        $this->pageSize = $pageSize;
    }

    /**
     * @return bool
     */
    public function isSort(): bool {
        return $this->sort;
    }

    /**
     * @param bool $sort
     */
    public function setSort(bool $sort) {
        $this->sort = $sort;
    }

    /**
     * @return string
     */
    public function getSortWhere(): string {
        return $this->sortWhere;
    }

    /**
     * @param string $sortWhere
     */
    public function setSortWhere(string $sortWhere) {
        $this->sortWhere = $sortWhere;
    }
}