<?php

namespace app\api\model;

use think\Db;
use think\Model;
use think\Validate;

class BaseModel extends Model
{
    protected $error = 0;

    protected $name;

    protected $pk;

    protected $rule = [];

    protected $msg = [];

    protected $Validate;

    public function __construct($data = [])
    {
        parent::__construct($data);

        $this->Validate = new Validate($this->rule, $this->msg);
        $this->Validate->extend('no_html_parse', function ($value, $rule) {
            return true;
        });
    }

    /**
     * 获取空模型
     */
    public function getEModel($tables)
    {
        $rs = Db::query('show columns FROM `' . config('database.prefix') . $tables . "`");
        $obj = [];
        if ($rs) {
            foreach ($rs as $key => $v) {
                $obj[ $v['Field'] ] = $v['Default'];
                if ($v['Key'] == 'PRI')
                    $obj[ $v['Field'] ] = 0;
            }
        }
        return $obj;
    }



    public  function save($data = [], $where = [], $sequence = null)
    {
        $data = $this->htmlClear($data);
        $retval = parent::save($data, $where, $sequence);
        if (!empty($where)) {
            //表示更新数据
            if ($retval == 0) {
                if ($retval !== false) {
                    $retval = 1;
                }
            }
        }
//         $retval = ['code' => $code, 'message' => $this->getError()];
        return $retval;
    }

    public function ihtmlspecialchars($string)
    {
        if (is_array($string)) {
            foreach ($string as $key => $val) {
                $string[ $key ] = $this->ihtmlspecialchars($val);
            }
        } else {
            $string = preg_replace('/&amp;((#(d{3,5}|x[a-fa-f0-9]{4})|[a-za-z][a-z0-9]{2,5});)/', '&\1',
                str_replace(array( '&', '"', '<', '>' ), array( '&amp;', '&quot;', '&lt;', '&gt;' ), $string));
        }
        return $string;
    }

    protected function htmlClear($data)
    {
        $rule = $this->rule;
        $info = empty($rule) ? $this->Validate : $rule;
        foreach ($data as $k => $v) {
            if (!empty($info)) {
                if (is_array($info)) {
                    $is_Specialchars = $this->is_Specialchars($info, $k);
                    // 数据对象赋值
                    if ($is_Specialchars) {
                        $data[ $k ] = $this->ihtmlspecialchars($v);
                    } else {
                        $data[ $k ] = $v;
                    }

                }
            }
        }
        return $data;
    }

    /**
     * 判断当前k 是否在数组的k值中
     * @param array $rule
     * @param string $k
     */
    protected function is_Specialchars($rule, $k)
    {
        $is_have = true;
        foreach ($rule as $key => $value) {
            if ($key == $k) {
                if (strcasecmp($value, "no_html_parse") != 0) {
                    $is_have = true;
                } else {
                    $is_have = false;
                }
            }
        }
        return $is_have;
    }

    /**
     * 数据库开启事务
     */
    public function startTrans()
    {
        Db::startTrans();
    }

    /**
     * 数据库事务提交
     */
    public function commit()
    {
        Db::commit();
    }

    /**
     * 数据库事务回滚
     */
    public function rollback()
    {
        Db::rollback();
    }


    /**
     * 获取关联查询数量
     *
     * @param object $viewObj 视图对象
     * @param array $condition 条件
     * @return int
     */
    public function viewCount($viewObj, $condition)
    {
        $count = $viewObj->where($condition)->limit(0, 1000000)->count();
        return $count;
    }



    /**
     * 获取单条记录的基本信息
     */
    public function getInfo($condition = '', $field = '*')
    {
        $info = Db::name($this->name)->where($condition)
            ->field($field)
            ->find();
        return $info;
    }

    /**
     * 查询数据的数量
     */
    public function getCount($condition)
    {
        $count = Db::name($this->name)->where($condition)
            ->count();
        return $count;
    }

    /**
     * 查询条件数量
     * @param array $condition
     * @param string $field
     */
    public function getSum($condition, $field)
    {
        $sum = Db::name($this->name)->where($condition)
            ->sum($field);
        if (empty($sum)) {
            return 0;
        } else
            return $sum;
    }

    /**
     * 查询数据最大值
     * @param array $condition
     * @param string $field
     * @return number
     */
    public function getMax($condition, $field)
    {
        $max = Db::name($this->name)->where($condition)
            ->max($field);
        if (empty($max)) {
            return 0;
        } else
            return $max;
    }

    /**
     * 查询数据最小值
     * @param array $condition
     * @param string $field
     * @return number
     */
    public function getMin($condition, $field)
    {
        $min = Db::name($this->name)->where($condition)
            ->min($field);
        if (empty($min)) {
            return 0;
        } else
            return $min;
    }

    /**
     * 查询数据均值
     * @param array $condition
     * @param int
     */
    public function getAvg($condition, $field)
    {
        $avg = Db::name($this->name)->where($condition)
            ->avg($field);
        if (empty($avg)) {
            return 0;
        } else
            return $avg;
    }

    /**
     * 查询第一条数据
     * @param array $condition
     */
    public function getFirstData($condition, $order)
    {
        $data = Db::name($this->name)->where($condition)->order($order)
            ->limit(1)->select();
        if (!empty($data)) {
            return $data[0];
        } else
            return '';
    }

    /**
     * 修改表单个字段值
     * @param int $pk_id
     * @param string $field_name
     * @param string $field_value
     */
    public function ModifyTableField($pk_name, $pk_id, $field_name, $field_value)
    {
        $data = array(
            $field_name => $field_value
        );
        $res = $this->save($data, [ $pk_name => $pk_id ]);
        return $res;
    }

    /**
     * 获取某个字段值
     * @param array $condition
     * @param string $name
     * @param string $order
     */
    public function getColumn($condition, $name, $order = '')
    {
        $data = Db::name($this->name)->where($condition)->order($order)
            ->column($name);
        return $data;
    }

    /**
     * @param $id
     * @param $col
     * @param int $num
     * @return int
     */
    public function updateCount($id,$col,$num = 1){
        $id = (int)$id;
        if($num>0){
            return Db::name($this->name)->where($this->pk,"=",$id)->setInc($col,$num);
        }else{
            return Db::name($this->name)->where($this->pk, "=",$id)->setDec($col,abs($num));
        }
    }
}