<?php

namespace Home\Controller;

use Think\Controller;
use Base\Service\PromoteService;

class BaseController extends HomeController
{
    protected $promotePermissions;
    protected $loginPromote = null;
    protected $canViewUserRecharge = true;

    protected $permControlUrls = [
        'Home/Query/recharge',
        'Home/Players/playAction',
        'Home/Query/userRecharges',
        'Home/Query/arpu',
        'Home/Finance/index',
        'Home/Finance/settlementDtl',
        'Home/Finance/withdrawRecord',
    ];

    protected function _initialize()
    {
        parent::_initialize();

        $this->login();

        $loginer = $this->getLoginPromote();
        // $this->certifiCation();
        $pid = is_login_promote();
        define('PLEVEL', $loginer['parent_id']);
        define('PID', $pid);
        define('PROMOTE_ACCOUNT', session('promote_auth.account'));

        if ($loginer['grand_id'] > 0) {/* 三级 */
            define('PRO_GRADE', 3);
        } elseif ($loginer['parent_id'] > 0) {/* 二级 */
            define('PRO_GRADE', 2);
            define('SETTLEMENT_GRADE', 'third_status'); /* 给三级结算 */
            define('G_SETTLEMENT_GRADE', 'third_status');
        } else {/* 一级 */
            define('PRO_GRADE', 1);
            define('SETTLEMENT_GRADE', 'sub_status'); /* 给二级结算 */
            define('G_SETTLEMENT_GRADE', 'sub_status,third_status');
        }

        if ($loginer['company_id']) {
            $company = M('promote_company', 'tab_')->where(['id'=>$loginer['company_id']])->find();
            $this->assign('company', $company);
        }

        $this->canViewUserRecharge = $this->promoteCan('view-user-recharge');
        $this->checkUrlPermission();

        $this->assign('loginer', $loginer);
        $this->assign("parent_id", $loginer['parent_id']);
        $this->assign("grand_id", $loginer['grand_id']);
        $this->assign('canViewUserRecharge', $this->canViewUserRecharge);

        $result = M('site_apply', 'tab_')->where("promote_id=$pid")->getField('status');
        if ($result['status'] == 1) {
            $this->assign('noapplysite', $result);
        }
        if (in_array(CONTROLLER_NAME, array('SiteBase', 'SiteGame', 'SiteGift', 'SiteGroup', 'SiteServer', 'SiteAdv'))) {
            if ($result != 1) {
                $this->redirect('SiteApply/index', array('msg' => 1));
            }
        }
    }


    /* 用户登录检测 */
    protected function login()
    {
        /* 用户登录检测 */
        is_login_promote() || $this->error('您还没有登录,请先登录!', U('Index/index'));
    }


    /**
     * 显示指定模型列表数据
     * @param String $model 模型标识
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function lists($model = null, $p = 0, $extend_map = array(), \Closure $appendCallback = null)
    {
        $model || $this->error('模型名标识必须!');
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据

        //获取模型信息
        $model = M('Model')->getByName($model);
        $model || $this->error('模型不存在!');

        //解析列表规则
        $fields = array();
        // 关键字搜索
        $map = $extend_map;
        $key = $model['search_key'] ? $model['search_key'] : 'title';
        if (isset($_REQUEST[$key])) {
            $map[$key] = array('like', '%' . $_GET[$key] . '%');
            unset($_REQUEST[$key]);
        }
        // 条件搜索
        foreach ($_REQUEST as $name => $val) {
            if (in_array($name, $fields)) {
                $map[$name] = $val;
            }
        }


        if (isset($_REQUEST['row'])) {
            $row = $_REQUEST['row'];
        } else {
            $row = 10;
        }

        $name = parse_name(get_table_name($model['id']), true);
        $data = M($name, "tab_")
            /* 查询指定字段,不指定则查询所有字段 */
            ->field(empty($fields) ? true : $fields)
            // 查询条件
            ->where($map)
            /* 默认通过id逆序排列 */
            ->order($model['need_pk'] ? 'id DESC' : '')
            /* 数据分页 */
            ->page($page, $row)
            /* 执行查询 */
            ->select();
        /* 查询记录总数 */
        $count = M($name, "tab_")->where($map)->count();

        //分页
        $parameter = $_POST;
        $parameter['p'] = I('get.p', 1);
        $parameter['row'] = I('get.row');

