<?php
/*
 * description：
 * author：wh
 * email：
 * createTime：{2022/5/4} {9:12} 
 */

namespace app\index\controller;



use app\apidata\Config;
use app\common\consts\LogDir;
use app\common\model\TabConf;
use app\index\model\WechatUserModel;
use think\Controller;
use think\Db;
use think\Request;
use wanghua\general_utility_tools_php\framework\base\OuterController;
use wanghua\general_utility_tools_php\tool\Tools;

class BaseAuthController extends BaseCommonController
{

    public function __construct(Request $request = null)
    {
        parent::__construct($request);


        //首页提示语
        $this->assign('index_msg',cache('index_msg_alert_cache_time'));

        //线上环境加载微信授权
        if(config('sys_env') == 'PROD'){
            $wx_user_info = session('wx_user_info');
            if(empty($wx_user_info['openid'])) {
                //重定向之前，保存当前url, 在获取授权信息之后，回跳到授权之前的网页地址
                session('redirect_before_url_session',request()->url(true));
                //没有则重定向去授权
                return $this->redirect(url('Wexinauth/usrAuth','',301,true));
            }

            $this->saveWechatUser($wx_user_info);
        }


        //校验系统维护状态 start
        $chm = $this->checkMaintain();
        if($chm['is_maintain']){
            if($chm['openid']){
                //解析openid
                if(!in_array(index_user_openid(), explode(',',$chm['openid']))){
                    //白名单之外维护中
                    //Tools::log_to_write_txt([
                    //    '维护测试'=>$chm['openid'],
                    //    'my'=>index_user_openid()
                    //]);
                    return $this->error($chm['msg']);
                }
            }else{
                //不存在，直接维护中
                return $this->error($chm['msg'].'！');
            }
        }
        //校验系统维护状态 end


    }




    /**
     * desc：
     * author：wh
     * @param $wx_user_info
     */
    private function saveWechatUser($wx_user_info){
        try {
            $wechat_user = WechatUserModel::getWxUserByOpenid($wx_user_info['openid']);
            if(empty($wechat_user)){
               return WechatUserModel::insertInfo($wx_user_info);
            }
            //扩展，按周期更新,而不是不更新
            if(empty($wechat_user['update_time']) || time()-strtotime($wechat_user['update_time'])>5*3600){

                return WechatUserModel::updateUser($wx_user_info);
            }


        }catch (\Exception $e){
            Tools::log_to_write_txt([
                'error'=>'存储异常.'.$e->getMessage(),
                'wx_user_info'=>$wx_user_info,
                'error_info'=>$e->getTraceAsString()
            ],LogDir::WECHAT_USER_INFO_LOG);
        }
    }
}