<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;

use OT\DataDictionary;
use function Sodium\add;
use User\Api\PromoteApi;
use User\Api\UserApi;
use Org\WeixinSDK\Weixin;
use Org\JubaobarSDK\Jubaobar;
use Org\JtpaySDK\Jtpay;
use Org\HeepaySDK\HeepaySDK;
use Org\GoldPig\GoldPig;
use Org\SwiftpassSDK\Swiftpass;
use Com\Wechat;
use Com\WechatAuth;
use Home\Model\UserPlayModel;
use Home\Model\PromoteModel;
use Base\Service\PromoteService;
use Base\Service\ApplyService;

/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class PromoteController extends BaseController
{
    //系统首页
    public function index($p = 1)
    {
        $this->meta_title = "首页";
        $loginPromote = $this->getLoginPromote();
        
        $isOpenQuery = true;

        if (!$isOpenQuery) {
            $this->display('prepare');
            exit(0);
        }

        header("Content-type:text/html;charset=utf-8");
        $user = D('Promote')->isLogin();
        if (empty($user)) {
            $this->redirect("Home/Index/index");
        }

        $quick_menu_list = M("quick_menu qmn", "tab_")
            ->join("tab_promote_quick_menu as pqmn on qmn.id=pqmn.quick_menu_id and promote_id=" . get_pid())
            ->field("qmn.*")
            ->where("qmn.status=0")
            ->order("create_time desc")
            ->limit("0,10")
            ->select();

        $game_list = M("game", "tab_")->field("id,game_name")->order("id desc")->select();
        $gg_list = M("document", "sys_")
            ->join("left join sys_document_article a on a.id=sys_document.id")
            ->limit('0,5')->where("category_id=56 and status=1 and a.id is not null")->order("update_time desc")->select(); //游戏公告
        $zx_list = M("document", "sys_")
            ->join("left join sys_document_article a on a.id=sys_document.id")
            ->limit('0,5')->where("category_id=51 and status=1 and a.id is not null")->order("update_time desc")->select(); //游戏咨询

//        echo M("document", "sys_")->_sql();die();

        $promote_id = get_pid();
        $field = 'id,game_name,server_name,user_account,nickname,promote_account,detail,create_time as update_time';
        $rz_list = M("protect_log", "tab_")->field($field)->where("promote_id = {$promote_id}")->limit('0,5')->order("create_time desc")->select(); //日志管理

        $logCount = M('protect_log', 'tab_')->where("promote_id = {$promote_id}")->count();
        $readLogCount = M('protect_log_read', 'tab_')->where("promote_id = {$promote_id}")->count();

        $gg_data = M("document", "sys_")->join("left join sys_document_article a on a.id=sys_document.id")->where("category_id=56 and status=1 and a.id is not null")->order("update_time desc")->select();
        $gg_Count = count($gg_data);
        $gg_data = implode(',', array_column($gg_data, 'id'));

        $gg_where = "promote_id = {$promote_id} and category_id=56";
        if ($gg_data) {
            $gg_where .= " and document_id IN({$gg_data})";
        }
        $gg_ReadDocument = M("document_read", "sys_")->where($gg_where)->count();
//        var_dump($gg_ReadDocument);die();


        $zx_data = M("document", "sys_")->join("left join sys_document_article a on a.id=sys_document.id")->where("category_id=51 and status=1 and a.id is not null")->order("update_time desc")->select();
        $zx_Count = count($zx_data);
        $zx_data = implode(',', array_column($zx_data, 'id'));
        $zx_where = "promote_id = {$promote_id} and category_id=51";
        if ($zx_data) {
            $zx_where .= " and document_id IN({$zx_data})";
        }
        $zx_ReadDocument = M("document_read", "sys_")->where($zx_where)->count();
        $xx_list = null;

        $today_start = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $today_end = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        $today_open_server_list = M("server as sv", "tab_")
            ->where(
                array("sv.start_time" => array("BETWEEN", array($today_start, $today_end)),
                    "sv.show_status" => 1))
            ->join("left join tab_game gm on gm.id=sv.game_id")
            ->field('sv.*,gm.icon')
            ->order("sv.start_time desc")
            ->page(1, 20)
            ->select();

        $count = M("server", "tab_")
            ->where(
                array("start_time" => array("BETWEEN", array($today_start, $today_end)),
                    "show_status" => 1))
            ->count();

        $page = $this->ajax_page($count, 20, 'seach');
        $this->assign("_page", $page);


        $promoteId = array(get_pid());

        //计算当日用户充值数据
//        $map['_string'] = "promote_id = {$promote_id} or tab_promote.parent_id = {$promote_id} or tab_promote.grand_id = {$promote_id} ";
        //计算当日用户充值数据
//        $map['_string'] = "promote_id = {$promote_id} or tab_promote.parent_id = {$promote_id} or tab_promote.chain like '%/{$promote_id}/%' ";

        $pay_time = " between 0 and " . time();
        $spendData = $this->caculateSpend($pay_time, []);

        $promoteId = implode(',', $promoteId);
        if ($promoteId) {
            $user_count = M("user", "tab_")->where("promote_id IN({$promoteId})")->count();
        } else {
            $user_count = 0;
        }

        $today = total(1);
        $yesterdays = total(5);
        $week = total(2);
        $mounth = total(3);

        $map['tp1.id'] = $promote_id;

        //计算今日的统计数据

        $data = M('promote', 'tab_')->alias('tp1')->field('tp1.account as promote_account,tp1.id, date_format(FROM_UNIXTIME(register_time),"%Y-%m-%d") AS time, count(u.id) as count,		
            count(IF(register_time ' . $yesterdays . ',1,null)) as yesterday,
            count(IF(register_time ' . $today . ',1,null)) as today,
            count(IF(register_time ' . $week . ',1,null)) as week,
            count(IF(register_time ' . $mounth . ',1,null)) as mounth')
            ->join("tab_promote AS tp2 ON tp2.`chain` LIKE CONCAT('%/', tp1.id, '/%')", 'left')
            ->join("tab_user as u on tp2.id = u.promote_id", 'left')
            ->join(false)
            ->where($map)
            ->group('tp1.id')
            ->order('count desc, register_time')
            ->find();

//        $data = M('User', 'tab_')
//            ->field('promote_account,promote_id,date_format(FROM_UNIXTIME(register_time),"%Y-%m-%d") AS time, count(tab_user.id) as count,
//			     IF(tab_promote.grand_id>0,tab_promote.grand_id,IF(tab_promote.grand_id=0 and tab_promote.parent_id >0,tab_promote.parent_id,promote_id)) as promote_id1 ,
//			    count(IF(register_time ' . $yesterdays . ',1,null)) as yesterday,
//			    count(IF(register_time ' . $today . ',1,null)) as today,
//			    count(IF(register_time ' . $week . ',1,null)) as week,
//			    count(IF(register_time ' . $mounth . ',1,null)) as mounth')
//            ->join('tab_promote on promote_id = tab_promote.id', 'left')
//            ->where($map)
//            ->group('promote_id1')
//            ->having('promote_id != 0')
//            ->order('count desc,register_time')
//            ->find();
//        var_dump($data);die();
//        echo M('promote', 'tab_')->_sql();die();

        $total_money = $this->pay_total(0, 0, $promoteId);
        $today_add_user_money = $this->pay_total(1, 1, $promoteId);
        $month_add_user_money = $this->pay_total(3, 1, $promoteId);

        $yesterday_start = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
        $yesterday_end = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        //计算昨天用户的统计数据,当日用户充值数据
        $pay_time = " between {$yesterday_start} and {$yesterday_end}";
        $createTime = ['between', array($yesterday_start, $yesterday_end - 1)];
        $yesterdaySpendData = $this->caculateSpend($pay_time, [], $createTime);

        $todayAddSpendData = $this->caculateSpend($pay_time, [], [], 1);
//        var_dump($todayAddSpendData);die();

        $mounthAddSpendData = $this->caculateSpend($pay_time, [], [], 2);

        $yesterday_user_regist_count = M("user", "tab_")->where(
            array("promote_id" => array('in', $promoteId),
                "register_time" => array("BETWEEN", array($yesterday_start, $yesterday_end))))
            ->count();

        $yesterday_total_money = $this->pay_total(5, 0, $promoteId);

        $today_start = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $today_end = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        $today_regist_user_count = M("user", "tab_")
            ->where(array("promote_id" => array('in', $promoteId),
                "register_time" => array("BETWEEN", array($today_start, $today_end))))
            ->count();
        $today_total_money = $this->pay_total(1, 0, $promoteId);

        $this->assign('data', $data);
//        $this->assign('yesterdayData',$yesterdayData);
        $this->assign('spendData', $spendData);
        $this->assign('yesterdaySpendData', $yesterdaySpendData);
        $this->assign('todayAddSpendData', $todayAddSpendData);
        $this->assign('mounthAddSpendData', $mounthAddSpendData);


        $this->assign("user_count", $user_count);
        $this->assign("total_money", $total_money);
        $this->assign("today_add_user_money", $today_add_user_money);
        $this->assign("month_add_user_money", $month_add_user_money);
        $this->assign("yesterday_user_regist_count", $yesterday_user_regist_count);
        $this->assign("yesterday_total_money", $yesterday_total_money);
        $this->assign("yesterday_total_money", $yesterday_total_money);
        $this->assign("today_regist_user_count", $today_regist_user_count);
        $this->assign("today_total_money", $today_total_money);

        $this->assign("menu_list", $quick_menu_list);
        $this->assign("gg_list", $gg_list);
        $this->assign("gg_count", $gg_Count - $gg_ReadDocument);
        $this->assign("zx_list", $zx_list);
        $this->assign("zx_count", $zx_Count - $zx_ReadDocument);
        $this->assign("xx_list", $xx_list);
        $this->assign('rz_list', $rz_list);
        $this->assign("rz_count", $logCount - $readLogCount);
        $this->assign("today_open_server_list", $today_open_server_list);
        $this->assign("game_list", $game_list);
        $this->meta_title = "首页";
        $this->display();
    }

    private function caculateSpend($pay_time, $condition, $create = [], $type = 0)
    {
        $spend = M('Spend', 'tab_');
        $today = total(1);
        $week = total(2);
        $mounth = total(3);
        $yesterday = total(5);

        $map1['promote_id'] = $map['promote_id'] = array('gt', 0);
        $map1['pay_status'] = $map['pay_status'] = 1;
        $map1['pay_way'] = $map['pay_way'] = array('gt', 0);
        $userId = [];

        $grandPromote = get_pid();

        $promoteId = M("promote", "tab_")->field('id')->where("chain like '%/{$grandPromote}/%' or id = {$grandPromote}")->select();
        $promoteId = array_column($promoteId, 'id');
        $promoteId = implode(',', $promoteId);
        $whereUser['promote_id'] = ['IN', $promoteId];


        if ($type == 1) {
            $start = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
            $end = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
            $whereUser['register_time'] = ['between', array($start, $end - 1)];
            $userId = M('user', 'tab_')->field('id')->where($whereUser)->select();

        } else if ($type == 2) {
            $start = mktime(0, 0, 0, date('m'), 1, date('Y'));
            $end = mktime(0, 0, 0, date('m') + 1, 1, date('Y')) - 1;
            $whereUser['register_time'] = ['between', array($start, $end - 1)];
            $userId = M('user', 'tab_')->field('id')->where($whereUser)->select();
        }

        $userId = implode(',', array_column($userId, 'id'));
        if ($userId) {
            $map1['user_id'] = $map['user_id'] = ['IN', $userId];
        } else if (!$userId && $type != 0) {
            return array('today' => 0, 'mounth' => 0);
        }

        if ($create) {
            $map['create_time'] = $create;
        }

        $bindrecharge_data = M('bind_recharge', 'tab_')
            ->field('max(id) as id,promote_account,promote_id,create_time as ordertime,date_format(FROM_UNIXTIME(create_time),"%Y-%m-%d") AS time, 
               floor(sum(IF(create_time ' . $pay_time . ',real_amount,0))*100)  as scount,
			   floor(sum(IF(create_time ' . $today . ',real_amount,0))*100)  as today,
			   floor(sum(IF(create_time ' . $week . ',real_amount,0))*100) as week,
			   floor(sum(IF(create_time ' . $mounth . ',real_amount,0))*100)   as mounth')
            ->where($map1)
            ->group('promote_id')
            ->select(false);

        $deposit_data = M('deposit', 'tab_')
            ->field('max(id) as id,promote_account,promote_id,create_time as ordertime,date_format(FROM_UNIXTIME(create_time),"%Y-%m-%d") AS time, 
               floor(sum(IF(create_time ' . $pay_time . ',pay_amount,0))*100)  as scount,
			   floor(sum(IF(create_time ' . $today . ',pay_amount,0))*100)  as today,
			   floor(sum(IF(create_time ' . $week . ',pay_amount,0))*100)  as week,
			   floor(sum(IF(create_time ' . $mounth . ',pay_amount,0))*100)  as mounth')
//            ->join('tab_user on tab_user.id = tab_spend.user_id','left')
            ->where($map1)
            ->group('promote_id')
            ->select(false);

        $spendData = $spend
            ->field('max(id) as id,promote_account,promote_id,pay_time as ordertime,date_format(FROM_UNIXTIME(pay_time),"%Y-%m-%d") AS time, 
                   floor(sum(IF(pay_time ' . $pay_time . ',pay_amount,0))*100)  as scount,
    			   floor(sum(IF(pay_time ' . $today . ',pay_amount,0))*100)  as today,
    			   floor(sum(IF(pay_time ' . $week . ',pay_amount,0))*100)  as week,
    			   floor(sum(IF(pay_time ' . $mounth . ',pay_amount,0))*100)  as mounth')
//            ->join('tab_user on tab_user.id = tab_spend.user_id','left')
            ->where($map)
            ->union(' (' . $bindrecharge_data . ') ')
            ->union(' (' . $deposit_data . ') ')
            ->group('promote_id')
            ->select(false);


//        $promote_map = "tp1.`chain` = '/'";
        $promote_id = get_pid();
        $promote_map = "tp1.`id` = {$promote_id}";

        $data = $spend->field('t.pid as promote_id,t.promote_account,sum(a.scount) AS count,sum(a.today) AS today,sum(a. WEEK) AS WEEK,sum(a.mounth) AS mounth')
            ->join("INNER JOIN (SELECT tp2.*, tp1.id AS pid, tp1.account as promote_account FROM tab_promote tp1 LEFT JOIN tab_promote tp2 ON tp2.`chain` LIKE CONCAT('%/', tp1.id, '/%') where $promote_map ) AS t ON promote_id = t.id")
            ->where($condition)->table('(' . $spendData . ') as a')->group('t.pid')->order('count desc,a.ordertime')->find();

        $spendData1 = $spend->field('t.pid as promote_id,t.promote_account,sum(a.scount) AS count,sum(a.today) AS today,sum(a. WEEK) AS WEEK,sum(a.mounth) AS mounth')
            ->join("INNER JOIN (SELECT tp2.*, tp1.id AS pid, tp1.account as promote_account FROM tab_promote tp1 LEFT JOIN tab_promote tp2 ON tp2.`chain` LIKE CONCAT('%/', tp1.id, '/%') ) AS t ON promote_id = t.id")
            ->where($condition)->table('(' . $spendData . ') as a')->group('t.pid')->order('count desc,a.ordertime')->find();

        $data['rand'] = 1;
        $data['count'] = $data['count'] / 100;
        $data['today'] = $spendData1['today'] / 100;
        $data['week'] = $spendData1['week'] / 100;
        $data['mounth'] = $spendData1['mounth'] / 100;

        return $data;
    }

    private function pay_total($type = 0, $newadd = 1, $promoteId = "")
    {
        if ($_REQUEST['promote_id'] === null || $_REQUEST['promote_id'] === '0') {
            $map['parent_id'] = get_pid();
            $map['grand_id'] = get_pid();
            $map['_logic'] = 'or';
            $ids = M('Promote', 'tab_')->where($map)->getfield("id", true);
            if (empty($ids)) {
                $ids = array(get_pid());
            }
            array_unshift($ids, get_pid());
        } else {
            $ids = array($_REQUEST['promote_id']);
        }
        $where['spend.promote_id'] = array('in', $promoteId);
        $where['spend.pay_status'] = 1;
        $where['spend.is_check'] = array('NEQ', 2);
        switch ($type) {
            case 1:
                { // 今天
                    $start = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                    $end = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
                };
                break;
            case 3:
                {
                    // 本月
                    $start = mktime(0, 0, 0, date('m'), 1, date('Y'));
                    $end = mktime(0, 0, 0, date('m') + 1, 1, date('Y')) - 1;
                };
                break;
            case 4:
                {
                    // 本年
                    $start = mktime(0, 0, 0, 1, 1, date('Y'));
                    $end = mktime(0, 0, 0, 1, 1, date('Y') + 1) - 1;
                };
                break;
            case 5:
                { // 昨天
                    $start = mktime(0, 0, 0, date('m'), date('d') - 1, date('Y'));
                    $end = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                };
                break;
            case 6:
                {
                    $start = mktime(0, 0, 0, date('m') - 1, 1, date('Y'));
                    $end = mktime(0, 0, 0, date('m'), 1, date('Y')) - 1;
                };
                break;
            case 9:
                { // 前七天
                    $start = mktime(0, 0, 0, date('m'), date('d') - 6, date('Y'));
                    $end = mktime(date('H'), date('m'), date('s'), date('m'), date('d'), date('Y'));
                };
                break;
            default:
                ;
        }
        if (isset($start) && isset($end)) {
            $where['spend.pay_time'] = array("BETWEEN", array($start, $end));
            if ($newadd == 1) {
                $where['user.register_time'] = array("BETWEEN", array($start, $end));
            }
        }

        if ($newadd == 1) {
            $total = M('spend as spend', "tab_")->field("SUM(spend.pay_amount) as amount")->join("right join tab_user user on user.id=spend.user_id")->where($where)->select();
        } else {
            $total = M('spend as spend', "tab_")->field("SUM(spend.pay_amount) as amount")->where($where)->select();
        }

        $total = $this->huanwei($total[0]['amount']);
        return $total;
    }

    private function huanwei($total)
    {
        $total = empty($total) ? '0' : trim($total . ' ');
        $len = strlen($total) - 3;
        if ($len > 16) {
            // 兆
            $len = $len - 20;
            $total = $len > 0 ? ($len > 4 ? ($len > 8 ? round(($total / 1e28), 4) . '万亿兆' : round(($total / 1e24), 4) . '亿兆') : round(($total / 1e20), 4) . '万兆') : round(($total / 1e16), 4) . '兆';
        } else if ($len > 8) {
            // 亿
            $len = $len - 12;
            $total = $len > 0 ? (round(($total / 1e12), 4) . '万亿') : round(($total / 1e8), 4) . '亿';
        } else if ($len > 4) {
            // 万
            $total = (round(($total / 10000), 4)) . '万';
        }
        return $total;
    }


    public function home_read_data()
    {
        $type = I("type", "0");
        $game_id = I("game_id");
        $pg = I("page", "0");
        $today_start = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
        $today_end = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
        if ($game_id) {
            $map['sv.game_id'] = $game_id;
            $count_map['game_id'] = $game_id;
        }
        if ($type > 0) {
            $map['sv.start_time'] = array("GT", $today_end);
            $count_map['start_time'] = array("GT", $today_end);
        } else {
            $map['sv.start_time'] = array("BETWEEN", array($today_start, $today_end));
            $count_map['start_time'] = array("BETWEEN", array($today_start, $today_end));
        }
        $map['sv.show_status'] = 1;
        $count_map['show_status'] = 1;

        $open_server_list = M("server as sv", "tab_")
            ->where($map)
            ->join("left join tab_game gm on gm.id=sv.game_id")
            ->field('sv.*,gm.icon')
            ->order("sv.start_time desc")
            ->page($pg, 20)
            ->select();

        $count = M("server", "tab_")
            ->where($count_map)
            ->count();
        //var_dump($count);
        $page = $this->ajax_page($count, 20, 'seach', $pg);
        //$this->assign("_page",$page);
        //$count = M("server", "tab_")->where($map)->count();
        foreach ($open_server_list as $key => $server) {
            $open_server_list[$key]['icon'] = get_cover($server['icon'], 'path');
            if ($server['server_version'] == 1) {
                $open_server_list[$key]['pay_type'] = '安卓';
            } elseif ($server['server_version'] == 2) {
                $open_server_list[$key]['pay_type'] = 'iOS';
            } else {
                $open_server_list[$key]['pay_type'] = '安卓、iOS';
            }
            $open_server_list[$key]['pay_type'];
            $open_server_list[$key]['start_time'] = date('m-d H:i', $server['start_time']);
        }
        //$content = $this->fetch('Promote/home_read_data');
        $this->ajaxReturn(['status' => 1, 'info' => '调用成功', 'data' => $open_server_list, '_page' => $page], "JSON");
    }


    public function quick_menu_list()
    {
        $data_list = M("quick_menu qmn", "tab_")
            ->join("left join tab_promote_quick_menu as pqmn on qmn.id=pqmn.quick_menu_id and promote_id=" . get_pid())
            ->field("qmn.*,pqmn.id as exist_id")
            ->where("qmn.status=0")
            ->order("qmn.id asc")
            ->select();
        $this->assign("data_list", $data_list);
        $this->meta_title = "快捷菜单";
        $this->display();
    }


    public function quick_menu_set()
    {
        $menu_id = I("menu_id");
        $info = M("promote_quick_menu ", "tab_")
            ->where(
                array("quick_menu_id" => $menu_id,
                    "promote_id" => get_pid())
            )
            ->find();
        if ($info) {
            M("promote_quick_menu ", "tab_")->where(
                array("quick_menu_id" => $menu_id,
                    "promote_id" => get_pid())
            )->delete();
            $this->ajaxReturn(['status' => 1, 'info' => '移除成功'], "JSON");
        } else {
            $menuData = M("promote_quick_menu ", "tab_")->where(array("promote_id" => get_pid()))->count();

            if ($menuData >= 10) {
                $this->ajaxReturn(['status' => 1, 'info' => '快捷菜单只能有10个'], "JSON");
            }
            M("promote_quick_menu ", "tab_")->add(
                array("quick_menu_id" => $menu_id,
                    "promote_id" => get_pid(),
                    "create_time" => time())
            );
            $this->ajaxReturn(['status' => 1, 'info' => '添加成功'], "JSON");
        }
    }


    // 消息列表
    public function msg_list($type = 56, $p = 0)
    {
        if (isset($_REQUEST['row'])) {
            $row = $_REQUEST['row'];
        } else {
            $row = 10;
        }
        $page = $p ? $p : 1; //默认显示第一页数据
        if ($type == 51) {
            $data_list = M("document", "sys_")->join("left join sys_document_article a on a.id=sys_document.id")->where("category_id=51 and status=1 and a.id is not null")->order("update_time desc")->page($page, $row)->select(); //游戏咨询
            $count = M("document", "sys_")->where("category_id=51 and status=1")->count();
        } elseif ($type == 50) {
            $data_list = null;
            $count = 0;
        } /*else if($type == 0) {
            $field = 'id,game_name,server_name,user_account,nickname,promote_account,detail,create_time as update_time';
            $data_list = M("protect_log","tab_")->field($field)->limit('0,5')->order("create_time desc")->select();

            foreach($data_list as $key => $value) {
                $data_list[$key]['title'] = '账号:'.$value['user_account'].','.$value['detail'];
            }

            $count = M("protect_log","tab_")->field($field)->count();
        }*/ else {
            $data_list = M("document", "sys_")->join("left join sys_document_article a on a.id=sys_document.id")->limit('0,50')->where("category_id=56 and status=1 and a.id is not null")->order("update_time desc")->page($page, $row)->select(); //游戏公告
            $count = M("document", "sys_")->where("category_id=56 and status=1")->count();
        }
        $promote_id = get_pid();
        $logCount = M('protect_log', 'tab_')->where("promote_id = {$promote_id}")->count();
        $readLogCount = M('protect_log_read', 'tab_')->where("promote_id = {$promote_id}")->count();

        $gg_data = M("document", "sys_")->join("left join sys_document_article a on a.id=sys_document.id")->where("category_id=56 and status=1 and a.id is not null")->order("update_time desc")->select();
//        echo M("document", "sys_")->_sql();die();
        $gg_Count = count($gg_data);
        $gg_data = implode(',', array_column($gg_data, 'id'));

        $gg_where = "promote_id = {$promote_id} and category_id=56";
        if ($gg_data) {
            $gg_where .= " and document_id IN({$gg_data})";
        }
        $gg_ReadDocument = M("document_read", "sys_")->where($gg_where)->count();
//        var_dump($gg_ReadDocument);die();


        $zx_data = M("document", "sys_")->join("left join sys_document_article a on a.id=sys_document.id")->where("category_id=51 and status=1 and a.id is not null")->order("update_time desc")->select();
        $zx_Count = count($zx_data);
        $zx_data = implode(',', array_column($zx_data, 'id'));
        $zx_where = "promote_id = {$promote_id} and category_id=51";
        if ($zx_data) {
            $zx_where .= " and document_id IN({$zx_data})";
        }
        $zx_ReadDocument = M("document_read", "sys_")->where($zx_where)->count();

        $parameter['p'] = I('get.p', 1);
        $parameter['row'] = I('get.row');
        $page = set_pagination($count, $row, $parameter);
        if ($page) {
            $this->assign('_page', $page);
        }

        $this->meta_title = "公告列表";
        $this->assign("type", $type);
        $this->assign("data_list", $data_list);
        $this->assign("gg_count", $gg_Count - $gg_ReadDocument);
        $this->assign("zx_count", $zx_Count - $zx_ReadDocument);
        $this->assign("rz_count", $logCount - $readLogCount);
        $this->display();
    }

    /*    public function page_show($model,$map,$p=1)
        {
            if (isset($_REQUEST['row'])) {
                $row = $_REQUEST['row'];
            } else {
                $row = 10;
            }
            $this->meta_title = "平台币充值";
            $page = $p ? $p : 1; //默认显示第一页数据
            $data = M($model, 'tab_')
                ->where($map)
                ->order('id DESC')
                ->page($page, $row)
                ->select();

            $count = M($model, "tab_")->where($map)->count();
            $parameter = $map;
            $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("data_list", $data);
            $this->display();
        }*/

    /**
     * 我的基本信息
     */
    public function base_info()
    {
        if (IS_POST) {
            $type = $_REQUEST['type'];
            $map['id'] = get_pid();
            $se = array();
            foreach ($_REQUEST as $key => $value) {
                $_REQUEST[$key] = trim($value);
            }
            switch ($type) {
                case 0:
                    //if (empty($_REQUEST['nickname']) ) {
                    //    $this->error('请输入昵称', U('Promote/base_info'));
                    //    exit();
                    //}
                    if (empty($_REQUEST['real_name'])) {
                        $this->error('请输入联系人姓名', U('Promote/base_info'));
                        exit();
                    }

                    $pattern = "/^[\x{4e00}-\x{9fa5}]+$/u";
                    if (!preg_match($pattern, $_REQUEST['real_name'])) {
                        $this->error('联系人姓名错误', U('Promote/base_info'));
                        exit();
                    }

                    if (empty($_REQUEST['email'])) {
                        $this->error('请输入电子邮箱', U('Promote/base_info'));
                        exit();
                    }
                    $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
                    if (!preg_match($pattern, $_REQUEST['email'])) {
                        $this->error('邮箱地址错误', U('Promote/base_info'));
                        exit;
                    }
//                    if (empty($_REQUEST['alipay_account']) ) {
//                        $this->error('请输入支付宝账号', U('Promote/base_info'));
//                        exit();
//                    }
                    $se['nickname'] = $_REQUEST['nickname'];
                    $se['real_name'] = $_REQUEST['real_name'];
                    $se['email'] = $_REQUEST['email'];
                    $se['alipay_account'] = $_REQUEST['alipay_account'];


                    break;
                case 1:
                    if (empty($_REQUEST['mobile_phone'])) {
                        $this->error('结算手机号不能为空', U('Promote/base_info'));
                        return false;
                    }
                    $pattern = "/^1[3|5|7|8]\\d{9}$/i";
                    if (!preg_match($pattern, $_REQUEST['mobile_phone'])) {
                        $this->error('您输入的手机号码格式不合法', U('Promote/base_info'));
                    }
                    if ($_REQUEST['s_county'] === "市、县级市") {
                        $this->error('开户城市填写不完整', U('Promote/base_info'));
                        return false;
                        exit();
                    }
                    if (empty($_REQUEST['account_openin'])) {
                        $this->error('开户网点不能为空', U('Promote/base_info'));
                        return false;
                    }
                    $account_openin_pattern = "/^[\x{4e00}-\x{9fa5}]{2,}$/u";
                    if (!preg_match($account_openin_pattern, $_REQUEST['account_openin'])) {
                        $this->error('开户网点错误', U('Promote/base_info'));
                        exit();
                    }
                    if (empty($_REQUEST['bank_name'])) {
                        $this->error('收款银行不能为空', U('Promote/base_info'));
                        return false;
                    }
                    if (empty($_REQUEST['bank_card'])) {
                        $this->error('银行卡号不能为空', U('Promote/base_info'));
                        return false;
                    }

                    if (!is_numeric($_REQUEST['bank_card'])) {
                        $this->error('卡号格式错误', U('Promote/base_info'));
                        return false;
                    }
                    $bank_card_pattern = "/^\d{10,19}$/u";
                    if (!preg_match($bank_card_pattern, $_REQUEST['bank_card'])) {
                        $this->error('卡号格式错误', U('Promote/base_info'));
                        exit();
                    }
                    if (empty($_REQUEST['bank_account'])) {
                        $this->error('银行户名不能为空', U('Promote/base_info'));
                        return false;
                    }
                    $bank_account_pattern = "/^[\x{4e00}-\x{9fa5}]{2,}$/u";
                    if (!preg_match($bank_account_pattern, $_REQUEST['bank_account'])) {
                        $this->error('银行卡开户人姓名错误', U('Promote/base_info'));
                        exit();
                    }
                    if (empty($_REQUEST['idcard'])) {
                        $this->error('证件号码不能为空', U('Promote/base_info'));
                        exit();
                    }
                    if (!is_idcard($_REQUEST['idcard'])) {
                        $this->error('证件号码错误', U('Promote/base_info'));
                        exit();
                    }


                    $se['mobile_phone'] = $_REQUEST['mobile_phone'];
                    $se['bank_name'] = $_REQUEST['bank_name'];
                    $se['bank_card'] = $_REQUEST['bank_card'];
                    $se['bank_account'] = $_REQUEST['bank_account'];
                    $se['account_openin'] = $_REQUEST['account_openin'];
                    $se['bank_area'] = $_REQUEST['s_province'] . ',' . $_REQUEST['s_city'] . ',' . $_REQUEST['s_county'];
                    $se['idcard'] = $_REQUEST['idcard'];
                    break;
                case 2:
                    if ($_REQUEST['old_password'] != "0" && empty($_REQUEST['old_password'])) {
                        $this->error('旧密码不能为空', U('Promote/base_info'));
                        return false;
                    }
                    if (strlen($_REQUEST['old_password']) < 6) {
                        $this->error('旧密码不正确', U('Promote/base_info'));
                        return false;
                    }
                    if ($_REQUEST['password'] != "0" && empty($_REQUEST['password'])) {
                        $this->error('新密码不能为空', U('Promote/base_info'));
                        return false;
                    }
                    if (strlen($_REQUEST['password']) < 6) {
                        $this->error('新密码最短6位', U('Promote/base_info'));
                        return false;
                    }
                    if (empty($_REQUEST['confirm_password'])) {
                        $this->error('确认密码不能为空', U('Promote/base_info'));
                        return false;
                    }
                    if (strlen($_REQUEST['confirm_password']) < 6) {
                        $this->error('确认密码最短6位', U('Promote/base_info'));
                        return false;
                    }
                    $prp = M("promote", "tab_")->where($map)->find();
                    $ue = new UserApi();
                    if ($_REQUEST['password'] !== $_REQUEST['confirm_password']) {
                        $this->error('新密码和确认密码不一致', U('Promote/base_info'));
                        return false;
                    } else {
                        $se['password'] = $this->think_ucenter_md5($_REQUEST['confirm_password'], UC_AUTH_KEY);
                    }
                    if ($this->think_ucenter_md5($_REQUEST['old_password'], UC_AUTH_KEY) !== $prp['password']) {
                        $this->error('请输入正确的旧密码', U('Promote/base_info'));
                        return false;
                        exit();
                    }
                    break;

                case 3:
                    $prp = M("promote", "tab_")->where($map)->find();
                    $ue = new UserApi();
                    if ($_REQUEST['old_second_pwd'] != "0" && empty($_REQUEST['old_second_pwd']) && !empty($prp['second_pwd'])) {
                        $this->error('旧二级密码不能为空', U('Promote/base_info'));
                        return false;
                    }
                    if (strlen($_REQUEST['old_second_pwd']) < 6 && !empty($prp['second_pwd'])) {
                        $this->error('旧二级密码不正确', U('Promote/base_info'));
                        return false;
                    }
                    if ($_REQUEST['second_pwd'] != "0" && empty($_REQUEST['second_pwd'])) {
                        $this->error('新二级密码不能为空', U('Promote/base_info'));
                        return false;
                    }

                    if (strlen($_REQUEST['second_pwd']) < 6) {
                        $this->error('新二级密码长度不能小于6', U('Promote/base_info'));
                        return false;
                    }
                    if (empty($_REQUEST['confirm_second_pwd'])) {
                        $this->error('请输入确认密码', U('Promote/base_info'));
                        return false;
                    }
                    if ($_REQUEST[''] != $_REQUEST['']) {
                        $this->error('新耳机密码和确认密码不一致', U('Promote/base_info'));
                        return false;
                    }
                    if ($this->think_ucenter_md5($_REQUEST['old_second_pwd'], UC_AUTH_KEY) != $prp['second_pwd']) {
                        $this->error('旧二级密码错误', U('Promote/base_info'));
                        return false;
                        exit();

                    } else if ($_REQUEST['second_pwd'] !== $_REQUEST['confirm_second_pwd']) {
                        $this->error('新二级密码和确认密码不一致', U('Promote/base_info'));
                        return false;
                    } else {
                        $se['second_pwd'] = $this->think_ucenter_md5($_REQUEST['confirm_second_pwd'], UC_AUTH_KEY);
                    }
                    break;
                default:
                    $se['nickname'] = $_REQUEST['nickname'];
                    $se['real_name'] = $_REQUEST['real_name'];
                    $se['email'] = $_REQUEST['email'];
                    break;
            }
            $res = M("promote", "tab_")->where($map)->save($se);
            if ($res !== false) {
                $this->success("修改成功", U('Promote/base_info?type=' . $type));
            } else {
                $this->error('修改失败', U('Promote/base_info'));
            }
        } else {
            $model = M('Promote', 'tab_');
            $data = $model->find(session("promote_auth.pid"));
            $data['bank_area'] = explode(',', $data['bank_area']);
            $this->meta_title = "基本信息";
            $this->assign("data", $data);

            $this->wxQrcode($data);
            $user = D('Promote')->isLogin();
            if (empty($user)) {
                $this->redirect("Home/Index/index");
            }
            $promoteUrl = "https://m.wmtxkj.com/mobile.php?s=Ssg/home/promote_id/" . $user['pid'];
            $this->assign("promote_url", $promoteUrl);

            $this->display();
        }
    }

    public function think_ucenter_md5($str, $key = 'ThinkUCenter')
    {
        return '' === $str ? '' : md5(sha1($str) . $key);
    }

    public function children()
    {
        $account = I('account', '');
        $idcard = I('idcard', '');
        $mobile = I('mobile', '');
        $realName = I('real_name', '');
        $status = I('status', 'all');
        $promoteType = I('promote_type', 0);

        $loginer = $this->getLoginPromote();

        $map = [];
        $map['chain'] = ['like', $loginer['chain'] . $loginer['id'] . '/%'];

        if ($promoteType == 0) {
            $map['level'] = 2;
        } elseif ($promoteType == 1) {
            $map['level'] = 3;
        } elseif ($promoteType == 2) {
            $map['level'] = 4;
        }

        if ($account) {
            $map['account'] = ['like', '%' . $account . '%'];
        }
        if ($mobile) {
            $map['mobile_phone'] = ['like', '%' . $mobile . '%'];
        }
        if ($idcard) {
            $map['idcard'] = ['like', '%' . $idcard . '%'];
        }
        if ($realName) {
            $map['real_name'] = ['like', '%' . $realName . '%'];
        }
        if ($status != 'all') {
            $map['status'] = ['eq', $status];
        }
        $query = M('promote', 'tab_')->where($map);
        list($records, $pagination, $count) = $this->paginate($query);

        $ids = array_column($records, 'id');

        $countList = [];
        $playerList = [];
        $shiftList = [];
        $shiftPlayerList = [];
        if (count($ids) > 0) {
            $countList = M('promote', 'tab_')->field(['count(*)' => 'count', 'parent_id' => 'parent_id'])->where(['parent_id' => ['in', $ids]])->group('parent_id')->select();
            $playerList = M('user_play', 'tab_')->field(['count(*)' => 'count', 'promote_id' => 'promote_id'])->where(['promote_id' => ['in', $ids]])->group('promote_id')->select();
            
            $shiftList = M('shift_task', 'sys_')
                ->field(['count(*)' => 'count', 'from_promote_id' => 'from_promote_id'])
                ->where(['status' => 0, 'type' => 1, 'from_promote_id' => ['in', $ids]])
                ->group('from_promote_id')
                ->select();
            
            $shiftPlayerList = M('shift_task', 'sys_')
                ->field(['count(*)' => 'count', 'from_promote_id' => 'from_promote_id'])
                ->where(['status' => 0, 'type' => 2, 'from_promote_id' => ['in', $ids]])
                ->group('from_promote_id')
                ->select();

            $hasChildList = array_column($countList, 'parent_id');
            $hasPlayerList = array_column($playerList, 'promote_id');
            $hasShiftList = array_column($shiftList, 'from_promote_id');
            $hasShiftPlayerList = array_column($shiftPlayerList, 'from_promote_id');
        }

        if ($promoteType == 0) {
            $promoteTypeName = '部门长';
        } elseif ($promoteType == 1) {
            $promoteTypeName = '组长';
        } elseif ($promoteType == 2) {
            $promoteTypeName = '推广员';
        }

        $this->assign('promoteTypeName', $promoteTypeName);
        $this->assign('hasChildList', $hasChildList);
        $this->assign('hasPlayerList', $hasPlayerList);
        $this->assign('hasShiftList', $hasShiftList);
        $this->assign('hasShiftPlayerList', $hasShiftPlayerList);
        $this->assign('count', $count);
        $this->assign('pagination', $pagination);
        $this->assign('records', $records);
        $this->display();
    }

    public function addPromote()
    {
        if (IS_POST) {
            $params = I('post.');
            $loginPromote = $this->getLoginPromote();
            
            if ($params['promote_type'] == 0 && $loginPromote['level'] > 1) {
                $this->ajaxReturn(['status' => 0, 'msg' => '无权限']);
            }
            if ($params['promote_type'] == 1 && $loginPromote['level'] > 2) {
                $this->ajaxReturn(['status' => 0, 'msg' => '无权限']);
            }
            if ($params['promote_type'] == 2 && $loginPromote['level'] > 3) {
                $this->ajaxReturn(['status' => 0, 'msg' => '无权限']);
            }

            $parent = null;
            if (isset($params['parent_id']) && $params['parent_id']) {
                $parent = M('promote', 'tab_')->where(['id' => $params['parent_id']])->find();
            } else {
                $parent = $loginPromote;
            }
            $promoteService = new PromoteService();
            $result = $promoteService->checkAddPromote($params);
            if (!$result['status']) {
                $this->ajaxReturn(['status' => 0, 'msg' => $result['message']]);
            }
            $status = $promoteService->addPromote($params, $parent);
            if ($status) {
                $this->ajaxReturn(['status' => 1, 'msg' => '添加成功']);
            } else {
                $this->ajaxReturn(['status' => 0, 'msg' => '添加失败']);
            }
        } else {
            $promoteType = I('get.promote_type', 0);
            $loginer = $this->getLoginPromote();
            $promotes = null;
            $promoteColumns = ['id', 'account', 'real_name'];
            $promoteMap = ['chain' => ['like', $loginer['chain'] . $loginer['id'] . '/' . '%']];
            if ($loginer['level'] == 1) {
                if ($promoteType == 1) {
                    $promoteMap['level'] = 2;
                    $promotes = M('promote', 'tab_')->field($promoteColumns)->where($promoteMap)->select();
                } elseif ($promoteType == 2) {
                    $promoteMap['level'] = 3;
                    $promotes = M('promote', 'tab_')->field($promoteColumns)->where($promoteMap)->select();
                }
            } elseif ($loginer['level'] == 2) {
                if ($promoteType == 2) {
                    $promoteMap['level'] = 3;
                    $promotes = M('promote', 'tab_')->field($promoteColumns)->where($promoteMap)->select();
                }
            }

            $promoteTypeName = '';
            $parentTypeName = '';
            if ($promoteType == 0) {
                $promoteTypeName = '部门长';
            } elseif ($promoteType == 1) {
                $promoteTypeName = '组长';
                $parentTypeName = '部门长';
            } elseif ($promoteType == 2) {
                $promoteTypeName = '推广员';
                $parentTypeName = '组长';
            }

            $this->assign('parentTypeName', $parentTypeName);
            $this->assign('promoteTypeName', $promoteTypeName);
            $this->assign('promotes', $promotes);
            $this->meta_title = "添加子渠道";
            $this->display();
        }
    }

    public function resetPassword()
    {
        $promoteId = I('promote_id', 0);
        if ($promoteId == 0) {
            $this->ajaxReturn(['status' => 0, 'msg' => "参数错误"]);
        }

        $promoteService = new PromoteService();
        if ($password = $promoteService->resetPassword($promoteId)) {
            $this->ajaxReturn(['status' => 1, 'msg' => '重置密码成功', 'data' => ['password' => $password]]);
        } else {
            $this->ajaxReturn(['status' => 0, 'msg' => '重置密码失败']);
        }
    }

    public function froze()
    {
        $promoteId = I('promote_id', 0);
        if ($promoteId == 0) {
            $this->ajaxReturn(['status' => 0, 'msg' => "参数错误"]);
        }
        $promoteService = new PromoteService();
        if ($promoteService->froze($promoteId)) {
            $this->ajaxReturn(['status' => 1, 'msg' => '冻结成功']);
        } else {
            $this->ajaxReturn(['status' => 0, 'msg' => '冻结失败']);
        }
    }

    public function unfreeze()
    {
        $promoteId = I('promote_id', 0);
        if ($promoteId == 0) {
            $this->ajaxReturn(['status' => 0, 'msg' => "参数错误"]);
        }
        $promoteService = new PromoteService();
        if ($promoteService->unfreeze($promoteId)) {
            $this->ajaxReturn(['status' => 1, 'msg' => '解冻成功']);
        } else {
            $this->ajaxReturn(['status' => 0, 'msg' => '解冻失败']);
        }
    }

    public function editPromote()
    {

    }

    public function edit_chlid($id = 0)
    {
        if (IS_POST) {
            $type = $_REQUEST['type'];
            $map['id'] = $id;
            $se = array();
            foreach ($_REQUEST as $key => $value) {
                $_REQUEST[$key] = trim($value);
            }
            switch ($type) {
                case 0:
                    if (empty($_REQUEST['nickname'])) {
                        $this->error('子账号昵称不能为空', U('Promote/edit_chlid', array('id' => $id, 'type' => I('type', 0))));
                        exit();
                    }

                    if ($_POST['password'] != "0" && empty($_POST['password'])) {
                        unset($_POST['password']);
                    } else {
                        if (strlen($_REQUEST['password']) < 6) {
                            $this->error('登录密码不能小于6位字符', U('Promote/edit_chlid', array('id' => $id, 'type' => I('type', 0))));
                            return false;
                        }
                    }

                    if (empty($_REQUEST['real_name'])) {
                        $this->error('联系人姓名不能为空', U('Promote/edit_chlid', array('id' => $id, 'type' => I('type', 0))));
                        exit();
                    }

                    $pattern = "/^[\x{4e00}-\x{9fa5}]+$/u";
                    if (!preg_match($pattern, $_REQUEST['real_name'])) {
                        $this->error('您输入的联系人姓名格式不正确', U('Promote/edit_chlid', array('id' => $id, 'type' => I('type', 0))));
                        exit();
                    }

                    if (empty($_REQUEST['mobile_phone'])) {
                        $this->error('手机号不能为空', U('Promote/edit_chlid', array('id' => $id, 'type' => I('type', 0))));
                        return false;
                    }

                    $pattern = "/^1[3|5|7|8]\\d{9}$/i";
                    if (!preg_match($pattern, $_REQUEST['mobile_phone'])) {
                        $this->error('您输入的手机号码格式不合法', U('Promote/edit_chlid', array('id' => $id, 'type' => I('type', 0))));
                    }

                    if (empty($_REQUEST['email'])) {
                        $this->error('电子邮箱不能为空', U('Promote/edit_chlid', array('id' => $id, 'type' => I('type', 0))));
                        return false;
                    }

                    $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
                    if (!preg_match($pattern, $_REQUEST['email'])) {
                        $this->error('您输入的电子邮箱地址不合法', U('Promote/edit_chlid', array('id' => $id, 'type' => I('type', 0))));
                    };

                    $user = new PromoteApi();
                    $res = $user->edit($_POST);

                    if ($res !== false) {
                        $this->success("子账号修改成功", U('Promote/children'));
                    } else {
                        $this->error("修改子账号失败");
                    }
                    break;
                case 1:
                    if ($_REQUEST['s_county'] === "市、县级市") {
                        $this->error('开户城市填写不完整', U('Promote/edit_chlid', array('id' => $id, 'type' => I('type', 1))));
                        return false;
                        exit();
                    }
                    if (empty($_REQUEST['account_openin'])) {
                        $this->error('开户网点不能为空', U('Promote/edit_chlid', array('id' => $id, 'type' => I('type', 1))));
                        return false;
                    }
                    if (empty($_REQUEST['bank_name'])) {
                        $this->error('收款银行不能为空', U('Promote/edit_chlid', array('id' => $id, 'type' => I('type', 1))));
                        return false;
                    }
                    if (empty($_REQUEST['bank_card'])) {
                        $this->error('银行卡号不能为空', U('Promote/edit_chlid', array('id' => $id, 'type' => I('type', 1))));
                        return false;
                    }
                    if (!is_numeric($_REQUEST['bank_card'])) {
                        $this->error('请输入正确的银行卡号', U('Promote/edit_chlid', array('id' => $id, 'type' => I('type', 1))));
                        return false;
                    }
                    if (empty($_REQUEST['bank_account'])) {
                        $this->error('银行户名不能为空', U('Promote/edit_chlid', array('id' => $id, 'type' => I('type', 1))));
                        return false;
                    }
                    $se['mobile_phone'] = $_REQUEST['mobile_phone'];
                    $se['bank_name'] = $_REQUEST['bank_name'];
                    $se['bank_card'] = $_REQUEST['bank_card'];
                    $se['bank_account'] = $_REQUEST['bank_account'];
                    $se['account_openin'] = $_REQUEST['account_openin'];
                    $se['bank_area'] = $_REQUEST['s_province'] . ',' . $_REQUEST['s_city'] . ',' . $_REQUEST['s_county'];
                    $res = M("promote", "tab_")->where($map)->save($se);

                    if ($res !== false) {
                        $this->success("修改成功", U('Promote/edit_chlid', array('id' => $id, 'type' => $type)));
                    } else {
                        $this->error('修改失败', U('Promote/edit_chlid', array('id' => $id, 'type' => $type)));
                    }
                    break;
            }

        } else {
            $promote = A('Promote', 'Event');
            $this->meta_title = '子帐号';
            $promote->baseinfo('edit_chlid', $id);
        }

    }

    /**
     * @param int $level
     * @param int $size
     */
    public function qrcode($level = 3, $size = 4, $url = "")
    {
        Vendor('phpqrcode.phpqrcode');
        $errorCorrectionLevel = intval($level);//容错级别
        $matrixPointSize = intval($size);//生成图片大小
        //生成二维码图片
        ob_clean();
        $object = new \QRcode();
        echo $object->png(base64_decode(base64_decode($url)), false, $errorCorrectionLevel, $matrixPointSize, 2);
    }

    public function checkAccount($account)
    {
        $user = get_promote_entity($account, true);
        if ($user) {
            $this->ajaxReturn(array('status' => 1));
        } else {
            $this->ajaxReturn(array('status' => 0));
        }
    }

    public function balance()
    {
        if (IS_POST) {

            $real_amount = $amount = I('amount');


            if (!is_numeric($amount)) {
                $res_msg = '充值金额不是数字';
                $this->show_balance();
                echo "<script>layer.msg('{$res_msg}',{time:1000});</script>;
										return false;";
                $this->redirect('balance', array('status' => 1), 3, '');
            }
            if ($amount < 0) {
                $res_msg = '充值金额不正确';
                $this->show_balance();
                echo "<script>layer.msg('{$res_msg}',{time:1000});</script>;
										return false;";
                $this->redirect('balance', array('status' => 1), 3, '');
            }
            $amount = abs($amount);
            // $amount = 0.01;//测试金额
            if (empty($_REQUEST['account'])) {
                $user = get_promote_entity(PID);
            } else {
                $user = get_promote_entity($_REQUEST['account'], true);
            }

            $order_no = "TB_" . date('Ymd') . date('His') . sp_random_string(4);
            $create['amount'] = $amount;
            $create['pay_order_number'] = $order_no;

            $vo = new \Think\Pay\PayVo();
            $vo->setBody("账户余额")
                ->setFee($amount)//支付金额
                ->setTitle("余额充值")
                ->setOrderNo($order_no)
                ->setSignType("MD5")
                ->setPayMethod("direct_tb")
                ->setTable("balance")
                ->setUserId($user['id'])
                ->setAccount($user['account'])
                ->setPromoteId(PID)
                ->setPromoteName(PROMOTE_ACCOUNT)
                ->setMoney($user['balance_coin']);

            switch (I('pay_type')) {
                case 'swiftpass':
                    //判断是否开启微信充值
                    if (pay_set_status('wei_xin') == 0 && pay_set_status('weixin') == 0) {
                        $this->error("网站未开启微信充值", '', 1);
                        exit();
                    }
                    if (get_wx_type() == 0) {
                        $weixn = new Weixin();
                        $is_pay = json_decode($weixn->weixin_pay("余额充值", $order_no, $real_amount), true);
                        if ($is_pay['status'] === 1) {
                            $json_['out_trade_no'] = $order_no;
                            $json_['amount'] = $amount;
                            $json_['pay_money'] = $real_amount;
                            $json_['code_img_url'] = U('qrcode', array('level' => 3, 'size' => 4, 'url' => base64_encode(base64_encode($is_pay['url']))));
                        }
                        $create['pay_way'] = 2;
                        $this->add_balance($user, $create);

                        $this->show_balance();
                        echo "<script> img_qrcode(" . json_encode($json_) . ") </script>";
                    } else {
                        $vo->setService("pay.weixin.native")
                            ->setPayWay(2);
                        $pay = new \Think\Pay('swiftpass', C('weixin'));
                        $all = $pay->buildRequestForm($vo);
                        $all['amount'] = $vo->getMoney();
                        $this->show_balance();
                        echo "<script> img_qrcode(" . json_encode($all) . ") </script>";
                    }
                    break;
                case 'goldpig':

                    if (pay_set_status('goldpig') == 0) {
                        $this->error("网站未开启金猪充值", '', 1);
                        exit();
                    }

                    if (empty(C('goldpig.partner')) || empty(C('goldpig.wooolid'))) {
                        $this->error("网站未配置金猪充值", '', 1);
                        exit();
                    }
                    if ($amount < 1) {
                        $this->error("单笔金额不小于1", '', 1);
                        exit();
                    }

                    $sign = think_encrypt(md5($real_amount . $order_no));
                    $create['pay_way'] = 8;

                    $this->add_balance($user, $create);
                    file_put_contents("./Application/Home/OrderNo/" . $order_no . '.txt', json_encode($create));
                    redirect(U('goldpig_pay', array('userid' => $user['id'], 'account' => $user['account'], 'pay_amount' => $real_amount, 'sign' => $sign, 'pay_order_number' => $order_no)));
                    break;
                default:
                    //判断是否开启支付宝充值
                    if (pay_set_status('alipay') == 0) {
                        $this->error("网站未开启支付宝充值", '', 1);
                        exit();
                    }
                    $vo->setService("create_direct_pay_by_user")
                        ->setPayWay(1);
                    $pay = new \Think\Pay('alipay', C('alipay'));
                    echo $pay->buildRequestForm($vo);
                    break;
            }


        } else {
            $model = M('Promote', 'tab_');
            $data = $model->find(session("promote_auth.pid"));
            $data['bank_area'] = explode(',', $data['bank_area']);
            $this->assign('data', $data);
            $this->meta_title = '账户余额';
            $this->display();
        }

    }

    public function balance_recharge()
    {
        if (IS_POST) {

            $real_amount = $amount = I('amount', 0, 'intval');

            //$real_amount = $amount = 0.01;

            if (!is_numeric($amount)) {

                $this->ajaxReturn(['status' => 0, 'info' => '充值金额不是数字']);

            }
            if ($amount < 0) {

                $this->ajaxReturn(['status' => 0, 'info' => '充值金额错误']);

            }

            if (empty($_REQUEST['account'])) {
                $user = get_promote_entity(PID);
            } else {
                $user = get_promote_entity($_REQUEST['account'], true);
            }

            $order_no = "TB_" . date('Ymd') . date('His') . sp_random_string(4);
            $create['amount'] = $amount;
            $create['pay_order_number'] = $order_no;

            $vo = new \Think\Pay\PayVo();
            $vo->setBody("账户余额")
                ->setFee($amount)//支付金额
                ->setTitle("余额充值")
                ->setOrderNo($order_no)
                ->setSignType("MD5")
                ->setPayMethod("direct_tb")
                ->setTable("balance")
                ->setUserId($user['id'])
                ->setAccount($user['account'])
                ->setPromoteId(PID)
                ->setPromoteName(PROMOTE_ACCOUNT)
                ->setMoney($user['balance_coin']);

            switch (I('pay_type')) {
                case 'swiftpass':
                    //判断是否开启微信充值
                    if (pay_set_status('wei_xin') == 0 && pay_set_status('weixin') == 0) {
                        $this->ajaxReturn(['status' => 0, 'info' => '网站未开启微信充值']);
                    }
                    if (get_wx_type() == 0) {
                        $weixn = new Weixin();
                        $is_pay = json_decode($weixn->weixin_pay("余额充值", $order_no, $real_amount), true);
                        if ($is_pay['status'] === 1) {
                            $json_['out_trade_no'] = $order_no;
                            $json_['amount'] = $amount;
                            $json_['pay_money'] = $real_amount;
                            $json_['code_img_url'] = U('qrcode', array('level' => 3, 'size' => 4, 'url' => base64_encode(base64_encode($is_pay['url']))));
                        }
                        $create['pay_way'] = 2;
                        $this->add_balance($user, $create);

                        $this->ajaxReturn(['status' => 1, 'info' => '', 'data' => $json_]);

                    } else {
                        $vo->setService("pay.weixin.native")
                            ->setPayWay(2);
                        $pay = new \Think\Pay('swiftpass', C('weixin'));
                        $all = $pay->buildRequestForm($vo);
                        $all['amount'] = $vo->getMoney();

                        $this->ajaxReturn(['status' => 1, 'info' => '', 'data' => $all]);

                    }
                    break;
                default:
                    //判断是否开启支付宝充值
                    if (pay_set_status('alipay') == 0) {
                        $this->ajaxReturn(['status' => 0, 'info' => '网站未开启支付宝充值']);
                    }
                    $vo->setService("create_direct_pay_by_user")
                        ->setPayWay(1);
                    $pay = new \Think\Pay('alipay', C('alipay'));
                    $url = $pay->buildRequestForm($vo);
                    $this->ajaxReturn(['status' => 1, 'info' => '', 'url' => $url]);
            }


        } else {
            $this->ajaxReturn(['status' => 0, 'info' => '请求有误']);
        }

    }


    /**
     * 金猪支付
     * @return [type] [description]
     * @author cb <[email address]>
     */
    public function goldpig_pay()
    {
        if (IS_POST) {
            SafeFilter($_POST);
            $msign = think_encrypt(md5($_POST['amount'] . $_POST['pay_order_number']));
            if ($msign !== $_POST['sign']) {
                $this->error('验证失败', U('promote/balance'));
                exit;
            }
            if ($_POST['amount'] <= 0) {
                $this->error('金额有误');
            }
            $url = "./Application/Home/OrderNo/" . $_POST['pay_order_number'] . '.txt';
            if (!file_exists($url)) {
                $this->error('操作有误', U('promote/balance'));
                exit;
            }

            $user = M('Promote', 'tab_')->field('id,account')->where(['account' => $_POST['UserName']])->find();

            if (empty($user)) {
                $this->error("账号不存在");
                exit();
            }


            $baseurl = 'http://api.357p.com/?';

            $url = $baseurl . "UserName={$_POST['UserName']}&Price={$_POST['amount']}&shouji={$_POST['shouji']}&PayID={$_POST['PayID']}&userid={$_POST['userid']}&wooolID={$_POST['wooolID']}&jinzhua={$_POST['pay_order_number']}&jinzhub={$_POST['jinzhub']}&jinzhuc={$_POST['jinzhuc']}&jinzhue={$_POST['pay_order_number']}";

            redirect($url);
            exit;

        } else {
            $this->display();
        }


    }


    public function show_balance()
    {
        $model = M('Promote', 'tab_');
        $data = $model->find(session("promote_auth.pid"));
        $data['bank_area'] = explode(',', $data['bank_area']);
        $this->assign('data', $data);
        $this->meta_title = '账户余额';
        $this->display('balance');
    }

    public function checkOrder($order_number)
    {
        $map['pay_order_number'] = $order_number;
        $data = M('Balance', 'tab_')
            ->where($map)
            ->field('pay_status')
            ->find();
        if ($data['pay_status'] == 1) {
            $this->success('支付成功');
        } else {
            $this->error('暂未支付');
        }
    }


    public function add_balance($promote, $data)
    {
        $balance = M("Balance", "tab_");
        $balance_data['order_number'] = "";
        $balance_data['pay_order_number'] = $data['pay_order_number'];
        $balance_data['money'] = $data['amount'];
        $balance_data['balance'] = $promote['balance_coin'];
        $balance_data['pay_status'] = 0;
        $balance_data['recharge_type'] = $data['pay_way'];
        $balance_data['create_time'] = time();
        $balance_data['recharge_id'] = $promote['id'];
        $balance_data['recharge_account'] = $promote['account'];
        $balance_data['promote_id'] = PID;
        $balance_data['promote_account'] = PROMOTE_ACCOUNT;
        $balance->create($balance_data);
        $result = $balance->add();
        return $result;
    }


    public function wxQrcode($promote = '')
    {
        if (C('wechat.status') > 0) {
            $appid = C('wechat.appid');
            $appsecret = C('wechat.appsecret');
            $token = session("token");
            if ($token) {
                $auth = new WechatAuth($appid, $appsecret, $token);
            } else {
                $auth = new WechatAuth($appid, $appsecret);
                $token = $auth->getAccessToken();

                session(array('expire' => $token['expires_in']));
                session("token", $token['access_token']);
            }
            if (empty($promote)) {
                $promote = D('promote')->detail();
            }

            $sign = $promote['weixin_openid_sign'] ? $promote['weixin_openid_sign'] : rand(1, 99999);

            $ticket = $auth->qrcodeCreate($sign, 604800);

            $this->assign('wxQrcodeUrl', $ticket['url']);

        } else {
            $this->assign('wxQrcodeUrl', null);
        }
    }

    public function wxQrcodeRedirect()
    {

        $xml_str = $GLOBALS['HTTP_RAW_POST_DATA'];

        $this->logger($xml_str);

        if (!empty($xml_str)) {
            libxml_disable_entity_loader(true);

            $request_xml = simplexml_load_string($xml_str, 'SimpleXMLElement', LIBXML_NOCDATA);

            switch ($request_xml->MsgType) {
                case 'event':
                    $this->_setOpenid($request_xml);
                    break;
            }
        } else {
            die('');
        }

    }


    public function _setOpenid($data, $type)
    {
        $event = strtolower($data->Event);
        $openid = $data->FromUserName; // 用户
        $auth = new WechatAuth(C('wechat.appid'), C('wechat.appsecret'));
        $model = D('Promote');
        $promote = $model->detail();
        $data = array('id' => $promote['id']);
        $user = $auth->userInfo($openid);
        switch ($event) {
            case 'subscribe':
                {
                    // 关注事件
                    if (!empty($promote['weixin_openid'])) {
                        $auth->setText($openid, date('Y-m-d H:i:s') . ' 请先解绑微信');
                        exit;
                    }
                    if (str_replace('qrscene_', '', $data['EventKey']) != $promote['weixin_openid_sign']) {
                        $auth->setText($openid, date('Y-m-d H:i:s') . ' 页面错误,请刷新页面重试');
                        exit;
                    }
                    $data['weixin_account'] = emoji_encode($user['nickname']);
                    $data['weixin_openid'] = $openid;
                    $res = $model->update($data);
                    if ($res) {
                        $auth->sendText($openid, date('Y-m-d H:i:s') . ' 微信绑定成功');
                    } else {
                        $auth->sendText($openid, date('Y-m-d H:i:s') . ' 微信绑定失败');
                    }
                };
                break;
            case 'scan':
                {
                    // 关注以后
                    if ($user['subscribe'] != 1) {
                        $auth->setText($openid, date('Y-m-d H:i:s') . ' 你未关注微信');
                        exit;
                    }
                    if (empty($promote['weixin_openid'])) {
                        $auth->setText($openid, date('Y-m-d H:i:s') . ' 请先绑定微信');
                        exit;
                    }


                };
                break;
            case 'unsubscribe':
                {
                    // 取消关注
                    if ($promote['weixin_openid'] != $openid) {
                        $auth->setText($openid, date('Y-m-d H:i:s') . ' 对不起,你没有权限');
                        exit;
                    }
                    if (str_replace('qrscene_', '', $data['EventKey']) != $promote['weixin_openid_sign']) {
                        $auth->setText($openid, date('Y-m-d H:i:s') . ' 页面错误,请刷新页面重试');
                        exit;
                    }
                    if (empty($promote['weixin_openid'])) {
                        $auth->setText($openid, date('Y-m-d H:i:s') . ' 暂未绑定微信');
                        exit;
                    }
                    $data['weixin_account'] = '';
                    $data['weixin_openid'] = '';
                    $res = $model->update($data);
                    if ($res) {
                        $auth->sendText($openid, date('Y-m-d H:i:s') . ' 微信解绑成功');
                    } else {
                        $auth->sendText($openid, date('Y-m-d H:i:s') . ' 微信解绑失败');
                    }

                };
                break;
        }
    }


    public function logger($log_content)
    {
        $fg_str = "\n============================================================\n";
        $max_size = 500000;
        $log_filename = __ROOT__ . "/Uploads/Logs/log" . date('Ymd') . ".xml";
        if (file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)) {
            unlink($log_filename);
        }
        if (is_array($log_content)) {
            file_put_contents($log_filename, date('Y-m-d H:i:s') . "\n" . json_encode($log_content) . $fg_str, FILE_APPEND);

        } else {
            file_put_contents($log_filename, date('Y-m-d H:i:s') . "\n" . $log_content . $fg_str, FILE_APPEND);

        }

    }

    /**
     * [数组分页,二维数组字段排序]
     * @param  [type]  $model      [description]
     * @param integer $p [description]
     * @param array $extend_map [description]
     * @return [type]              [description]
     * @author [yyh] <[email address]>
     */
    public function order_lists($model = null, $p = 0, $extend_map = array())
    {
        $model || $this->error('模型名标识必须!');
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $arraypage = $page; //默认显示第一页数据
        //获取模型信息
        $model = M('Model')->getByName($model);
        $model || $this->error('模型不存在!');
        //解析列表规则
        $fields = array();
        $grids = preg_split('/[;\r\n]+/s', trim($model['list_grid']));
        foreach ($grids as &$value) {
            if (trim($value) === '') {
                continue;
            }
            // 字段:标题:链接
            $val = explode(':', $value);
            // 支持多个字段显示
            $field = explode(',', $val[0]);
            $value = array('field' => $field, 'title' => $val[1]);
            if (isset($val[2])) {
                // 链接信息
                $value['href'] = $val[2];
                // 搜索链接信息中的字段信息
                preg_replace_callback('/\[([a-z_]+)\]/', function ($match) use (&$fields) {
                    $fields[] = $match[1];
                }, $value['href']);
            }
            if (strpos($val[1], '|')) {
                // 显示格式定义
                list($value['title'], $value['format']) = explode('|', $val[1]);
            }
            foreach ($field as $val) {
                $array = explode('|', $val);
                $fields[] = $array[0];
            }
        }

        $fields[] = 'grand_id';

        // 过滤重复字段信息
        $fields = array_unique($fields);
        // 关键字搜索
        $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;
        }


        //读取模型数据列表
        if ($model['extend']) {
            $name = get_table_name($model['id']);
            $parent = get_table_name($model['extend']);
            $fix = C("DB_PREFIX");

            $key = array_search('id', $fields);
            if (false === $key) {
                array_push($fields, "{$fix}{$parent}.id as id");
            } else {
                $fields[$key] = "{$fix}{$parent}.id as id";
            }

            /* 查询记录数 */
            $count = D($parent)->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")->where($map)->count();

            // 查询数据
            $data = D($parent)
                ->join("INNER JOIN {$fix}{$name} ON {$fix}{$parent}.id = {$fix}{$name}.id")
                /* 查询指定字段,不指定则查询所有字段 */
                ->field(empty($fields) ? true : $fields)
                // 查询条件
                ->where($map)
                /* 默认通过id逆序排列 */
                ->order("{$fix}{$parent}.id DESC")
                /* 数据分页 */
                // ->page($page, $row)  需要查询所有数据  后面用数组分页,原因: 页面要排序
                /* 执行查询 */
                ->select();

        } else {
            if ($model['need_pk']) {
                in_array('id', $fields) || array_push($fields, 'id');
            }
            $name = parse_name(get_table_name($model['id']), true);
            $data = D($name)
                /* 查询指定字段,不指定则查询所有字段 */
                ->field(empty($fields) ? true : $fields)
                // 查询条件
                ->where($map)
                /* 默认通过id逆序排列 */
                ->order(empty($map['order']) ? "id desc" : $map['order'])
                /* 数据分页 */
                // ->page($page, $row)//需要查询所有数据  后面用数组分页,原因: 页面要排序
                /* 执行查询 */
                ->select();
            /* 查询记录总数 */
            $count = count($data);
        }
        //分页

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

        $data = $this->parseDocumentList($data, $model['id']);
        if (isset($extend_map['for_show_pic_list'])) {
            if ($extend_map['for_show_pic_list'] == 'icon') {
                foreach ($data as $key => $value) {
                    $data[$key]['pic_path'] = get_cover($value['icon'], 'path');
                }
            }
            if ($extend_map['for_show_pic_list'] == 'novice') {
                foreach ($data as $key => $value) {
                    $data[$key]['novice'] = arr_count($value['novice']);
                }
            }
        }
        if ($_REQUEST['data_order'] != '') {
            $data_order = reset(explode(',', $_REQUEST['data_order']));
            $data_order_type = end(explode(',', $_REQUEST['data_order']));
            $this->assign('userarpu_order', $data_order);
            $this->assign('userarpu_order_type', $data_order_type);
        }

        $data = my_sort($data, $data_order_type, (int)$data_order);
        $size = $row;//每页显示的记录数
        $pnum = ceil(count($data) / $size); //总页数,ceil()函数用于求大于数字的最小整数
        //用array_slice(array,offset,length) 函数在数组中根据条件取出一段值;array(数组),offset(元素的开始位置),length(组的长度)
        $data = array_slice($data, ($arraypage - 1) * $size, $size);
        $this->assign('model', $model);
        $this->assign('list_grids', $grids);
        $this->assign('list_data', $data);
        $this->meta_title = $model['title'] . '列表';
        $this->display($model['template_list']);
    }

    /**
     * 处理文档列表显示
     * @param array $list 列表数据
     * @param integer $model_id 模型id
     */
    protected function parseDocumentList($list, $model_id = null)
    {
        $model_id = $model_id ? $model_id : 1;
        $attrList = get_model_attribute($model_id, false, 'id,name,type,extra');
        // 对列表数据进行显示处理
        if (is_array($list)) {
            foreach ($list as $k => $data) {
                foreach ($data as $key => $val) {
                    if (isset($attrList[$key])) {
                        $extra = $attrList[$key]['extra'];
                        $type = $attrList[$key]['type'];
                        if ('select' == $type || 'checkbox' == $type || 'radio' == $type || 'bool' == $type) {
                            // 枚举/多选/单选/布尔型
                            $options = parse_field_attr($extra);
                            if ($options && array_key_exists($val, $options)) {
                                $data[$key] = $options[$val];
                            }
                        } elseif ('date' == $type) { // 日期型
                            $data[$key] = date('Y-m-d', $val);
                        } elseif ('datetime' == $type) { // 时间型
                            $data[$key] = date('Y-m-d H:i:s', $val);
                        }
                    }
                }
                $data['model_id'] = $model_id;
                $list[$k] = $data;
            }
        }
        return $list;
    }

    public function shift()
    {
        $promoteService = new PromoteService();
        $result = $promoteService->addShiftTask($_POST);
        $this->ajaxReturn($result);
    }

    public function cancelShift()
    {
        $promoteService = new PromoteService();
        $result = $promoteService->cancelShift($_POST);
        $this->ajaxReturn($result);
    }

    public function downGame()
    {
        $gameId = $_POST['game_id'];
        $promoteId = $_POST['promote_id'];
        $applyService = new ApplyService();
        $applyService->cancelGame($gameId, $promoteId);
        $this->ajaxReturn(['status' => true, 'msg' => '下架成功']);
    }

    function ajax_page($count, $row, $ajax_func = 'index', $current = 1)
    {
        $aside = '<select id="pagechange" name="row" onchange="seach(this)"><option value="5">每页5条</option><option value="10">每页10条</option><option value="25">每页25条</option><option value="50">每页50条</option><option value="100">每页100条</option></select>';
        $count = $count ? $count : 0;
        $row = $row ? $row : 10;
        if ($count > $row) {
            $p = new \Think\AjaxPage($count, $row, $ajax_func);
            $p->nowpage($count, $row, $current, $ajax_func);
            $p->setConfig('theme', '%first% %upPage% %linkPage% %downPage% %end% %header%');
            //产生分页信息
            $html = $p->show();
            return "<div>" . $html . "</div>";
        } else {
            //return '<div>' .$aside. '<span class="rows">共 '.$count.' 条记录</span></div>';
            return '<div><span class="rows">共 ' . $count . ' 条记录</span></div>';
        }
    }

    public function setChildGamePermission()
    {
        $parentId = getParentPromoteId(PID);//上级ID
        if ($parentId > 0) {
            $this->error('权限异常');
        }

        //验证安全密码
        $metaTitle = '设置';
        $modelList = ['游戏管理', $metaTitle];
        $res = $this->verifyPasswordView($modelList, ($_POST ? false : true));

        if ($_POST) {
            if ($res === false) {
                $data['status'] = 0;
                $data['msg'] = '权限异常';
                $this->ajaxReturn($data);
            }

            $save['child_game_permission'] = I('post.child_game_permission');
            $saveRes = D('Promote')->where(array('id' => PID))->save($save);
            if ($saveRes === false) {
                $data['status'] = 0;
                $data['msg'] = '保存失败';
            } else {
                $data['status'] = 1;
                $data['msg'] = '保存成功';
            }

            $this->ajaxReturn($data);
        } else {
            $map['id'] = PID;
            $promoteData = D('Promote')->field('id,child_game_permission')->where($map)->find();

            $this->assign('data', $promoteData);
            $this->meta_title = $metaTitle;
            $this->assign('modelList', $modelList);
            $this->display();
        }
    }

    public function getSubPromotes()
    {
        $level = I('level', 0);
        $promoteId = I('promote_id', 0);
        $promote = $this->getLoginPromote();
        if ($promoteId > 0) {
            $promote = M('promote', 'tab_')->where(['id' => $promoteId])->find();
        }
        $map = ['chain' => ['like', $promote['chain'] . $promote['id'] . '/%']];
        if ($level > 0) {
            $map['level'] = $level;
        }
        $promotes = M('promote', 'tab_')->field(['id', 'account', 'real_name'])->where($map)->select();
        $this->ajaxReturn([
            'status' => 1,
            'msg' => '成功',
            'data' => ['promotes' => $promotes]
        ]);
    }
}