<?php
namespace Admin\Controller;

use User\Api\UserApi;
use Com\Wechat;
use Com\WechatAuth;
use Base\Tool\TaskClient;

/**
 * 后台首页控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class PublicController extends \Think\Controller
{

    /**
     * 后台用户登录
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function login($username = null, $password = null, $verify = null)
    {
        if (IS_POST) {
            /* 检测验证码 TODO: */
            if (!check_verify($verify)) {
                $this->error('验证码输入错误!');
            }

            /* 调用UC登录接口登录 */
            $User = new UserApi;
            $uid = $User->login($username, $password);
            if (0 < $uid) { //UC登录成功
                /* 登录用户 */
                $Member = D('Member');
                if ($Member->login($uid)) { //登录用户
                    //TODO:跳转到登录前页面
                    $this->success('登录成功!', U('Index/index'));
                } else {

                    $this->error($Member->getError());
                }

            } else { //登录失败
                switch ($uid) {
                    case -1:
                        $error = '账户或密码错误!';
                        break; //系统级别禁用
                    case -2:
                        $error = '账户或密码错误!';
                        break;
                    default:
                        $error = '未知错误!';
                        break; // 0-接口参数错误(调试阶段使用)
                }
                $this->error($error);
            }
        } else {
            if (is_login()) {
                $this->redirect('Index/index');
            } else {
                /* 读取数据库中的配置 */
                $config = S('DB_CONFIG_DATA');
                if (!$config) {
                    $config = D('Config')->lists();
                    S('DB_CONFIG_DATA', $config);
                }
                C($config); //添加配置

                $this->display();
            }
        }
    }

    /**
     * 后台用户登录
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function phone_login($mobile = null, $verify = null)
    {
        if (IS_POST) {
            if (!$this->checksafecode($mobile, $verify)) {
                $this->error('验证码错误');
            }
            $member = M('ucenter_member ucenter')
                ->field("uid,nickname,ucenter.last_login_time,member.status")
                ->join("left join sys_member member on ucenter.id=member.uid")
                ->where(['mobile' => $mobile])->find();

            if(!$member || 1 != $member['status']) {
                $error = '用户不存在或已被禁用!'; //应用级别禁用
                $this->error($error);
                return false;
            }

            if ($member) {
                /* 记录登录SESSION和COOKIES */
                $Member = D('Member');
                /* 更新登录信息 */
                $data = array(
                    'uid'             => $member['uid'],
                    'login'           => array('exp', '`login`+1'),
                    'last_login_time' => NOW_TIME,
                    'last_login_ip'   => get_client_ip(1),
                );
                $Member->save($data);

                $adminData = getAdminData($member['uid']);
                $groupId = getGameGroup($member['uid']);

                /* 记录登录SESSION和COOKIES */
                $auth = array(
                    'uid'             => $member['uid'],
                    'username'        => $member['nickname'],
                    'last_login_time' => $member['last_login_time'],
                    'data_empower_type'=>$adminData['data_empower_type'],
                    'data_president'=>$adminData['data_president'],
                    'show_data'=>$adminData['show_data'],
                );
                //登录有效时间改为6小时
                $expireTime = 3600;
                ini_set('session.gc_maxlifetime', $expireTime);
                ini_set('session.cookie_lifetime', $expireTime);
                session('user_group_id',$groupId);
                session('user_auth', $auth);
                session('user_auth_sign', data_auth_sign($auth));
                session('user_auth_expire', time());
                session_regenerate_id();

            } else {
                $this->error('登录失败');
            }
