<?php
/**
 * Created by PhpStorm.
 * User: dengjq
 * Date: 2019/1/24
 * Time: 14:59
 */

namespace app\common\model;


use think\Model;

abstract class Base extends Model
{
    protected $keywordColumn = "name";


    public function getList()
    {
        $where = [];
        $keyword = input("keyword");
        if (empty($keyword)) {
            $keyword = input("searchData.keyword");
        }
        if ($keyword) {
            $where[] = array($this->keywordColumn, "like", "%" . $keyword . "%");
        }
        $order_by = input("order_by", $this->getPk() . " desc");
        $page_size = input("page_size", 10);
        $list = $this->where($where)->order($order_by)->paginate($page_size);
        return returnFormat(0, '查询成功', $list);
    }

    public function add()
    {
        $param = input('param.');
        $param['update_time'] = $param['create_time'] = getNow();
        $res = self::insert($param);
        if ($res === false) {
            return returnFormat(999, '服务器错误,新增失败');
        }
        return returnFormat(0, '添加成功');
    }

    public function detail()
    {
        $id = input("id");
        if (!$id) {
            return returnFormat(999, '缺少参数');
        }
        $where['id'] = $id;
        $model = $this->where($where)->find();
        if (!$model) {
            return returnFormat(999, '未找到记录');
        }
        return returnFormat(0, '', $model->toArray());
    }

    public function del()
    {
        $id = input("id");
        $where[$this->getPk()] = $id;

        $model = $this->where($where)->find();
        if (empty($model)) {
            return returnFormat(999, '未找到记录');
        }

        $res = $model->delete();
        if ($res === false) {
            return returnFormat(999, '服务器错误');
        }
        return returnFormat(0, '删除成功');
    }

    public function edit()
    {
        $id = input("id");
        if (!$id) {
            return returnFormat(999, '缺少参数');
        }
        $where[$this->getPk()] = $id;
        $model = $this->where($where)->find();
        if (!$model) {
            return returnFormat(999, '未找到记录');
        }
        $param = input("param.");
        $param[$this->getPk()] = $id;
        $res = self::update($param);
        if ($res === false) {
            return returnFormat(999, '服务器错误');
        }
        return returnFormat(0, '修改成功');
    }

    public function appendMerge($arr)
    {
        $arr = (array)$arr;
        $this->append = array_merge($this->append, $arr);
    }


    /**
     * 构造标准输出
     * @param $code
     * @param string $msg
     * @return array
     */
    public static function standardOutput($code, $msg = "", $data = [])
    {
        $res = [
            "code" => $code,
            "msg" => $msg,
            "data" => $data
        ];
        return $res;
    }
}