<?php
namespace app\admin\logic;

use app\BaseController;
use app\admin\model\User as AdminUser;
use app\shared\model\App as PlatformUser;
use app\shared\model\Store as StoreUser;
use app\shared\model\User as SharedUser;
use app\shared\model\TeaSpecialist;
use app\admin\model\Role;
use app\shared\model\BypassAccount as SharedBypassAccount;
use app\shared\model\Role as SharedRole;
use app\shared\model\Option;
use app\admin\model\Menu;
use think\facade\Db;
use think\facade\Cache;
class Base extends BaseController
{
    public $page;
    public $limit;
    public $admin;
    public $role;
    public $acid=-1;
    public $store_id=0;
    public $user_id=0;
    public $role_name;
    public $menu_auth;
    public function __construct()
    {
        $this->initialize();
         //更新数据库
        self::updateSql();
        $access_token=request()->post('access_token');
        if(!$access_token){
            $access_token=request()->get('access_token');
        }
        if(!$access_token){
            die(json_encode(['code'=>-1,'data'=>[],'msg'=>'会话失效请重新登录']));
        }
        $token_type=get_access_token_type($access_token);
        if($token_type==-1){
            die(json_encode(['code'=>-1,'data'=>[],'msg'=>'会话失效请重新登录']));
        }

        switch ($token_type) {
            case '1'://超级管理员
                $this->admin=AdminUser::where('access_token',$access_token)->cache(10)->find();
                if(!$this->admin)die(json_encode(['code'=>-1,'data'=>[],'msg'=>'会话失效请重新登录']));
                $this->role=$this->admin->role;
                $this->role_name='超级管理员';
                break;
            case '2'://平台
                 $this->admin=PlatformUser::where('access_token',$access_token)->cache(10)->find();
                if(!$this->admin)die(json_encode(['code'=>-1,'data'=>[],'msg'=>'会话失效请重新登录']));
                $this->role=2;
                $this->acid=$this->admin->id;
                $menu_auth=Role::where('id',$this->role)->value('menu_auth');
                $this->role_name='平台';
                $this->menu_auth=json_decode($menu_auth,1);
                break;
            case '3'://商户
                $this->admin=StoreUser::where('access_token',$access_token)->cache(10)->find();
                if(!$this->admin)die(json_encode(['code'=>-1,'data'=>[],'msg'=>'会话失效请重新登录']));
                $this->role=3;
                $this->acid=$this->admin->acid;
                $this->store_id=$this->admin->id;
                $menu_auth=Role::where('id',$this->role)->value('menu_auth');
                $this->menu_auth=json_decode($menu_auth,1);
                $this->role_name='商户';
                break;
            case '4'://用户
                $this->admin=SharedUser::where('access_token',$access_token)->cache(10)->find();
                if(!$this->admin)die(json_encode(['code'=>-1,'data'=>[],'msg'=>'会话失效请重新登录']));
                $this->role=3;
                $this->acid=$this->admin->acid;
                $this->user_id=$this->admin->id;
                $this->store_id=0;
                break;
           case '5'://商户子账户
                $this->admin=SharedBypassAccount::where('access_token',$access_token)->cache(10)->find();
                if(!$this->admin)die(json_encode(['code'=>-1,'data'=>[],'msg'=>'会话失效请重新登录']));
                $this->role=5;
                $this->acid=$this->admin->acid;
                $this->store_id=$this->admin->store_id;
                $menu_auth=SharedRole::where('id',$this->admin->role_id)->value('menu_auth');
                $this->menu_auth=explode(',', $menu_auth);
                $this->role_name='商户子账号';
                break;
             case '6'://平台子账户
                $this->admin=SharedBypassAccount::where('access_token',$access_token)->cache(10)->find();
                if(!$this->admin)die(json_encode(['code'=>-1,'data'=>[],'msg'=>'会话失效请重新登录']));
                $this->role=6;
                $this->acid=$this->admin->acid;
                $menu_auth=SharedRole::where('id',$this->admin->role_id)->value('menu_auth');
                $this->menu_auth=explode(',', $menu_auth);
                $this->role_name='平台子账户';
                break;    
            case '7'://茶艺师
                $this->admin=TeaSpecialist::where('access_token',$access_token)->cache(10)->find();
                if(!$this->admin)die(json_encode(['code'=>-1,'data'=>[],'msg'=>'会话失效请重新登录']));
                $this->role=3;
                $this->acid=$this->admin->acid;
                break;             
            default:
                die(json_encode(['code'=>-1,'data'=>[],'msg'=>'会话失效请重新登录']));
                break;
        }
        $this->page=request()->post('page')?request()->post('page'):1;
        $this->limit=request()->post('limit')?request()->post('limit'):20;

        //接口权限控制
        // if($this->role!=1){
        //     $menu_auth=Role::where('id',$this->role)->cache(10)->value('menu_auth');
        //     $menu_auth=json_decode($menu_auth,1);
        //     $authlist=Menu::where('id','in',$menu_auth)->cache(10)->column('url_value');
        //     $auth=request()->root().'/'.request()->controller(true).'/'.request()->action();
        //     $auth=substr($auth,1);
        //     if(!$authlist){
        //         die(json_encode(['code'=>1,'data'=>[],'msg'=>'暂无权限']));
        //     }
        //     if(!in_array($auth,$authlist)){
        //          die(json_encode(['code'=>1,'data'=>[],'msg'=>'暂无权限']));
        //     }
        // }
        
    }
    //更新数据库
    private function updateSql(){
        if(Cache::get('system_version')){
            return false;
         }else{
             Cache::set('system_version',1,120);
         }
        $version= Option::get_data('-1','admin','system_version');
        if(!$version){
            Option::set_data('-1','admin','system_version','1.0.0');
            $version="1.0.0";
        }
        $path_version=[];
        foreach(explode('.',$version) as $version_v_index=>$version_v){
          if($version_v_index<2){
            $path_version[]=$version_v;
          }else{
            break;
          }
        }
        $path_version=implode($path_version,'.');
        $path_version=(string)$path_version;
        $path=app()->getRootPath().'sql/'.$path_version.'/';
        if(!is_dir($path)){
            return 0;
        }
        $data = scandir($path);
        $array=[];
        foreach ($data as $key => $value) {
            if(strpos($value,'.sql') !== false){
                $updSql=$path.$value;
                $val=str_replace('.sql','',$value);
                $array[]=$val;
            }
        }
        $array=sortVersion($array);
        foreach ($array as $k => $vl) {
             $version= Option::get_data('-1','admin','system_version');
             $updata=version_compare($version,$vl);
             if($updata==-1||$updata==0){
                $newversion=QyVersionsInc($vl);
                 Option::set_data('-1','admin','system_version',$newversion);
                //处理SQL
                 $sql = Sql::getSqlFromFile($path.$vl.'.sql');  
                 foreach ($sql as $v) {  
                    @Db::execute($v);
                 }
                
            }else{
                continue;
            }
        }
    
    }
   
}
class Sql
{
    /**
     * 从sql文件获取纯sql语句
     * @param  string $sql_file sql文件路径
     * @param  bool $string 如果为真，则只返回一条sql语句，默认以数组形式返回
     * @param  array $replace 替换前缀，如：['my_' => 'me_']，表示将表前缀"my_"替换成"me_"
     *         这种前缀替换方法不一定准确，比如正常内容内有跟前缀相同的字符，也会被替换
     * @return mixed
     */
   static public function getSqlFromFile($sql_file = '', $string = false, $replace = [])
    {
        if (!file_exists($sql_file)) {
            return false;
        }

        // 读取sql文件内容
        $handle = self::read_file($sql_file);

        // 分割语句
        $handle = self::parseSql($handle, $string, $replace);

        return $handle;
    }