        $page = set_pagination($count, $row, $parameter);
        if ($page) {
            $this->assign('_page', $page);
        }

        $hasList = false;
        if ($appendCallback) {
            $appends = $appendCallback($data);
            foreach ($appends as $key => $value) {
                if ($key == 'list_data') {
                    $hasList = true;
                }
                $this->assign($key, $value);
            }
        }

        $this->assign("count", $count);
        $this->assign('model', $model);
        $this->assign('list_grids', $grids);
        if ($hasList == false) {
            $this->assign('list_data', $data);
        }
        $this->meta_title = $model['title'] . '列表';
        $this->display($model['template_list']);
    }

    public function data_lists($p, $model, $extend = [])
    {
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据

        if (isset($_REQUEST['row'])) {
            $row = $_REQUEST['row'];
        } else {
            $row = 10;
        }

        $model = D($model);
        // 条件搜索
        $map = [];
        foreach (I('get.') as $name => $val) {
            $map[$name] = $val;
        }
        $map = array_merge($map, $extend['map']);
        $lists_data = $model->where($map)->page($page, $row)->order($extend['order'])->select();
        $count = $model->where($map)->count();
        //分页

        $parameter = $_POST;
        $parameter['p'] = I('get.p', 1);
        $parameter['row'] = I('get.row');

        $page = set_pagination($count, $row, $parameter);
        if ($page) {
            $this->assign('_page', $page);
        }

        $this->assign('lists_data', $lists_data);
        $this->assign('count', $count);
        $this->display();
    }

    /**
     * @author ELF<360197197@qq.com>
     * 分页方法(请勿擅自修改)
     */
    public function paginate($query, $defaultPageSize = 10, $defaultPage = 1)
    {
        $page = I('get.p', $defaultPage);
        $pageSize = I('get.row', $defaultPageSize);

        $countQuery = clone $query;
        $count = $countQuery->count();
        $records = $query->page($page, $pageSize)->select();

        $params = [
            'p' => $page,
            'row' => $pageSize
        ];
        $params = array_merge($params, $_POST);
        $params = array_merge($params, $_GET);
        $pagination = set_pagination($count, $pageSize, $params);

        return [$records, $pagination, $count];
    }

    public function getRecordsByIds($query, $ids, $params = [])
    {
        if (count($ids) == 0) {
            return [];
        }
        $field = isset($params['field']) ? $params['field'] : 'id';
        $indexBy = isset($params['indexBy']) ? $params['indexBy'] : '';

        $items = $query->where([$field => ['in', $ids]])->select();
        $records = [];
        if ($indexBy) {
            foreach ($items as $item) {
                $records[$item[$field]] = $item;
            }
            return $records;
        }
        return $items;
    }

    public function getColumnsByIds($query, $ids, $column, $params = [])
    {
        if (count($ids) == 0) {
            return [];
        }
        $field = isset($params['field']) ? $params['field'] : 'id';
        $indexBy = isset($params['indexBy']) ? $params['indexBy'] : '';

        $items = $query->where([$field => ['in', $ids]])->select();
        $records = [];
        if ($indexBy) {
            foreach ($items as $item) {
                $records[$item[$field]] = $item[$column];
            }
        } else {
            foreach ($items as $item) {
                $records[] = $item[$column];
            }
        }
        return $records;
    }

    public function getLoginPromote()
    {
        if ($this->loginPromote == null) {
            $promoteId = session('promote_auth.pid');
            $this->loginPromote = M('promote', 'tab_')->where(['id' => $promoteId])->find();
        }
        return $this->loginPromote;
    }

    //验证安全密码--视图
    public function verifyPasswordView($modelList, $show = true)
    {
        $securityCode = empty(session('game_divide_second_pwd')) ? '' : session('game_divide_second_pwd');//安全密码
        $model = new \User\Api\PromoteApi();
        $res = $model->verify_er_User(PID, $securityCode);//验证安全密码
        if ($res) {
            return true;
        }
        if ($show) {
            $this->assign('modelList', $modelList);
            $this->assign('meta_title', '安全密码');
            $this->display('Public/verify_password');
            exit;
        }

        return false;
    }

    //验证安全密码
    public function verifyPassword()
    {
        $password = I('post.password');
        $model = new \User\Api\PromoteApi();
        $res = $model->verify_er_User(PID, $password);
        if ($res) {
            session('game_divide_second_pwd', $password);

            $data['status'] = 1;
            $data['msg'] = '验证成功';
        } else {
            $data['status'] = 0;
            $data['msg'] = '安全密码不正确';
        }

        $this->ajaxReturn($data);
    }

     //判断是否认证资质
     public function certifiCation() {
        $pid = get_pid();
        $verInfo = M('promote','tab_')->field('ver_status,level,second_pwd')->where(['id' => $pid])->find();
        $ver_status = intval($verInfo['ver_status']);
        $level = intval($verInfo['level']);
        $second_pwd = $verInfo['second_pwd'];
        $module_name = MODULE_NAME;
        $controller_name = CONTROLLER_NAME;
        $action_name = ACTION_NAME;
        $rule_name = $module_name.'/'.$controller_name.'/'.$action_name;
        if($level == 1) {
            switch ($ver_status) {
                case 0:
                    $this->verConAction($rule_name,$second_pwd,'请进行资质认证,认证成功后才可进行操作');
                    break;
                case 2:
                    $this->verConAction($rule_name,$second_pwd,'资质审核失败,请重新验证认证资料');
                    break;    
                case 3:
                    $this->verConAction($rule_name,$second_pwd,'资质验证未审核,请联系管理员');
                    break;
                default:
                    break;
            }
        }
        
    }
    
    //判断控制器方法
    public function verConAction($rule_name,$second_pwd,$status='') {
        switch ($rule_name) {
            case 'Home/Safe/modifyBaseInfo':
                break;
            case 'Home/Safe/setSafePassword':
                break;
            case 'Home/Safe/verifySafePwd':
                break; 
            case 'Home/Promote/index':
                break;
            case 'Home/Safe/verifyPassword':
                break;  
            case 'Home/Safe/safeDocument':
                break;
            case 'Home/Promote/popRuleDetail':         
                break;   
            case 'Home/Promote/popRuleFinish':
                break;               
            default:
                $this->tips($status,U('Safe/modifyBaseInfo'));
                break;
        }
    }

    public function checkUrlPermission()
    {
        $currentUrl = MODULE_NAME . '/' . CONTROLLER_NAME . '/' . ACTION_NAME;
        if (!$this->canViewUserRecharge) {
            foreach ($this->permControlUrls as $url) {
                if (strtolower($currentUrl) == strtolower($url)) {
                    $this->error('无权限查看');
                }
            }
        }
    }

    public function promoteCan($permission)
    {
        $promote = $this->getLoginPromote();
        if (!$promote) {
            return false;
        }
        if ($permission == 'recharge') {
            if ($promote['level'] == 1) {
                return true;
            }
        }
        if ($permission == 'view-user-recharge') {
            $promoteService = new PromoteService();
            $topPromote = $promoteService->getTopPromote($promote);

            /**
             * 市场部特殊推广公司的规则
             */
            $onlyPresidentList = [330, 331, 332];
            if (in_array($topPromote['company_id'], $onlyPresidentList)) {
                if ($topPromote['can_view_recharge'] == 1 && $promote['level'] == 1) {
                    return true;
                } else {
                    return false;
                }
            }

            $closePromoteLowest = [334];
            if (in_array($topPromote['company_id'], $closePromoteLowest)) {
                if ($topPromote['can_view_recharge'] == 1 && $promote['level'] != 4) {
                    return true;
                } else {
                    return false;
                }
            }

            if ($topPromote['can_view_recharge'] == 1) {
                return true;
            }
        }
        return false;
    }

    public function getSelectGames()
    {
        $query = M('game', 'tab_');
        $map = [];
        $map['apply_status'] = 1;
        $map['online_status'] = 1;
        $map['down_port'] = 1;

        $promote = $this->getLoginPromote();
        $promoteService = new PromoteService();
        $gameIds = $promoteService->getVisibleGameIds($promote);
        if (count($gameIds) > 0) {
            $map['id'] = ['in', $gameIds];
        } else {
            $map['_string'] = '1<>1';
        }

        return M('game', 'tab_')
            ->field('id,game_name,sdk_version,relation_game_name,icon,relation_game_id')
            ->where($map)
            ->group('relation_game_id')
            ->select();
    }
}