<?php

namespace app\common\model;

use think\Model;

/**
 * 基础扩展模型
 */
class BaseModel extends Model
{


    use \traits\ModelTrait;
//    use \traits\ErrorTrait;

    public $timeKey = 'createtime';
    public static $staticTimeKey = 'createtime';

        //允许修改的字段
    public $no_auth_fields = [];

    //更新数据是否需要触发审核开关

    public $have_auth = false;
        //更新数据是否需要触发审核开关
    public $need_auth = false;


    public $success_auth = false;
    public $error_auth = false;



    /**
     * 是否开启Validate验证
     */
    protected $modelValidate = false;

    /**
     * 是否开启模型场景验证
     */
    protected $modelSceneValidate = false;



    /**
     * 是否开启数据限制
     * 支持auth/personal
     * 表示按权限判断/仅限个人
     * 默认为禁用,若启用请务必保证表中存在admin_id字段
     */
    protected $dataLimit = false;


    /**
     * 数据限制字段
     */
    protected $dataLimitField = 'admin_id';

    /**
     * 数据限制开启时自动填充限制字段值
     */
    protected $dataLimitFieldAutoFill = true;





    /**
     * 获取数据限制的管理员ID(后台api版本)
     * 禁用数据限制时返回的是null
     * @return mixed
     */
    protected function getDataLimitAdminIds()
    {
        if (!$this->dataLimit) {
            return null;
        }
        $auth = \app\adminapi\library\Auth::instance();
        if ($auth->isSuperAdmin()) {
            return null;
        }
        $adminIds = [];
        if (in_array($this->dataLimit, ['auth', 'personal'])) {
            $adminIds = $this->dataLimit == 'auth' ? $auth->getChildrenAdminIds(true) : [$auth->id];
        }
        return $adminIds;
    }


     public function checkAssemblyParameters($get=[],$exclude = []){
        //得到所有get参数
        $get = $get ?: request()->get();
        //得到当前model所有字段


        $fields = $this->getTableFields();

//        $commonFields = (new Field())->getCommonFields();
//        var_dump($commonFields);
        $fieldLists = $fields;
//        foreach ($commonFields as $commonField) {
//            if (!in_array($commonField['column_name'], $fields)) {
//                $fieldLists[] = $commonField;
//            }
//        }
        $q_fields = [];

        foreach ($get as $kay=>$getField) {
            if (in_array($kay, $fieldLists) && !in_array($kay, $exclude)) {
                $q_fields[$kay] = $getField;
            }
        }

        return $q_fields;

        //将q_fields塞入模板中
//        foreach ($q_fields as $k=>$v) {
//            //渲染站点配置
//            $this->assign('q_'.$k, $v);
//        }

//        foreach ($this->qFields as $k) {
//            //渲染站点配置
//            if(!isset($q_fields[$k]))$this->assign('q_'.$k, "");
//        }


    }




    public function no_auth_fields_check($params,$row){

         $this->have_auth = false;
         if($this->no_auth_fields == "*")return $this->have_auth;
//         $this->getTableFields();
        $params = $this->checkAssemblyParameters($params);
        foreach ($params as $k=>$v){

            //说明数值有变动
            //$params[$k] 去掉两端空格
            $params[$k] = trim($v);

            if($row[$k]!=$params[$k]){
                //当修改参数不在允许修改的字段中
                if(!in_array($k,$this->no_auth_fields)){
//                     var_dump($k,$row[$k],$params[$k]);
                    $this->have_auth = true;break;

                }
            }

        }

        return $this->have_auth;

    }


    /**得到基础条件
     * @param $status
     * @param null $model
     * @param string $alisa
     */
    public static function getBaseWhere($whereData = [], $model = null, $alisa = '',$with = false)
    {
        if (!$model) {
            $model = new static;
            if ($alisa&&!$with) $model = $model->alias($alisa);
        }
        if ($alisa) $alisa = $alisa . '.';
        //$model = $model->where($alisa . 'status', '1');
        $tableFields = (new static)->getTableFields();
        foreach ($tableFields as $fields)
        {
            if (isset($whereData[$fields]) && $whereData[$fields]){
                if(is_array($whereData[$fields])){
                    $model = $model->where("{$alisa}{$fields}", $whereData[$fields][0], $whereData[$fields][1]);
                }else{
                    $model = $model->where("{$alisa}{$fields}", '=', $whereData[$fields]);
                }

            }
        }
        //关联查询条件
        if($with && is_array($with)){
            foreach ($whereData as $param => $value)
            {
              //如果存在.则按.分割取到表别名
              //如果表别名属于$with中的表别名，则塞入查询条件里
                if(strpos($param,'.')!==false){
                    $param_alisa = explode('.',$param)[0];
                    if(in_array($param_alisa,$with)){
                        if(is_array($value)){
                            $model = $model->where($param, $value[0], $value[1]);
                        }else{
                            $model = $model->where($param, $value);
                        }
                    }
                }
            }
        }
        return self::getDivWhere($whereData, $model, $alisa,$with);
    }
    public static function getDivWhere($whereData = [], $model = null, $alisa = '',$with = false)
    {
        return $model;
    }