//            else {
//                $partner = M('partner', 'tab_')->where(['link_phone' => $mobile,])->find();
//                if ($partner) {
//                    /* 记录登录SESSION和COOKIES */
//                    $cp_auth = array(
//                        'link_man'=>$partner['link_man'],
//                        'mobile_phone'   => $partner['link_phone'],
//                        'company_name'  => $partner['partner'],
//                        'company_type'=>"cp",
//                        'company_id'  => $partner['id'],
//                    );
//                    $session_name = 'cp_user_auth';
//                    if (I('auto_login')) {
//                        $expireTime = 60*60*24*30;//自动登录一个月
//                        ini_set('session.gc_maxlifetime', $expireTime);
//                        ini_set('session.cookie_lifetime', $expireTime);
//                        session($session_name, $cp_auth);
//                        session($session_name.'_sign', data_auth_sign($cp_auth));
//                        session($session_name.'_expire', time());
//                    } else {
//                        session($session_name, $cp_auth);
//                        session($session_name.'_sign', data_auth_sign($cp_auth));
//                    }
//
//                    $uid = $partner['id'];
//                }
//            }
            /* 登录用户 */
            $this->success('登录成功!', U('Index/index'));

        } else {
            if (is_login()) {
                $this->redirect('Index/index');
            } else {
                /* 读取数据库中的配置 */
                $config = S('DB_CONFIG_DATA');
                if (!$config) {
                    $config = D('Config')->lists();
                    S('DB_CONFIG_DATA', $config);
                }

                C($config); //添加配置

                $this->display();
            }
        }
    }

    /**
     * 后台用户登录
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function cp_login($mobile = null, $verify = null)
    {
        if (IS_POST) {
            if (!$this->checksafecode($mobile, $verify)) {
                $this->error('验证码错误');
            }
            $islogon = false;
            $promote = M('promote_company', 'tab_')->where(['contact_phone' => $mobile])->select();
            $partner = M('partner', 'tab_')->where(['link_phone' => $mobile,])->select();
            $cp_auth = [
                "mobile_phone"=>$mobile
            ];
            
            if ($promote) {
                $cp_auth['promote_company_id'] = implode(",",array_column($promote,"id"));
                $cp_auth['link_man'] = $promote[0]["settlement_contact"];
                $islogon = true;
            } 
            if ($partner) {
                $cp_auth['partner_id'] = implode(",",array_column($partner,"id"));
                if(!isset($cp_auth['link_man'])){
                    $cp_auth['link_man'] = $partner[0]["settlement_contact"];
                }

                $islogon = true;
            } 
            $session_name = 'cp_user_auth';
            if (I('auto_login')) {
                $expireTime = 60*60*24*30;//自动登录一个月
                ini_set('session.gc_maxlifetime', $expireTime);
                ini_set('session.cookie_lifetime', $expireTime);
                session($session_name, $cp_auth);
                session($session_name.'_sign', data_auth_sign($cp_auth));
                session($session_name.'_expire', time());
            } else {
                session($session_name, $cp_auth);
                session($session_name.'_sign', data_auth_sign($cp_auth));
            }

            if ($islogon) { //UC登录成功
                /* 登录用户 */
                $this->success('登录成功!', U('VerifyBill/index'));
            } else { //登录失败
                $this->error('该账号没有权限登录对账系统');
            }
        } else {
            if (session('cp_user_auth')) {
                $this->redirect('VerifyBill/index');
            } else {
                /* 读取数据库中的配置 */
                $config = S('DB_CONFIG_DATA');
                if (!$config) {
                    $config = D('Config')->lists();
                    S('DB_CONFIG_DATA', $config);
                }
                C($config); //添加配置

                $this->display();
            }
        }
    }

    public function cp_logout()
    {
        session('cp_user_auth', null);
        session('cp_user_auth_sign', null);
        $this->redirect('cp_login');
    }

    /* 退出登录 */
    public function logout()
    {
        if (is_login()) {
            D('Member')->logout();
            session('user_auth', null);
            session('user_auth_sign', null);
            session('user_auth_promote_ids', null);
            cookie('think_language', Null);
            session('[destroy]');
            // $this->success('退出成功!', U('login'));
            $this->ajaxReturn(array('status' => 1, 'msg' => '退出成功!'));
        } else {
            $this->redirect('login');
        }
    }

    public function checkVerify()
    {
        $verify = $_POST['verify'];
        if (!check_verify($verify)) {
            $this->ajaxReturn(array('status' => 0, 'msg' => '验证码输入错误!'));
        }
    }

    public function verify()
    {
        $config = array(
            'seKey' => 'ThinkPHP.CN',    //验证码加密密钥
            'fontSize' => 22,            // 验证码字体大小(px)
            'imageH' => 50,              // 验证码图片高度
            'imageW' => 180,             // 验证码图片宽度
            'length' => 4,               // 验证码位数
            'fontttf' => '4.ttf',        // 验证码字体,不设置随机获取
        );
        ob_clean();
        $verify = new \Think\Verify($config);
        $verify->codeSet = '0123456789';
        $verify->entry(1);
    }

    public function get_openid()
    {
        $appid = C('wechat.appid');
        $appsecret = C('wechat.appsecret');
        $result = auto_get_access_token(RUNTIME_PATH . '/access_token_validity.txt');
        if ($result['is_validity']) {
            session('token', $result['access_token']);
            $auth = new WechatAuth($appid, $appsecret, $result['access_token']);
        } else {
            $auth = new WechatAuth($appid, $appsecret);
            $token = $auth->getAccessToken();
            $token['expires_in_validity'] = time() + $token['expires_in'];
            wite_text(json_encode($token), RUNTIME_PATH . '/access_token_validity.txt');
            session('token', $token['access_token']);
        }
        $scene_id = sp_random_num(4) . '0';
        $ticket = $auth->qrcodeCreate($scene_id, 120);//10分钟
        if ($ticket['errcode']) {
            $return = array('status' => 0, 'data' => '获取ticket失败!');
        } else {
            $qrcode = $auth->showqrcode($ticket['ticket']);
            $return = array('status' => 1, 'data' => $qrcode, 'token' => $scene_id);
        }
        $this->ajaxReturn($return);
    }

    public function wite_token()
    {
        $appid = C('wechat.appid');
        $appsecret = C('wechat.appsecret');
        $auth = new WechatAuth($appid, $appsecret);
        $token = $auth->getAccessToken();
        $token['expires_in_validity'] = time() + $token['expires_in'];
        wite_text(json_encode($token), RUNTIME_PATH . '/access_token_validity.txt');
        session('token', $token['access_token']);
        $this->get_openid();
    }

    /** * 第三方微信扫码登陆 * */
    public function wechat_qrcode_login($state = 1)
    {
        if (empty(session("user_auth.user_id")) && !is_weixin()) {
            $appid = C('weixin_login.appid');
            $appsecret = C('weixin_login.appsecret');
            $auth = new WechatAuth($appid, $appsecret);
            $result = auto_get_access_token(RUNTIME_PATH . '/qr_access_token_validity.txt');
            if ($result['is_validity']) {
                session('token', $result['access_token']);
            } else {
                $token = $auth->getAccessToken();
                $token['expires_in_validity'] = time() + $token['expires_in'];
                wite_text(json_encode($token), RUNTIME_PATH . '/qr_access_token_validity.txt');
                session('token', $token['access_token']);
            }
            $redirect_uri = "http://" . $_SERVER['HTTP_HOST'] . "/admin.php/Public/wechat_login_callback";
            redirect($auth->getQrconnectURL($redirect_uri, $state));
        }
    }

    public function wechat_login_callback()
    {
        if ($host && $_GET['state'] != $_SERVER['HTTP_HOST']) {
            $url = 'http://' . $_GET['state'] . '/admin.php/Public/wechat_login_callback?' . http_build_query($_GET);
            Header("Location: $url");
            exit;
        }
        if (is_weixin()) {
            $appid = C('wechat.appid');
            $appsecret = C('wechat.appsecret');
        } else {
            $appid = C('weixin_login.appid');
            $appsecret = C('weixin_login.appsecret');
        }
        $auth = new WechatAuth($appid, $appsecret);
        $token = $auth->getAccessToken("code", $_GET['code']);
        if (isset($_GET['auto_get_openid'])) {
            if (base64_decode($_GET['auto_get_openid']) != 'auto_get_openid') {
                die('非法操作!');
            } else {
                session('admin_wechat_token', array('openid' => $token['openid']));
                session('admin_openid', $token['openid']);
            }
        }
        $Member = D('UcenterMember');
        $admin = $Member->where(array('admin_openid' => $token['openid']))->find();
        if ($admin == '') {
            $this->error("微信未绑定管理员账号!");
        } else {
            $User = new UserApi;
            $uid = $User->login($admin['username'], $admin['password']);
            if (0 < $uid) { //UC登录成功
                /* 登录用户 */
                $Member = D('Member');
                if ($Member->login($uid)) { //登录用户
                    //TODO:跳转到登录前页面
                    $this->success('登录成功!', U('Index/index'));
                } else {
                    $this->error($Member->getError());
                }

            } else { //登录失败
                switch ($uid) {
                    case -1:
                        $error = '用户不存在或被禁用!';
                        break; //系统级别禁用
                    case -2:
                        $error = '密码错误!';
                        break;
                    default:
                        $error = '未知错误!';
                        break; // 0-接口参数错误(调试阶段使用)
                }
                $this->error($error);
            }
        }
    }


    public function zh_cn()
    {
        cookie('think_language', 'zh-cn');
        $this->ajaxReturn(['status' => 1]);
    }


    public function en_us()
    {
        cookie('think_language', 'en-us');
        $this->ajaxReturn(['status' => 1]);
    }

    /**
     * 发动手机验证码
     */
    public function telsafecode($phone = '', $delay = 10, $flag = true)
    {
        $taskClient = new TaskClient();
        $result = $taskClient->sendSmsCode($phone, get_client_ip());
        $data = [];
        if ($result['code'] == TaskClient::SUCCESS) {
            $data['status'] = 1;
        } else {
            $data['status'] = 0;
        }
        $data['msg'] = $result['message'];
        echo json_encode($data);
        exit;
    }

    /**
     * 手机安全码验证
     */
    public function checksafecode($phone, $code)
    {
        // if($code == "txsb0601"){
        //     return true;
        // }
        $taskClient = new TaskClient();
        $result = $taskClient->checkSms($phone, $code);
        $data = [];
        if ($result && $result['code'] == TaskClient::SUCCESS) {
            return true;
        } else {
            return false;
        }
    }

}