<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 小虎哥 <1105415366@qq.com>
 * Date: 2018-4-3
 */

namespace weapp\Mbackend\logic;

/**
 * 业务逻辑
 */
use think\Db;

load_trait('controller/Jump');
class MbackendLogic
{
    use \traits\controller\Jump;
    
    public function ajaxAdminWechatLogin()
    {
        // 获取微信公众号配置
        $data = get_gzh_config();
        // 获取微信配置授权登陆
        if (!empty($data['appid']) && !empty($data['appsecret'])) {
            $transferDomain = getTransferDomain();
            if (stristr($transferDomain, '/transfer.')) {
                $vars = [
                    'transferDomain' => request()->domain() . ROOT_DIR,
                    'admin_basefile' => preg_replace('/^((.*)\/)?([^\/]+)\.php$/', '${3}.php', request()->baseFile()),
                ];
                $redirect_uri = url('Admin/get_admin_wechat_users', $vars, true, $transferDomain);
            } else {
                $redirect_uri = url('Admin/get_admin_wechat_users', '', true, true);
            }
            $redirect_uri = urlencode($redirect_uri);
            $result = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $data['appid'] . "&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_userinfo&state=eyoucms&#wechat_redirect";
            return $result;
        }
    }

    public function getAdminWechatUsers()
    {
        // 获取微信公众号配置
        $data = get_gzh_config();
        // 微信配置信息
        $appid  = $data['appid'];
        $secret = $data['appsecret'];
        $code   = input('param.code/s');
        // 获取登陆者微信信息
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
        $userInfo = json_decode(httpRequest($url), true);
        if (isset($userInfo['errcode'])) {
            $this->error($userInfo['errmsg']);
        }
        // 查询系统是否存在这个管理员信息
        $where = [
            'status' => 1,
        ];
        if (!empty($userInfo['unionid'])) {
            $where['union_id'] = $userInfo['unionid'];
        } else {
            $where['wechat_open_id'] = $userInfo['openid'];
        }
        $result = Db::name('admin')->where($where)->find();
        if (empty($result)) {
            $this->error('该微信未绑定后台账号');
        }

        // 跳转链接
        // $referurl = session('m_from_url') ? session('m_from_url') : weapp_url('Mbackend/Mbackend/index');
        // $referurl = preg_replace('/^([^\?]+)(\?(.*))?$/i', '${3}', $referurl);
        // $referurl = request()->domain().request()->baseFile().'?'.$referurl;
        $referurl = weapp_url('Mbackend/Mbackend/index');
        $result['referurl'] = $referurl;

        return $result;
    }

    public function fileCacheHandle($action = 'put', $data = [])
    {
        // 获取aid
        $aid = input('param.aid/d', 0) ? input('param.aid/d', 0) : input('param.id/d', 0);
        $aid = !empty($aid) ? intval($aid) : input('param.virtual_id/d', 0);
        // 缓存文件路径
        $file = './weapp/Mbackend/fileCache/article/' . session('admin_id') . '_' . $aid . '_saveContent.txt';
        // 添加缓存文件
        if ('put' == $action && !empty($data)) {
            file_put_contents($file, json_encode($data));
        }
        // 获取缓存文件
        else if ('get' == $action) {
            $data = file_get_contents($file);
            return !empty($data) ? json_decode($data, true) : [];
        }
        // 删除缓存文件
        else if ('del' == $action) {
            @unlink($file);
        }
        // 错误提示
        else {

        }
    }

    public function login_assign(&$assign_data = [])
    {
        $referurl = input('param.referurl/s', session('m_from_url'));
        if (empty($referurl)) {
            $referurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : weapp_url('Mbackend/Mbackend/index');
            $referurl = strip_tags($referurl);
            $referurl = preg_replace('/^([^\?]+)(\?(.*))?$/i', '${3}', $referurl);
            session('m_from_url', $referurl);
        } else if (!stristr($referurl, '?')) {
            $referurl = request()->domain().request()->baseFile().'?'.$referurl;
        }

        // 是否配置微信公众号登录信息
        $assign_data['wechat'] = get_gzh_config();
        // 后台登录模式
        $mbackendRow = model('Weapp')->getWeappList('Mbackend');
        $assign_data['mbackendConf'] = $mbackendRow['data'];
    }
}