    /**
     * 基础列表
     */
    public function getBaseList($whereData = [], $page = 0, $limit = 0, $sort = '',$field =[],$where=[],$toArray = true)
    {
        $alisa = $this->getWithAlisaName();
        if($field){
            //如果是一维数组
            if(is_array($field)&&count($field) == count($field,1)) $field = ['base'=>$field];
            //如果是字符串
            if(is_string($field)) $field = ['base'=>explode(',',$field)];
        }
        $this->withTable = array_keys($field);
        $base_i = array_search("base",$this->withTable);
        if($base_i!==false)unset($this->withTable[$base_i]);
        if(!$this->withTable)$alisa = '';
        $alisa_name = '';
        if($alisa)$alisa_name = "{$alisa}.";
        if(!$sort)$sort = "{$alisa_name}id desc";
        $self = static::getBaseWhere($whereData, null, $alisa,$this->withTable);
        if($this->withTable)$self = $self->with($this->withTable);
        if($page&&$limit)$self = $self->where($where)->page($page, $limit);
        $list = $self->orderRaw($sort)->select();
        foreach ($list as $row) {

            if(isset($field['base'])&&$field['base']!=['*']){
                $row->visible($field['base']);
            }else{
                $getTableFields = $this->getTableFields();
                if(!empty($this->hidden) && is_array($this->hidden)){
                    $getTableFields = array_diff($getTableFields,$this->hidden);
                }
                $row->visible($getTableFields);
            }
            foreach ($this->withTable as $withName) {
                if(isset($field[$withName])&&$field[$withName]!=['*']){
                    $row->visible([$withName]);
                    $row->getRelation($withName)->visible($field[$withName]);
                }elseif(isset($field[$withName])&&$field[$withName]==['*']){
                    $row->visible([$withName]);
                }
            }
        }
        if($toArray)$list = collection($list)->toArray();
        $countSelf = static::getBaseWhere($whereData, null, $alisa,$this->withTable);
        if($this->withTable)$countSelf = $countSelf->with($this->withTable);
        $count = $countSelf->where($where)->count();
        return compact('list', 'count','page','limit');
    }



    /**
     * 时间段搜索器
     * @param Model $query
     * @param $value
     */
    public function scopeTime($query, $value)
    {
        $timeKey = $this->timeKey;
        if(static::$staticTimeKey)$timeKey =static::$staticTimeKey;

        if(is_array($value)){
            $timeKey = $value[0];
            $value = $value[1];
        }


        switch ($value) {
            case 'today':
            case 'week':
            case 'month':
            case 'year':
            case 'yesterday':
            case 'last year':
            case 'last week':
            case 'last month':
                $query->whereTime($timeKey, $value);
                break;
            case 'quarter':
                list($startTime, $endTime) = static::getMonth();
                $query->whereTime($timeKey, 'between', [$startTime, $endTime]);
                break;
            case 'lately7':
                $query->whereTime($timeKey, 'between', [strtotime("-7 day"), time()]);
                break;
            case 'lately30':
                $query->whereTime($timeKey, 'between', [strtotime("-30 day"), time()]);
                break;
            default:
                if (strstr($value, '---') !== false||strstr($value, '-') !== false) {
                    if(strstr($value, '---') !== false){
                        [$startTime, $endTime] = explode('---', $value);
                    }elseif (strstr($value, '-') !== false){
                        [$startTime, $endTime] = explode('-', $value);
                    }
                    $startTime = trim($startTime);
                    $endTime = trim($endTime);
                    if ($startTime && $endTime) {
                        $query->whereTime($timeKey, 'between', [strtotime($startTime), $startTime == $endTime ? strtotime($endTime) + 86400 : strtotime($endTime)]);
                    } else if (!$startTime && $endTime) {
                        $query->whereTime($timeKey, '<', strtotime($endTime) + 86400);
                    } else if ($startTime && !$endTime) {
                        $query->whereTime($timeKey, '>=', strtotime($startTime));
                    }
                }
                break;
        }
    }