    /**
     * 分割sql语句
     * @param  string $content sql内容
     * @param  bool $string 如果为真，则只返回一条sql语句，默认以数组形式返回
     * @param  array $replace 替换前缀，如：['my_' => 'me_']，表示将表前缀my_替换成me_
     * @return array|string 除去注释之后的sql语句数组或一条语句
     */
    public static function parseSql($content = '', $string = false, $replace = [])
    {
        // 被替换的前缀
        $from = '';
        // 要替换的前缀
        $to = '';

        // 替换表前缀
        if (!empty($replace)) {
            $to   = current($replace);
            $from = current(array_flip($replace));
        }

        if ($content != '') {
            // 纯sql内容
            $pure_sql = [];

            // 多行注释标记
            $comment = false;

            // 按行分割，兼容多个平台
            $content = str_replace(["\r\n", "\r"], "\n", $content);
            $content = explode("\n", trim($content));

            // 循环处理每一行
            foreach ($content as $key => $line) {
                // 跳过空行
                if ($line == '') {
                    continue;
                }

                // 跳过以#或者--开头的单行注释
                if (preg_match("/^(#|--)/", $line)) {
                    continue;
                }

                // 跳过以/**/包裹起来的单行注释
                if (preg_match("/^\/\*(.*?)\*\//", $line)) {
                    continue;
                }

                // 多行注释开始
                if (substr($line, 0, 2) == '/*') {
                    $comment = true;
                    continue;
                }

                // 多行注释结束
                if (substr($line, -2) == '*/') {
                    $comment = false;
                    continue;
                }

                // 多行注释没有结束，继续跳过
                if ($comment) {
                    continue;
                }

                // 替换表前缀
                if ($from != '') {
                    $line = str_replace('`'.$from, '`'.$to, $line);
                }

                // sql语句
                array_push($pure_sql, $line);
            }

            // 只返回一条语句
            if ($string) {
                return implode($pure_sql, "");
            }

            // 以数组形式返回sql语句
            $pure_sql = implode($pure_sql, "\n");
            $pure_sql = explode(";\n", $pure_sql);
            return $pure_sql;
        } else {
            return $string == true ? '' : [];
        }
    }

    /**
     * 读取文件内容
     * @param $filename  文件名
     * @return string 文件内容
     */
    public static function read_file($filename) {
        $content = '';
        if(function_exists('file_get_contents')) {
            @$content = file_get_contents($filename);
        } else {
            if(@$fp = fopen($filename, 'r')) {
                @$content = fread($fp, filesize($filename));
                @fclose($fp);
            }
        }
        return $content;
    }
}
