<?php

namespace app\common\model\manystore;

use app\common\model\BaseModel;
use app\common\model\User;
use think\Model;


class UserAuth extends BaseModel
{

    

    

    // 表名
    protected $name = 'manystore_user_auth';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'status_text',
        'auth_time_text',
        'update_time_text'
    ];
    

    
    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getAuthTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['auth_time']) ? $data['auth_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setAuthTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function shop()
    {
        return $this->belongsTo('Shop', 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public static function authcheck($shop_id,$user_id){
         $usercheck = UserAuth::where("user_id",$user_id)
                ->where("shop_id",$shop_id)
                ->where("status",1)->find();
         if(!$usercheck) return false;
         return $usercheck;
    }



     /**用户授权机构
     * @param $id
     * @param int $user_id
     * @param int $status 授权状态:0=待确认,1=通过,2=拒绝
     * @param bool $check
     * @param bool $trans
     * @throws \Exception
     */
    public static function auth($id,$shop_id,$user_id,$status,$oper_type='user',$oper_id=0,$trans=false){

        $create = false;
        if($id){
         $classes_lib = self::where("id",$id)->where("status","in",[0,2])->find();
          if(!$classes_lib)throw new \Exception("找不到待授权记录！");
        }
        if($shop_id && $user_id){
            $shop_info = Shop::get($shop_id);
            if(!$shop_info)throw new \Exception("找不到店铺！");
            $classes_lib = self::where("shop_id",$shop_id)->where("user_id",$user_id)->find();
          if(!$classes_lib){
              $create = true;
          }else{
              if(!in_array($classes_lib["status"],[0,2])){
                if($status != 1){
                    throw new \Exception("用户已授权！");
                }else{
                    return $classes_lib;
                }
              }
          }
        }

        if(!$create && !$classes_lib)throw new \Exception("找不到待授权记录！缺失必要参数！");

        if($user_id){
            $user_info = User::get($user_id);
            if(!$user_info)throw new \Exception("找不到用户！");
            if($classes_lib && $classes_lib["user_id"]!=$user_id)throw new \Exception("用户与授权记录不匹配！");
        }
        if($classes_lib &&$classes_lib["status"] == $status)return $classes_lib;

        //判断逻辑
        if($trans){
            self::beginTrans();
        }

        try{


            //更新授权记录
             $data = [
                    "shop_id"=>$shop_id,
                    "user_id"=>$user_id,
                    "status"=>0,
                ];
           //没创建先创建
            if($create){
                $classes_lib = self::create($data);
                 //调用事件
                $datas = ['user_auth' => $classes_lib,"oper_type"=>$oper_type,"oper_id"=>$oper_id];
                \think\Hook::listen('user_auth_need_after', $datas);
            }

            $data["status"] = $status;

            $equa = true;
            //for循环数据变更检测
           foreach ($data as $key=>$value){
               if($value!=$classes_lib[$key]){
                   $equa = false;break;
               }
           }

           if(!$create && $equa) throw new \Exception("无变更无需更新！");

            //事务逻辑
            if($status == 1){
                $classes_lib["status"] = $status;
                $classes_lib["auth_time"] = time();
                $classes_lib->save();


             //调用事件
                $datas = ['user_auth' => $classes_lib,"oper_type"=>$oper_type,"oper_id"=>$oper_id];
                \think\Hook::listen('user_auth_success_after', $datas);

            }elseif($status == 2){
                //拒绝
                $classes_lib["status"] = $status;
                $classes_lib["auth_time"] = time();
                $classes_lib->save();

             //调用事件
                $datas = ['user_auth' => $classes_lib,"oper_type"=>$oper_type,"oper_id"=>$oper_id];
                \think\Hook::listen('user_auth_fail_after', $datas);
            }else{
//                throw new \Exception("状态错误！");
            }

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

        return $classes_lib;
    }







    public function detail($id){
        $self = $this->get($id,["shop"]);
        $self["shop"]->visible(['name',"logo","image"]);
        return $self;
    }





    /**得到基础条件
     * @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 . '.';
        $tableFields = (new static)->getTableFields();
        foreach ($tableFields as $fields)
        {
            if(in_array($fields, ['status']))continue;
//            if (isset($whereData[$fields]) && $whereData[$fields]) $model = $model->where("{$alisa}{$fields}", '=', $whereData[$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 (isset($whereData['status']) && $whereData['status']) $model = $model->where("{$alisa}status", 'in', $whereData['status']);
        if (isset($whereData['not_status']) && $whereData['not_status']) $model = $model->where("{$alisa}status", 'not in', $whereData['not_status']);

//        if (isset($whereData['keywords'])&&$whereData['keywords']) $model = $model->where("{$alisa}name|{$alisa}id", '=', $whereData['keywords']);
        if (isset($whereData['time'])&&$whereData['time']){
            $model = $model->time(['auth_time',$whereData['time']]);
        }
        if (isset($whereData['user_id']) && $whereData['user_id']) $model = $model->where("{$alisa}user_id", '=', $whereData['user_id']);

        if (isset($whereData['shop_id']) && $whereData['shop_id']) $model = $model->where("{$alisa}shop_id", 'in', $whereData['shop_id']);

        if (isset($whereData['keywords'])&&$whereData['keywords']){

            if($with){
                $model = $model->where( function($query) use($whereData,$alisa,$with){
                    $query = $query->where("{$alisa}url|{$alisa}title|{$alisa}content|{$alisa}ip", 'like', "%". $whereData['keywords']."%");
                    if(in_array('user',$with)){
                        $query = $query->whereOr("user.nickname|user.realname|user.mobile", 'like', "%". $whereData['keywords']."%");
                    }
                    if(in_array('shop',$with)){
                        $query = $query->whereOr("shop.name|shop.address|shop.address_detail|shop.tel", 'like', "%". $whereData['keywords']."%");
                    }
                });
            }else{
                $model = $model->where("{$alisa}shop_id|{$alisa}user_id", 'like', "%". $whereData['keywords']."%");
            }

        }

        return $model;
    }






    public static function allList($page, $limit,$params=[]){
        $with_field = [
            'user'=>['nickname','mobile','avatar','realname'],
            'shop'=>['name','logo','image','images'],
            'base'=>['*'],
        ];
        $alisa = (new self)->getWithAlisaName();
        $sort = "{$alisa}.status asc,{$alisa}.id desc";
//        if(!empty($params['status'])){
//            $params['status'] = '1';
//        }
        return (new self)->getBaseList($params, $page, $limit,$sort,$with_field);
    }



}