    public function demo($id,$trans=false){
//判断逻辑
        if($trans){
            self::beginTrans();
        }
        $res = true;
        try{

            if($trans){
                self::commitTrans();
            }
        }catch (\Exception $e){
            if($trans){
                self::rollbackTrans();
            }
            throw new \Exception($e->getMessage().$e->getFile().$e->getLine());
        }
        return $res;
    }


//    /** 通用新增(后台api版本)
//     * @param $params
//     * @param $trans
//     * @return $this
//     * @throws \Exception
//     */
//    public function add($params,$trans=false){
//
//        if (empty($params)) {
//            throw new \Exception(__('Parameter %s can not be empty', ''));
//        }
//
//        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
//            $params[$this->dataLimitField] = $this->auth->id;
//        }
////判断逻辑
//        if($trans){
//            self::beginTrans();
//        }
//        $res = true;
//        try{
//
//            //是否采用模型验证
//            if ($this->modelValidate) {
//                $name = str_replace("\\model\\", "\\validate\\", get_class($this));
//                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
//                $this->validateFailException()->validate($validate);
//            }
//
//            $result = $this->allowField(true)->save($params);
//
//            if($trans){
//                self::commitTrans();
//            }
//        }catch (\Exception $e){
//            if($trans){
//                self::rollbackTrans();
//            }
//            throw new \Exception($e->getMessage().$e->getFile().$e->getLine());
//        }
//        return $this;
//    }
//
//
//    /** 通用编辑(后台api版本)
//     * @param $params
//     * @param $trans
//     * @return $this
//     * @throws \Exception
//     */
//    public function edit($id,$params,$trans=false){
//
//        $row = $this->get($id);
//        if (!$row) {
//            throw new \Exception(__('No Results were found'));
//        }
//
//        $adminIds = $this->getDataLimitAdminIds();
//        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
//            throw new \Exception(__('You have no permission'));
//        }
//
//        if (empty($params)) {
//            throw new \Exception(__('Parameter %s can not be empty', ''));
//        }
////判断逻辑
//        if($trans){
//            self::beginTrans();
//        }
//        $res = true;
//        try{
//
//            //是否采用模型验证
//            if ($this->modelValidate) {
//                $name = str_replace("\\model\\", "\\validate\\", get_class($this));
//                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
//                $row->validateFailException()->validate($validate);
//            }
//            $result = $row->allowField(true)->save($params);
//
//            if($trans){
//                self::commitTrans();
//            }
//        }catch (\Exception $e){
//            if($trans){
//                self::rollbackTrans();
//            }
//            throw new \Exception($e->getMessage().$e->getFile().$e->getLine());
//        }
//        return $row;
//    }
//
//
//    /** 通用详情(后台api版本)
//     * @param $params
//     * @param $trans
//     * @return $this
//     * @throws \Exception
//     */
//    public function detail($id,$show_field=[],$except_field=[]){
//        $row = $this->get($id);
//        if (!$row) {
//            throw new \Exception(__('No Results were found'));
//        }
//        if($show_field){
//            $row->visible($show_field);
//        }
//        if($except_field){
//            $row->hidden($except_field);
//        }
//        return $row;
//    }
//
////    public function index($page,$limit,$where=[])
////    {
////        $adminIds = $this->getDataLimitAdminIds();
////        $aliasName = "" ;
////        if (is_array($adminIds)) {
////            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
////        }
////
////    }
//
//
//    /** 通用删除(后台api版本)
//     * @param $params
//     * @param $trans
//     * @return $this
//     * @throws \Exception
//     */
//    public function del($ids = null,$trans=false){
//        if (empty($ids)) {
//            throw new \Exception(__('Parameter %s can not be empty', 'ids'));
//        }
////判断逻辑
//
//        $pk = $this->getPk();
//        $adminIds = $this->getDataLimitAdminIds();
//        if (is_array($adminIds)) {
//            $this->where($this->dataLimitField, 'in', $adminIds);
//        }
//        $list = $this->where($pk, 'in', $ids)->select();
//        $count = 0;
//        if($trans){
//            self::beginTrans();
//        }
//        $res = true;
//        try{
//
//            foreach ($list as $item) {
//                $count += $item->delete();
//            }
//
//            if($trans){
//                self::commitTrans();
//            }
//        }catch (\Exception $e){
//            if($trans){
//                self::rollbackTrans();
//            }
//            throw new \Exception($e->getMessage().$e->getFile().$e->getLine());
//        }
//        return $count;
//    }



}
