<?php

namespace Home\Controller;
use Think\Controller;
use App\Model\GameModel;
use User\Api\PromoteApi;
use Base\Repository\PromoteRepository;
use Base\Repository\SpendRepository;
use Base\Repository\UserRepository;
use Base\Service\PromoteService;
use Base\Facade\Request;
use Base\Service\ApplyService;

/**
 * @author elf<360197197@qq.com>
 */
class DownloadController extends BaseController {
    public  $payWay = [
        -1 => '绑币',
        0 => '平台币',
        1 => '支付宝',
        3 => '微信',
        5 => '聚宝云',
        6 => '竣付通',
        7 => '苹果支付',
        8 => '金猪支付',
        9 => '双乾支付',
    ];
    
     //提现状态
    public static $withdrawStatus = [
        -1 => '审核未通过',
        0 => '待审核',
        1 => '汇款中',
        2 => '已汇款',
    ];
    
    public function downloadError($message)
    {
        $this->assign('message', $message);
        $this->display('error');
    }

    public function index()
    {
        $code = I('code', '');
        $gameId = I('game_id', 0);
        $promoteId = I('promote_id', 0);

        if ($code == '' && ($gameId == 0 || $promoteId == 0)) {
            $this->redirect("download/downloadError", ['message' => '访问错误']);
        }

        $blackList = [];
        if (in_array($code, $blackList) || in_array('game_id/' . $gameId . '/promote_id/' . $promoteId, $blackList)) {
            $this->redirect("download/downloadError", ['message' => '该链接已被禁']);
        }
        if ($code != '') {
            $applyService = new ApplyService();
            $data = $applyService->decodeApplyCode($code);
            $result = $applyService->checkApplyCode($data, ApplyService::ENCRYPT_TYPE_DOWNLOAD);
            if (!$result['status']) {
                $this->error($result['message']);
            }
            
            $gameId = $data['game_id'];
            $promoteId = $data['promote_id'];
        }

        $map = [];
        $map['status'] = 1;
        $map['enable_status'] = 1;
        $map['game_id'] = $gameId;
        $map['promote_id'] = $promoteId;
        $columns = ['game_id', 'promote_id', 'promote_account', 'pack_url', 'plist_url', 'status', 'enable_status'];
        $apply = M('apply','tab_')->field($columns)->where($map)->find();
        $game = M('game','tab_')->field(['id', 'game_name', 'sdk_version'])->where(['id' => $apply['game_id']])->find();
        
        if (Request::isMobile()) {
            if (!Request::isAndroid() && $game['sdk_version'] == 1) {
                $this->redirect("download/downloadError", ['message' => '请使用安卓浏览器下载']);
            }
            if (!Request::isIOS() && $game['sdk_version'] == 2) {
                $this->redirect("download/downloadError", ['message' => '请使用ios浏览器下载']);
            }
        }
        $packageUrl = $game['sdk_version'] == 1 ? $apply['pack_url'] : $apply['plist_url'];

        M('game','tab_')->where(['id' => $game['id']])->setInc('dow_num');
        if (Request::isAndroid()) {
            $this->gotoPkgUrl($packageUrl);
        } else if (Request::isIOS()) {
            $plistUrl = substr($packageUrl, 1, strlen($packageUrl));
            header("HTTP/1.1 303 See Other");
            header("Location: "."itms-services://?action=download-manifest&url=" . Request::getHost() . "/" . $plistUrl);
        } else {
            $this->gotoPkgUrl($packageUrl);
        }
    }

    private function gotoPkgUrl($packageUrl)
    {
        if (preg_match("/oss/", $packageUrl)) {
            $url = str_replace('-internal', '', $packageUrl);
            echo "<script>window.location.href='$url';</script>";
        } elseif (preg_match("/clouddn/", $packageUrl)) {
            $url = "http://".$packageUrl;
            redirect($url);
        } elseif (preg_match("/myqcloud/", $packageUrl)) {
            redirect($packageUrl);
        } elseif(preg_match("/bcebos/", $packageUrl)) {
            redirect($packageUrl);
        } else {
            if (!file_exists($packageUrl)) {
                $this->error('文件不存在哦,亲!');
            }else{
                redirect(Request::getHost() . ltrim($packageUrl, '.'));
            }
        }
    }
    
    /**
    * excel
    */
    public function exportExcel($expTitle, $expCellName, $expTableData,$id)
    {
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
//        $fileName = session('user_auth.username').date('_YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
        $fileName = $expTitle.'_'.date('YmdHis');
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        Vendor("PHPExcel.PHPExcel");
        $objPHPExcel = new \PHPExcel();
        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1');//合并单元格
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle);
        $objPHPExcel->setActiveSheetIndex(0)->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
        for ($i = 0; $i < $cellNum; $i++) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '2', $expCellName[$i][1]);
        }
        for ($i = 0; $i < $dataNum; $i++) {
            for ($j = 0; $j < $cellNum; $j++) {
                $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j] . ($i + 3), $expTableData[$i][$expCellName[$j][0]]);
            }
        }
        ob_end_clean();//清除缓冲区,避免乱码
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        $this->backSuccessExport($id);
        exit;
    }
     
     public function listsIndex($p = 0) {
        $childPromoteIds = getAllChildPromoteList(3);
        if (empty($childPromoteIds)) {
            $map1['admin_id'] = PID;
            $promote = PID;
        } else {
            $childPromoteIds .= ','.PID;
            $map1['admin_id'] = ['in', $childPromoteIds];
            $promote = $childPromoteIds;
        }
        $pro = $_REQUEST['pid']; 
        if(empty($pro)) {
            $map['admin_id'] = $map1['admin_id'];
        }else {
            $map['admin_id'] = intval($pro);
        }
        if(!empty($_REQUEST['dataname'])) {
           $map['dataname'] = ['like','%'.$_REQUEST['dataname'].'%'];
        }
        if(!empty($_REQUEST['logid'])) {
           $map['logid'] = $_REQUEST['logid'];
        }
        if(!empty($_REQUEST['begtime']) && !empty($_REQUEST['endtime'])) {
           if(strtotime($_REQUEST['begtime']) == strtotime($_REQUEST['endtime'])) {
               $endtime = strtotime($_REQUEST['endtime']) + 24*60*60;
           }else {
               $endtime = strtotime($_REQUEST['endtime']);
           }
             $map['addtime'] = array('BETWEEN',array(strtotime($_REQUEST['begtime']),$endtime));
        }
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $row=10;
        $rs = M('downloadlog','tab_')->where($map)->order('tab_downloadlog.addtime desc')
            ->page($page, $row)->select();
        foreach ($rs as $key => $value) {
            $pid = intval($value['admin_id']);
            $getNameRs = M('promote','tab_')->field("real_name")->where(['id' => $pid])->find();
            $rs[$key]['actor'] = $getNameRs['real_name'];
        }
        
        $promoteArr = explode(',', $promote);
        $promoteNameArr = [];
        foreach ($promoteArr as $key1 => $value1) {
            $promoteName = M('promote','tab_')->field("real_name")->where(['id' => intval($value1)])->find();
            $promoteNameArr[$key1]['name'] = $promoteName['real_name'];
            $promoteNameArr[$key1]['promote_id'] = $value1;       
        }
        /* 查询记录总数 */
        $count = M("downloadlog", "tab_")
            ->field('tab_downloadlog.id')
            ->where($map)
            ->select();
        $count = count($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->assign('data',$rs);
        $this->assign('promoteNameArr',$promoteNameArr);
       return $this->display();  
     } 
     
     /**
    * 每日概况
    * @author sunke 
    */
     public function dailysummary_data_export() {
         $relationGameId = intval(I('relation_game_id', 0));
        $sdkVersion = intval(I('sdk_version', 0));
        $serverId = intval(I('server_id'), 0);
        $nowTime = date('Y-m-d');
        $initBegTime = date('Y-m-d', strtotime('-6 day', strtotime($nowTime)));
        $initBegTime = empty(I('begtime')) ? $initBegTime : I('begtime');
        $initEndTime = $nowTime;
        $initEndTime = empty(I('endtime')) ? $initEndTime : I('endtime');
        $begTime = strtotime($initBegTime);
        $endTime = strtotime($initEndTime);
        $endTime += +3600 * 24;
        $levelPromote = $this->getLevelPromote();
        $queryPromote = $this->getQueryPromote($levelPromote);

        $loginPromote = $this->getLoginPromote();
        $map1['chain'] = ['like','%'.PID.'/'.'%'];
        $rs = M('promote','tab_')->where($map1)->field('id,account,nickname')->select();
        $childPromoteIds = '';
        if(empty($rs)) {
            $map['tab_test_resource.promote_id'] = PID;
        }else {
             foreach ($rs as $rsKey => $rsValue) {
                $id = $rsValue['id'];
                $childPromoteIds .= $id.',';
            }
           $childPromoteIds = rtrim($childPromoteIds, ',');
           $childPromoteIds .= ',' . PID;
           $map['promote_id'] = ['in', $childPromoteIds];
        }
        
        $ownId = intval(I('own_id'), 0);//本账号
         if ($ownId) {
            $map['promote_id'] = $queryPromote['id'];
        } else {
            $map2['chain'] = ['like', $queryPromote['chain'] . $queryPromote['id'] . '/%'];
            $ids = M('promote', 'tab_')->where($map2)->getField('id', true);
            $ids[] = $queryPromote['id'];
            $ids = implode(',', $ids);
            $map['promote_id'] = $ids;
        }
         if ($serverId > 0) {
            $map['server_id'] = $serverId;
        }
         if ($relationGameId > 0 || $sdkVersion > 0) {
            if ($sdkVersion > 0) {
                $map['sdk_version'] = $sdkVersion;
            }
            if ($relationGameId > 0) {
                $map['relation_game_id'] = $relationGameId;
            }
             $gameIds = M('Game', 'tab_')->where($map)->getField('id', true);
             $map['gameIds'] = $gameIds;
        }
        
        $map['begin_time'] = $begTime;
        $map['end_time'] = $endTime;

        $dayList = $this->getDayList($begTime, $endTime);
        $map['dayList'] = $dayList;
        $conditions = json_encode($map,TRUE);
         $addtime = time();
         $data = [
             'logid' => 'dy_'.time(),
             'admin_id' => PID,
             'type' => '/Home/Query/dailySummary',
             'dataname' => '每日概况',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
         if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
        
        
     }
     
     /**
    * 提现记录
    * @author sunke 
    */
     public function withdrawRecord_data_export() {
        $withdrawNumber = I('widthdraw_number', '');
        $initBegTime = I('begtime', '');
        $initEndTime = I('endtime', '');
        $begTime = strtotime(date('Y-m-d', strtotime($initBegTime)));
        $endTime = strtotime(date('Y-m-d', strtotime($initEndTime))) + 3600 * 24;
        $status = '';
        $map['promote_id'] = $this->loginPromote['id'];
        if (!empty($withdrawNumber)) {
            $map['widthdraw_number'] = $withdrawNumber;
        } 
         if (!empty($initBegTime) && empty($initEndTime)) {
            $map['create_time'] = ['egt', $begTime];
        } elseif (empty($initBegTime) && !empty($initEndTime)) {
            $map['create_time'] = ['lt', $endTime];
        } elseif (!empty($initBegTime) && !empty($initEndTime)) {
            $map['create_time'] = ['between', [$begTime, $endTime - 1]];
        }
        
        if (isset($_GET['status']) && $_GET['status'] !== '') {
            $status = intval($_GET['status']);
            if (!isset(FinanceController::$withdrawStatus[$status])) {
                $this->error('参数异常');
            }

            $map['status'] = $status;
        }
        
         $conditions = json_encode($map,TRUE);
         $addtime = time();
         $data = [
             'logid' => 'withdrawRecord'.time(),
             'admin_id' => PID,
             'type' => '/Home/Finance/withdrawRecord',
             'dataname' => '提现记录',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
         if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
     }
     /**
    * 提现明细
    * @author sunke 
    */
     public function withdrawDtl_data_export() {
        $withdrawId = intval(I('get.id', 0));
        if ($withdrawId == 0) {
            $this->error('参数异常');
        }
        $withdraw = M('withdraw', 'tab_')->field('promote_id,status')->where(array('id' => $withdrawId))->find();
        if (empty($withdraw) || $withdraw['promote_id'] != $this->loginPromote['id']) {
            $this->error('参数异常');
        }
        $gameId = intval(I('game_id', 0));
        $userAccount = I('user_account', '');
        $payOrderNumber = I('pay_order_number', '');
         $map['withdraw_id'] = $withdrawId;
        if (!empty($gameId)) {
            $map['game_id'] = $gameId;
        }
        if (!empty($userAccount)) {
            $map['user_account'] = $userAccount;
        }
        if (!empty($payOrderNumber)) {
            $map['pay_order_number'] = $payOrderNumber;
        }
        
        $conditions = json_encode($map,TRUE);
         $addtime = time();
         $data = [
             'logid' => 'withdrawDtl_'.time(),
             'admin_id' => PID,
             'type' => '/Home/Finance/withdrawDtl',
             'dataname' => '提现明细',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
         if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
     }
     
     /**
    * 结算中心
    * @author sunke 
    */
     public function financeindex_data_export() {
        $thisDay = strtotime(date('Y-m-d'));
        $thisMonth = strtotime(date('Y-m'));
        $yesterday = strtotime(date('Y-m-d', strtotime('-1 day', time())));
        $nowTime = date('Y-m-d');
        $initBegTime = date('Y-m-d', strtotime('-6 day', strtotime($nowTime)));
        $initBegTime = empty(I('begtime')) ? $initBegTime : I('begtime');
        $initEndTime = $nowTime;
        $initEndTime = empty(I('endtime')) ? $initEndTime : I('endtime');
        $begTime = strtotime($initBegTime);
        $endTime = strtotime($initEndTime);
        $endTime = $endTime + 3600 * 24;
        $map['chain'] = ['like', $this->loginPromote['chain'] . $this->loginPromote['id'] . '/%'];
        $promoteIds = M('promote', 'tab_')->where($map)->getField('id', true);
        $promoteIds[] = $this->loginPromote['id'];
        $promoteIds = implode(',', $promoteIds);
        $map = [];
        $map['pay_status'] = 1;
        $map['promote_id'] = ['in', $promoteIds];
        $map['pay_time'] = ['between', [$begTime, $endTime]];
          
         $conditions = json_encode($map,TRUE);
         $addtime = time();
         $data = [
             'logid' => 'finance_'.time(),
             'admin_id' => PID,
             'type' => '/Home/Finance/index',
             'dataname' => '结算中心',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
         if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
     }
     
      /**
    * 结算明细
    * @author sunke 
    */
     public function settlementDtl_data_export() {
        $payOrderNumber = I('pay_order_number', '');
        $nowTime = date('Y-m-d');
        $initBegTime = date('Y-m-d', strtotime('-6 day', strtotime($nowTime)));
        $initBegTime = empty(I('begtime')) ? $initBegTime : I('begtime');
        $initEndTime = $nowTime;
        $initEndTime = empty(I('endtime')) ? $initEndTime : I('endtime');
        $begTime = strtotime($initBegTime);
        $endTime = strtotime($initEndTime);
        
        $map['chain'] = ['like', $this->loginPromote['chain'] . $this->loginPromote['id'] . '/%'];
        $ids = M('promote', 'tab_')->where($map)->getField('id', true);
        $ids[] = $this->loginPromote['id'];
        $ids = implode(',', $ids);
        $map = [];
        $map['promote_id'] = ['in', $ids];
        if (!empty($payOrderNumber)) {
            $map['pay_order_number'] = $payOrderNumber;
        }
        if (!empty($begTime) && empty($endTime)) {
            $map['pay_time'] = ['egt', $begTime];
        } elseif (empty($begTime) && !empty($endTime)) {
            $map['pay_time'] = ['elt', $endTime + 86399];
        } elseif (!empty($begTime) && !empty($endTime)) {
            $map['pay_time'] = ['between', [$begTime, $endTime + 86399]];
        }
         $conditions = json_encode($map,TRUE);
         $addtime = time();
         $data = [
             'logid' => 'settlementDtl_'.time(),
             'admin_id' => PID,
             'type' => '/Home/Finance/settlementDtl',
             'dataname' => '结算明细',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
         if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
        
     }
    /**
    * 测试资源
    * @author sunke 
    */
     public function testresource_data_export() {
         $map1['chain'] = ['like','%'.PID.'/'.'%'];
        $rs = M('promote','tab_')->where($map1)->field('id,account,nickname')->select();
        $childPromoteIds = '';
        if(empty($rs)) {
            $map['tab_test_resource.promote_id'] = PID;
        }else {
             foreach ($rs as $rsKey => $rsValue) {
                $id = $rsValue['id'];
                $childPromoteIds .= $id.',';
            }
           $childPromoteIds = rtrim($childPromoteIds, ',');
           $childPromoteIds .= ',' . PID;
           $map['tab_test_resource.promote_id'] = ['in', $childPromoteIds];
        }
        
         if(!empty(I('role_name'))){
            $map['role_name']=['like','%'.I('role_name').'%'];
        }
        if(!empty(I('server_name'))){
            $map['server_name']=I('server_name');
        }
        if(!empty(I('game_name'))){
            $map['game_name']=I('game_name');
        }
        if(!empty(I('user_account'))){
            $map['user_account']=['like','%'.I('user_account').'%'];
        }
        if(!empty($_REQUEST['start'])&&empty($_REQUEST['end'])){
            $map['create_time']  =  array('GT',strtotime($_REQUEST['start']));
            unset($_REQUEST['start']);
        }
        if(empty($_REQUEST['start'])&&!empty($_REQUEST['end'])){
            $map['create_time']  =  array('LT',strtotime($_REQUEST['end'])+24*60*60-1);
            unset($_REQUEST['end']);
        }
        if(!empty($_REQUEST['start'])&&!empty($_REQUEST['end'])){
            $map['create_time']  =  array('BETWEEN',array(strtotime($_REQUEST['start']),strtotime($_REQUEST['end'])+24*60*60-1));
            unset($_REQUEST['start']);unset($_REQUEST['end']);
        }
        
         $conditions = json_encode($map,TRUE);
         $addtime = time();
         $data = [
             'logid' => 'test_'.time(),
             'admin_id' => PID,
             'type' => '/Home/TestResource/index',
             'dataname' => '申请测试资源',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
         if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
     }
     
     /**
    * 测试资源申请记录
    * @author sunke 
    */
     public function testresourcelists_data_export() {
         $map1['chain'] = ['like','%'.PID.'/'.'%'];
        $rs = M('promote','tab_')->where($map1)->field('id,account,nickname')->select();
        $childPromoteIds = '';
        if(empty($rs)) {
            $map['tab_test_resource.promote_id'] = PID;
        }else {
             foreach ($rs as $rsKey => $rsValue) {
                $id = $rsValue['id'];
                $childPromoteIds .= $id.',';
            }
           $childPromoteIds = rtrim($childPromoteIds, ',');
           $childPromoteIds .= ',' . PID;
           $map['tab_test_resource.promote_id'] = ['in', $childPromoteIds];
        }
        
        if(!empty(I('type'))||I('type')==='0'){
            $map['apply_status']=I('type');
        }

        if(!empty(I('role_name'))){
            $map['role_name']=['like','%'.I('role_name').'%'];
        }
        if(!empty(I('server_name'))){
            $map['server_name']=I('server_name');
        }
        if(!empty(I('game_name'))){
            $map['game_name']=I('game_name');
        }
        if(!empty(I('user_account'))){
            $map['user_account']=['like','%'.I('user_account').'%'];
        }
        if(!empty($_REQUEST['start'])&&empty($_REQUEST['end'])){
            $map['create_time']  =  array('GT',strtotime($_REQUEST['start']));
            unset($_REQUEST['start']);
        }
        if(empty($_REQUEST['start'])&&!empty($_REQUEST['end'])){
            $map['create_time']  =  array('LT',strtotime($_REQUEST['end'])+24*60*60-1);
            unset($_REQUEST['end']);
        }
        if(!empty($_REQUEST['start'])&&!empty($_REQUEST['end'])){
            $map['create_time']  =  array('BETWEEN',array(strtotime($_REQUEST['start']),strtotime($_REQUEST['end'])+24*60*60-1));
            unset($_REQUEST['start']);unset($_REQUEST['end']);
        }
        //$data=M('test_resource','tab_')->where($map)->order('id desc')->select();
        $conditions = json_encode($map,TRUE);
         $addtime = time();
         $data = [
             'logid' => 'test_'.time(),
             'admin_id' => PID,
             'type' => '/Home/TestResource/lists',
             'dataname' => '申请测试资源记录',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
         if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
     }
     
     /**
    * 扶持号管理
    * @author sunke 
    */
     public function supportNumberList_data_export() {
         $map1['chain'] = ['like','%'.PID.'/'.'%'];
        $rs = M('promote','tab_')->where($map1)->field('id,account,nickname')->select();
        $childPromoteIds = '';
        if(empty($rs)) {
            $map['tab_test_resource.promote_id'] = PID;
        }else {
             foreach ($rs as $rsKey => $rsValue) {
                $id = $rsValue['id'];
                $childPromoteIds .= $id.',';
            }
           $childPromoteIds = rtrim($childPromoteIds, ',');
           $childPromoteIds .= ',' . PID;
           $map['tab_test_resource.promote_id'] = ['in', $childPromoteIds];
        }
        
      if(!empty(I('server_name'))){
          $map['tab_test_resource.server_name']=I('server_name');
      }
      if(!empty(I('game_name'))){
          $map['tab_test_resource.game_name']=I('game_name');
      }
      if(!empty(I('role_name'))){
          $map['tab_test_resource.role_name']=['like','%'.I('role_name').'%'];
      }
      if(!empty(I('user_account'))){
          $map['tab_test_resource.user_account']=['like','%'.I('user_account').'%'];
      }
      if(!empty(I('promote_id'))){
          $map['tab_test_resource.promote_id']=I('promote_id');
      }
      
       $conditions = json_encode($map,TRUE);
         $addtime = time();
         $data = [
             'logid' => 'test_'.time(),
             'admin_id' => PID,
             'type' => '/Home/TestResource/supportNumberList',
             'dataname' => '扶持号管理',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
         if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));

     }
     
      /**
    * arpu统计
    * @author sunke 
    */
     public function arpu_data_export() {
         $defaultTime = date('Y-m-d', time() - 6 * 24 * 3600) . ' 至 ' . date('Y-m-d');

        $time = I('time', '');
        $time = $time == '' ? $defaultTime : $time;
        $sdkVersion = I('sdk_version', 0);
        $gameId = I('game_id', 0);
        $serverId = I('server_id', 0);
        
        $map1['chain'] = ['like','%'.PID.'/'.'%'];
        $rs = M('promote','tab_')->where($map1)->field('id,account,nickname')->select();
        $childPromoteIds = '';
        if(empty($rs)) {
            $map['promote_id'] = PID;
        }else {
             foreach ($rs as $rsKey => $rsValue) {
                $id = $rsValue['id'];
                $childPromoteIds .= $id.',';
            }
           $childPromoteIds = rtrim($childPromoteIds, ',');
           $childPromoteIds .= ',' . PID;
           $map['promote_id'] = ['in', $childPromoteIds];
        }
        $levelPromote = $this->getLevelPromote();
        $queryPromote = $this->getQueryPromote($levelPromote);
         
        $map2[] = [
            '_logic' => 'or',
            'id' => $queryPromote['id'],
            'chain' => ['like', $queryPromote['chain'] . $queryPromote['id'] . '/%']
        ];
        $ids = M('promote', 'tab_')->where($map2)->getField('id', true);
        if(empty($ids)) {
           $ids = array();
        }
        if(empty($levelPromote)) {
            array_push($ids,PID);
            
        }
        array_push($ids,$queryPromote['id']);
        if (!empty($ids)) {
            $pro = "";
            foreach ($ids as $value1) {
                $pid = $value1;
                $pro .= $pid.','; 
            }
            $pro = rtrim($pro,',');
            $map['promote_id'] = ['in',$pro];
            
        }else {
            $map['_string'] = '1<>1';
        }
     
       $searchGameName = '';
        $searchServerName = '';
        if ($gameId > 0) {
            $map['game_id'] = $gameId;
            $searchGameName = M('game', 'tab_')->where(['id' => $gameId])->getField('game_name');
        }
        if ($serverId > 0) {
            $map['server_id'] = $serverId;
            $searchServerName = M('server', 'tab_')->where(['server_id' => $serverId])->getField('server_name');
        }
        if ($sdkVersion > 0) {
            $map['sdk_version'] = $sdkVersion;
        } 
        list($beginTime, $endTime) = $this->getBetweenTime($time);
        $map['begin_time'] = $beginTime;
        $map['end_time'] = $endTime;
        
        $dayList = $this->getDayList($beginTime, $endTime);
        $map['dayList'] = $dayList;
        $conditions = json_encode($map,TRUE);
         $addtime = time();
         $data = [
             'logid' => 'zc_'.time(),
             'admin_id' => PID,
             'type' => '/Home/Query/arpu',
             'dataname' => 'ARPU统计',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
         if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
        
    }            
     /**
    * 注册数据添加下载
    * @author sunke 
    */
     public function regist_data_export() {
         
        $map1['chain'] = ['like','%'.PID.'/'.'%'];
        $rs = M('promote','tab_')->where($map1)->field('id,account,nickname')->select();
        $childPromoteIds = '';
        if(empty($rs)) {
            $map['tab_user.promote_id'] = PID;
        }else {
             foreach ($rs as $rsKey => $rsValue) {
                $id = $rsValue['id'];
                $childPromoteIds .= $id.',';
            }
           $childPromoteIds = rtrim($childPromoteIds, ',');
           $childPromoteIds .= ',' . PID;
           $map['tab_user.promote_id'] = ['in', $childPromoteIds];
        }
        $levelPromote = $this->getLevelPromote();
        $queryPromote = $this->getQueryPromote($levelPromote);
         
        $map2[] = [
            '_logic' => 'or',
            'id' => $queryPromote['id'],
            'chain' => ['like', $queryPromote['chain'] . $queryPromote['id'] . '/%']
        ];
        $ids = M('promote', 'tab_')->where($map2)->getField('id', true);
        if(empty($ids)) {
           $ids = array();
        }
        if(empty($levelPromote)) {
            array_push($ids,PID);
            
        }
        array_push($ids,$queryPromote['id']);
        if (!empty($ids)) {
            $map['tab_user.promote_id'] = ['in',$ids];
            
        }else {
            $map['_string'] = '1<>1';
        }
        
        if (!empty(I('own_id'))) {
            $map['tab_user.promote_id'] = $queryPromote['id'];//本账号
        }

        if (!empty(I('begtime')) && empty(I('endtime'))) {
            $map['tab_user.register_time'] = ['egt', strtotime(I('begtime'))];
        } elseif (empty(I('begtime')) && !empty(I('endtime'))) {
            $map['tab_user.register_time'] = ['elt', strtotime(I('endtime')) + 86399];
        } elseif (!empty(I('begtime')) && !empty(I('endtime'))) {
            $map['tab_user.register_time'] = ['between', [strtotime(I('begtime')), strtotime(I('endtime')) + 86399]];
        }

        empty(I('account')) || $map['tab_user.account'] = ['like', '%' . I('account') . '%'];
        empty(I('id')) || $map['tab_user.id'] = intval(I('id'));
         $conditions = json_encode($map,TRUE);
         $addtime = time();
         $data = [
             'logid' => 'zc_'.time(),
             'admin_id' => PID,
             'type' => '/Home/Query/registe',
             'dataname' => '注册明细数据',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
         if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
     }
     
     //渠道管理
     public function children_data_export() {
        $promoteType = intval(I('promote_type', 0));
        $loginer = $this->getLoginPromote();
        $map1['chain'] = ['like','%'.PID.'/'.'%'];
        $rs = M('promote','tab_')->where($map1)->field('id,account,nickname')->select();
        $childPromoteIds = '';
        if(empty($rs)) {
            $map['promote_id'] = PID;
        }else {
             foreach ($rs as $rsKey => $rsValue) {
                $id = $rsValue['id'];
                $childPromoteIds .= $id.',';
            }
           $childPromoteIds = rtrim($childPromoteIds, ',');
           $childPromoteIds .= ',' . PID;
           $map['promote_id'] = ['in', $childPromoteIds];
        }
        
        if ($promoteType == 0) {
            $map['level'] = 2;
        } elseif ($promoteType == 1) {
            $map['level'] = 3;
        } elseif ($promoteType == 2) {
            $map['level'] = 4;
        }
        if(I('account', '')) {
            $map['account'] = ['like', '%' . I('account', '') . '%'];
        }
         if (I('mobile', '')) {
            $map['mobile_phone'] = ['like', '%' . I('mobile', '') . '%'];
        }
        if (I('idcard', '')) {
            $map['idcard'] = ['like', '%' . I('idcard', '') . '%'];
        }
        if (I('real_name', '')) {
            $map['real_name'] = ['like', '%' . I('real_name', '') . '%'];
        }
        if (I('status', 'all') != 'all') {
            $map['status'] = ['eq', I('status', 'all')];
        }
         $conditions = json_encode($map,TRUE);           
         $addtime = time();
         $type = "/Home/Promote/children/promote_type/".$promoteType;
         $data = [
             'logid' => 'cz_'.time(),
              'admin_id' => PID,
             'type' => $type,
             'dataname' => '渠道管理',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
        if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
         
     }
     
      /**
    * 平台币转移
    * @author sunke 
    */
     public function coinrecord_data_export() {
        $map1['chain'] = ['like','%'.PID.'/'.'%'];
        $rs = M('promote','tab_')->where($map1)->field('id,account,nickname')->select();
        $childPromoteIds = '';
        if(empty($rs)) {
            $map['promote_id'] = PID;
        }else {
             foreach ($rs as $rsKey => $rsValue) {
                $id = $rsValue['id'];
                $childPromoteIds .= $id.',';
            }
           $childPromoteIds = rtrim($childPromoteIds, ',');
           $childPromoteIds .= ',' . PID;
           $map['promote_id'] = ['in', $childPromoteIds];
        }
        $map["type"] = 2;
        $end_time = strtotime(I('time_end'));
        $start_time = strtotime(I('time_start'));
        if (!empty($end_time) && !empty($start_time)) {
            $map['create_time'] = ['between', [$start_time, $end_time + 86400 - 1]];
        } elseif (!empty($start_time)) {
            $map['create_time'] = array('gt', $start_time);
        } elseif (!empty($end_time)) {
            $map['create_time'] = array('lt', $end_time + 86400 - 1);
        }
        
        $account = I('account');
        $sn = I('sn');
        if($sn) {
            $map['sn'] = ['like','%'.$sn.'%'];
        }
        if($account) {
             $searchUsers = M('User', 'tab_')->field('id')->where(['account' => ['like', '%' . $account . '%']])->select();
            $searchPromotes = M('Promote', 'tab_')->field('id')->where(['account' => ['like', '%' . $account . '%']])->select();
            if (empty($searchUsers) && empty($searchPromotes)) {
                $map['_string'] = '1<>1';
            }
            if (empty($searchUsers) && !empty($searchPromotes)) {
                $map['source_id'] = ['in', array_column($searchPromotes, 'id')];
            }
            if (!empty($searchUsers) && empty($searchPromotes)) {
                $map['source_id'] = ['in', array_column($searchUsers, 'id')];
            }
            if (!empty($searchUsers) && !empty($searchPromotes)) {
                $map['_string'] = '(source_id in (' . implode(',', array_column($searchUsers, 'id')) . ') or'
                    . '(source_id in (' . implode(',', array_column($searchPromotes, 'id')) . '))';
            }
        }
        
         $searchHandleType = I('handle_type', 0);
        if ($searchHandleType) {
            if ($searchHandleType == 2) {
                $map['source_type'] = 2;
            } else {

            }
        }
        $searchGameId = I('game_id', -1);
        if ($searchGameId != -1) {
            $map['game_id'] = $searchGameId;
        }
        
         $conditions = json_encode($map,TRUE);           
         $addtime = time();
         $type = "/Home/PromoteCoin/record";
         $data = [
             'logid' => 'cr_'.time(),
              'admin_id' => PID,
             'type' => $type,
             'dataname' => '平台币转移',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
        if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
        
        
     }
     
      /**
    * 我的平台币明细
    * @author sunke 
    */
     public function mycoinrecord_data_export() {
        $map['tab_promote_coin_record.target_id'] = PID;
        empty(I('type')) || $map['tab_promote_coin_record.type'] = I('type');
        empty(I('sub_type')) || $map['tab_promote_coin_record.sub_type'] = I('sub_type');

        if (!empty(I('start_time')) && empty(I('end_time'))) {
            $map['tab_promote_coin_record.create_time'] = ['egt', strtotime(I('start_time'))];
        } elseif (empty(I('start_time')) && !empty(I('end_time'))) {
            $map['tab_promote_coin_record.create_time'] = ['elt', strtotime(I('end_time')) + 86399];
        } elseif (!empty(I('start_time')) && !empty(I('end_time'))) {
            $map['tab_promote_coin_record.create_time'] = ['between', [strtotime(I('start_time')), strtotime(I('end_time')) + 86399]];
        }
        
         $having = '';
        $where['_string'] = '1 = 1';
        if (empty(I('get.game_id'))) {
            $where['_logic'] = 'or';
            $join = 'left join tab_promote_coin on tab_promote_coin_record.ref_id = tab_promote_coin.id and tab_promote_coin_record.sub_type > 2 and tab_promote_coin.banlan_type = 1';
            $having = '(coin_id > 0 or pay_id > 0)';
        } else {
            $where['tab_promote_coin_record.sub_type'] = ['gt', 2];
            $join = 'inner join tab_promote_coin on tab_promote_coin_record.ref_id = tab_promote_coin.id and tab_promote_coin.banlan_type = 2 and tab_promote_coin.game_id = ' . I('get.game_id');
        }
        
        if (!empty(I('handle_type'))) {
            switch (I('handle_type')) {
                case 1:
                    $where['tab_promote_coin.source_type'] = 1;
                    $join .= ' inner join tab_promote on tab_promote_coin.source_id = tab_promote.id and tab_promote.parent_id = 0';
                    break;
                case 2:
                    $where['tab_promote_coin.source_type'] = 1;
                    $join .= ' inner join tab_promote on tab_promote_coin.source_id = tab_promote.id and tab_promote.parent_id > 0 and tab_promote.grand_id = 0';
                    break;
                case 3:
                    $where['tab_promote_coin.source_type'] = 1;
                    $join .= ' inner join tab_promote on tab_promote_coin.source_id = tab_promote.id and tab_promote.grand_id > 0';
                    break;
                case 4:
                    $where['tab_promote_coin.source_type'] = 2;
                    break;
            }
        }

        $join .= ' left join tab_coin_pay_order on tab_promote_coin_record.ref_id = tab_coin_pay_order.id and tab_promote_coin_record.sub_type in (1,2)';
        $map['_complex'] = $where;
        $conditions = json_encode($map,TRUE);           
         $addtime = time();
         $type = "/Home/PromoteCoin/coinRecord";
         $data = [
             'logid' => 'pt_'.time(),
              'admin_id' => PID,
             'type' => $type,
             'dataname' => '我的平台币明细',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
        if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
        
        
     }
     /**
    * 我的平台币
    * @author sunke 
    */
     public function mycoin_data_export() {
        $map1['chain'] = ['like','%'.PID.'/'.'%'];
        $rs = M('promote','tab_')->where($map1)->field('id,account,nickname')->select();
        $childPromoteIds = '';
        if(empty($rs)) {
            $map['promote_id'] = PID;
        }else {
             foreach ($rs as $rsKey => $rsValue) {
                $id = $rsValue['id'];
                $childPromoteIds .= $id.',';
            }
           $childPromoteIds = rtrim($childPromoteIds, ',');
           $childPromoteIds .= ',' . PID;
           $map['promote_id'] = ['in', $childPromoteIds];
        }
       // var_dump($map);
        $game_id = I('game_id');
        if(!empty($game_id)) {
            $map['game_id'] = $game_id;
        }
        $status = I("status");
        if(!empty($status)) {
           $map['status'] = $status;
        }
        $coin_type = I('coin_type');
        if(!empty($coin_type)) {
            switch ($coin_type) {
                case 1:
                    $map['game_id'] = 0;
                    break;
                case 2:
                    $map['game_id'] = ["gt",0];
                    break;
            }
        }
        
         $conditions = json_encode($map,TRUE);           
         $addtime = time();
         $type = "/Home/PromoteCoin/myCoin";
         $data = [
             'logid' => 'pt_'.time(),
              'admin_id' => PID,
             'type' => $type,
             'dataname' => '我的平台币',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
        if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
     }
     /**
    * 充值明细添加下载
    * @author sunke 
    */
     public function recharge_data_export() {
         
        $map1['chain'] = ['like','%'.PID.'/'.'%'];
        $rs = M('promote','tab_')->where($map1)->field('id,account,nickname')->select();
        $childPromoteIds = '';
        if(empty($rs)) {
            $map['tab_spend.promote_id'] = PID;
        }else {
             foreach ($rs as $rsKey => $rsValue) {
                $id = $rsValue['id'];
                $childPromoteIds .= $id.',';
            }
           $childPromoteIds = rtrim($childPromoteIds, ',');
           $childPromoteIds .= ',' . PID;
           $map['tab_spend.promote_id'] = ['in', $childPromoteIds];
        }

         $levelPromote = $this->getLevelPromote();
        $queryPromote = $this->getQueryPromote($levelPromote);
         
        $map2[] = [
            '_logic' => 'or',
            'id' => $queryPromote['id'],
            'chain' => ['like', $queryPromote['chain'] . $queryPromote['id'] . '/%']
        ];
        $ids = M('promote', 'tab_')->where($map2)->getField('id', true);
        if(empty($ids)) {
           $ids = array();
        }
        if(empty($levelPromote)) {
            array_push($ids,PID);
            
        }
        array_push($ids,$queryPromote['id']);
        if (!empty($ids)) {
            $map['tab_spend.promote_id'] = ['in',$ids];
            
        }else {
            $map['_string'] = '1<>1';
        }
        
        if (!empty(I('own_id'))) {
            $map['tab_spend.promote_id'] = $queryPromote['id'];//本账号
        }

        
        
         if (!empty(I('begtime')) && empty(I('endtime'))) {
            $map['tab_spend.pay_time'] = ['egt', strtotime(I('begtime'))];
        } elseif (empty(I('begtime')) && !empty(I('endtime'))) {
            $map['tab_spend.pay_time'] = ['elt', strtotime(I('endtime')) + 86399];
        } elseif (!empty(I('begtime')) && !empty(I('endtime'))) {
            $map['tab_spend.pay_time'] = ['between', [strtotime(I('begtime')), strtotime(I('endtime')) + 86399]];
        }
        
        empty(I('relation_game_id')) || $map['tab_game.relation_game_id'] = I('relation_game_id');
        empty(I('sdk_version')) || $map['tab_game.sdk_version'] = I('sdk_version');
        empty(I('server_id')) || $map['tab_spend.server_id'] = I('server_id');
        empty(I('game_player_name')) || $map['tab_spend.game_player_name'] = ['like', '%' . I('game_player_name') . '%'];
        empty(I('user_account')) || $map['tab_spend.user_account'] = ['like', '%' . I('user_account') . '%'];
        empty(I('order_number')) || $map['tab_spend.order_number'] = I('order_number');
        $map['tab_spend.pay_status'] = 1;
        $map['tab_spend.is_check'] = ['neq', 2];
        
        $conditions = json_encode($map,TRUE);           
         $addtime = time();
         $data = [
             'logid' => 'cz_'.time(),
              'admin_id' => PID,
             'type' => '/Home/Query/recharge',
             'dataname' => '充值明细数据',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
         if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
     }
     
     public function userRecharge_data_export() {
        $gameId = I('game_id', 0);
        $serverId = I('server_id', 0);
        $isSelf = I('is_self', 0);
        $roleName = I('role_name', '');
        $userAccount = I('user_account', '');
        $promoteId = I('promote_id', 0);
        $sdkVersion = I('sdk_version', 0);
        $headmanPromoteId = I('headman_promote_id', 0);
        $map1['chain'] = ['like','%'.PID.'/'.'%'];
        $rs = M('promote','tab_')->where($map1)->field('id,account,nickname')->select();
        $childPromoteIds = '';
        if(empty($rs)) {
            $map['promote_id'] = PID;
        }else {
             foreach ($rs as $rsKey => $rsValue) {
                $id = $rsValue['id'];
                $childPromoteIds .= $id.',';
            }
           $childPromoteIds = rtrim($childPromoteIds, ',');
           $childPromoteIds .= ',' . PID;
           $map['promote_id'] = ['in', $childPromoteIds];
        }
        $levelPromote = $this->getLevelPromote();
        $queryPromote = $this->getQueryPromote($levelPromote);
         
        $map2[] = [
            '_logic' => 'or',
            'id' => $queryPromote['id'],
            'chain' => ['like', $queryPromote['chain'] . $queryPromote['id'] . '/%']
        ];
        $ids = M('promote', 'tab_')->where($map2)->getField('id', true);
        if(empty($ids)) {
           $ids = array();
        }
        if(empty($levelPromote)) {
            array_push($ids,PID);     
        }
        array_push($ids,$queryPromote['id']);
        if (!empty($ids)) {
            $map['promote_id'] = ['in',$ids];
            
        }else {
            $map['_string'] = '1<>1';
        }
        
        if ($gameId != 0) {
            $map['game_id'] = $gameId;
        }
        if ($serverId != 0) {
            $map['server_id'] = $serverId;
        }
        if ($roleName != '') {
            $map['role_name'] = ['like', '%' . $roleName . '%'];
        }
        if ($userAccount != '') {
            $map['user_account'] = ['like', '%' . $userAccount . '%'];
        }
        if ($sdkVersion != 0) {
            $map['sdk_version'] = $sdkVersion;
        }
        if ($isSelf) {
            $map['promote_id'] = $queryPromote['id'];//本账号
        } else {
            if ($headmanPromoteId != 0) {
                $map['promote_id'] = $headmanPromoteId;
            }
            if ($promoteId != 0) {
                $map['promote_id'] = $promoteId;
            }
        }

        $conditions = json_encode($map,TRUE);
         $addtime = time();
         $data = [
             'logid' => 'wj_'.time(),
             'admin_id' => PID,
             'type' => '/Home/Query/userRecharges',
             'dataname' => '充值玩家数据',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
         if (!$res) {
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
        
     }
     
     public function achievement_data_export() { 
        $time = I('time', date('Y-m-d'));
        $sdkVersion = I('sdk_version', 0);
        $gameId = I('game_id', 0);
        $serverId = I('server_id', 0);
        $parentId = I('parent_id', 0);
        $promoteId = I('promote_id', 0);
        $status = I('status', 0);
        $searchLevel = 0;
        $searchLevelName = '';
        $currentDisplay = '';
        $prevParentId = 0;
        $promoteService = new PromoteService();
        $loginPromote = $this->getLoginPromote();
        $parent = null;
        if ($parentId > 0) {
            $parent = M('promote', 'tab_')->where(['id' => $parentId])->find();
            $currentDisplay = $promoteService->getLevelName($parent['level']) . '推广';
            $prevParentId = $parent['parent_id'] == $loginPromote['parent_id'] ? 0 : $parent['parent_id'];
        } else {
            $parent = $loginPromote;
            $currentDisplay = '自己';
        }
        $map = ['parent_id' => $parent['id']];
        if ($promoteId > 0) {
            $map['id'] = $promoteId;
        }
        $data = M('promote', 'tab_')->field(['id', 'account', 'real_name', 'level'])->where($map)->select();
        $ids = array_column($data, 'id'); 
        $rows = [];
        if (count($ids) > 0) {
            $rows = M('promote', 'tab_')->field(['id', 'parent_id'])->where(['parent_id' => ['in', $ids]])->select();
        }
        $basicPromotes = [];
        foreach ($rows as $row) {
            $basicPromotes[$row['id']] = $row['parent_id'];
        }
        $map = [
            'isContainSubs' => true,
            'basicPromotes' => json_encode($basicPromotes,FALSE),
        ];
        $map['promotes'] = json_encode($data,FALSE);
         $map['ids'] = $ids;
        if ($gameId > 0) {
            $params['game_id'] = $gameId;
        }
        if ($serverId > 0) {
            $params['server_id'] = $serverId;
        }
        if ($sdkVersion > 0) {
            $params['sdk_version'] = $sdkVersion;
        }
        if ($status > 0) {
            $params['lock_status'] = $status;
        }
        list($beginTime, $endTime) = $this->getBetweenTime($time);
        $map['begin_time'] = $beginTime;
        $map['end_time'] = $endTime;
        $conditions = json_encode($map,TRUE);
         $addtime = time();
         $data1 = [
             'logid' => 'tg_'.time(),
             'admin_id' => PID,
             'type' => '/Home/Query/achievement',
             'dataname' => '推广员业绩',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data1);
         if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
        
     }
     //玩家角色
     public function userRoles_data_export() {
       $gameId = I('game_id', 0);
        $serverId = I('server_id', 0);
        $isSelf = I('is_self', 0);
        $roleName = I('role_name', '');
        $userAccount = I('user_account', '');
        $promoteId = I('promote_id', 0);
        $sdkVersion = I('sdk_version', 0);
        $roleLevelBegin = intval(I('role_level_begin', 0));
        $roleLevelEnd = intval(I('role_level_end', 0));
        $headmanPromoteId = I('headman_promote_id', 0);
        $playTime = I('play_time', '');
        $promote = $this->getLoginPromote();
         $map1['chain'] = ['like','%'.PID.'/'.'%'];
        $rs = M('promote','tab_')->where($map1)->field('id,account,nickname')->select();
        $childPromoteIds = '';
        if(empty($rs)) {
            $map['tab_user.promote_id'] = PID;
        }else {
             foreach ($rs as $rsKey => $rsValue) {
                $id = $rsValue['id'];
                $childPromoteIds .= $id.',';
            }
           $childPromoteIds = rtrim($childPromoteIds, ',');
           $childPromoteIds .= ',' . PID;
           $map['promote_id'] = ['in', $childPromoteIds];
        }
        
        $levelPromote = $this->getLevelPromote();
        $queryPromote = $this->getQueryPromote($levelPromote);
         
        $map2[] = [
            '_logic' => 'or',
            'id' => $queryPromote['id'],
            'chain' => ['like', $queryPromote['chain'] . $queryPromote['id'] . '/%']
        ];
        $ids = M('promote', 'tab_')->where($map2)->getField('id', true);
        if(empty($ids)) {
           $ids = array();
        }
        if(empty($levelPromote)) {
            array_push($ids,PID);
            
        }
        array_push($ids,$queryPromote['id']);
        if (!empty($ids)) {
            $map['promote_id'] = ['in',$ids];
            
        }else {
            $map['_string'] = '1<>1';
        }
        

        if ($gameId != 0) {
            $map['game_id'] = $gameId;
        }
        if ($serverId != 0) {
            $map['serverId'] = $serverId;
        }
        if ($roleName != '') {
            $map['role_name'] = ['like', '%' . $roleName . '%'];
        }
        if ($userAccount != '') {
            $map['user_account'] = ['like', '%' . $userAccount . '%'];
        }
        if ($sdkVersion != 0) {
            $map['sdk_version'] = $sdkVersion;
        }
        if ($roleLevelBegin != 0 && $roleLevelEnd == 0) {
            $map['role_level'] = ['egt', $roleLevelBegin];
        } elseif ($roleLevelEnd != 0 && $roleLevelBegin == 0) {
            $map['role_level'] = ['elt', $roleLevelEnd];
        } elseif ($roleLevelEnd != 0 && $roleLevelBegin != 0) {
            $map['role_level'] = ['between', [$roleLevelBegin, $roleLevelEnd]];
        }
        if ($playTime != '') {
            $playTimeRow = explode(' 至 ', $playTime);
            $playTimeBegin = 0;
            $playTimeEnd = 0;
            if (count($playTimeRow) == 2) {
                $playTimeBegin = strtotime($playTimeRow[0] . ' 00:00:00');
                $playTimeEnd = strtotime($playTimeRow[1] . ' 23:59:59');
            } else {
                $playTimeBegin = strtotime($playTimeRow[0] . ' 00:00:00');
                $playTimeEnd = strtotime($playTimeRow[0] . ' 23:59:59');
            }
            $map['play_time'] = ['between', [$playTimeBegin, $playTimeEnd]];
        }
        if ($isSelf) {
            $map['promote_id'] = $queryPromote['id'];
        } else {
            if ($headmanPromoteId != 0) {
                $map['promote_id'] = $headmanPromoteId;
            }
            if ($promoteId != 0) {
                $map['promote_id'] = $promoteId;
            }
        }
        
        
        $conditions = json_encode($map,TRUE);
         $addtime = time();
         $data = [
             'logid' => 'js_'.time(),
             'admin_id' => PID,
             'type' => '/Home/Query/userRoles',
             'dataname' => '角色查询数据',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
         if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));
        
        
     }
       /**
    * 数据汇总添加下载
    * @author sunke 
    */
     public function summary_data_export() {
        $promoteId = I('promote_id',0);
        $teamLeaderId = I('team_leader_id',0);
        $own_id = I('own_id',0);
        $relation_game_id = I('relation_game_id',0);
        $sdk_version = I('sdk_version',0);
        $begtime = I('begtime','');
        $endtime = I('endtime','');
      //  $childPromoteIds = getAllChildPromoteList(3);
        $map1['chain'] = ['like','%'.PID.'/'.'%'];
        $rs = M('promote','tab_')->where($map1)->field('id,account,nickname')->select();
        $childPromoteIds = '';
        if(empty($rs)) {
            $map['tab_user.promote_id'] = PID;
        }else {
             foreach ($rs as $rsKey => $rsValue) {
                $id = $rsValue['id'];
                $childPromoteIds .= $id.',';
            }
           $childPromoteIds = rtrim($childPromoteIds, ',');
           $childPromoteIds .= ',' . PID;
           $map['tab_apply.promote_id'] = ['in', $childPromoteIds];
        }
        $levelPromote = $this->getLevelPromote();
        $queryPromote = $this->getQueryPromote($levelPromote);
        $map2[] = [
            '_logic' => 'or',
            'id' => $queryPromote['id'],
            'chain' => ['like', $queryPromote['chain'] . $queryPromote['id'] . '/%']
        ];
        $ids = M('promote', 'tab_')->where($map2)->getField('id', true);
        if(empty($ids)) {
           $ids = array();
        }
        if(empty($levelPromote)) {
            array_push($ids,PID);
            
        }
        array_push($ids,$queryPromote['id']);
        if (!empty($ids)) {
            $map['tab_apply.promote_id'] = ['in',$ids];
            
        }else {
            $map['_string'] = '1<>1';
        }
    
        if (!empty($own_id)) {
            if (!empty($map['_string'])) {
                unset($map['_string']);
                unset($userPlayInfoWhere['_string']);
                unset($userGameLoginWhere['_string']);
                unset($spendWhere['_string']);
            }

            $map['tab_apply.promote_id'] = $queryPromote['id'];//本账号

        }
        empty($relation_game_id) || $map['tab_game.relation_game_id'] = $relation_game_id;
        empty($sdk_version) || $map['tab_game.sdk_version'] = $sdk_version;
        if(!empty($begtime) && !empty($endtime)) {
            $map["apply_time"] = ["between",[$begtime,$endtime]];
        }
        $serverField = '';
        $serverJoin = '';
        if (!empty(I('server_id'))) {
            $map['tab_server.id'] = I('server_id');
        }
   
         $conditions = json_encode($map,TRUE);
         $addtime = time();
         $data = [
             'logid' => 'hz_'.time(),
             'admin_id' => PID,
             'type' => '/Home/Query/summary',
             'dataname' => '数据汇总数据',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions
         ];
         $res = M('downloadlog','tab_')->add($data);
         if (!$res) {
              //  $this->ajaxReturn(array("status" => -1, "msg" => "添加导出日志失败", 'ret' => $res));
             $this->error('添加下载失败');
            }
        $this->success('添加下载成功',U('listsIndex'));
     }
     
     /*
      * 开始导出数据
      */
     public function export() {             //开始导出
         $id = $_REQUEST['id'];
         $dataname = $_REQUEST['dataname'];
         $downloadStatus = M('downloadlog','tab_')->where(['id'=>$id])->field('status')->select();
         if($downloadStatus[0]['status'] == 1) {
             $this->error("该数据已下载请重新添加",U('listsIndex'));
         }
         $conditions = $_REQUEST['conditions'];
         $map = array();
         foreach (json_decode($conditions,FALSE) as $key => $value) {
            if($value !== 0 && $value !== "" ) {
                 $map[$key] = $value;
            }
         }
        switch ($dataname) {
            case  "注册明细数据":
                $this->registerExcelInfo($id,$map);         //注册明细
                break;
            case "角色查询数据":
                $this->userRolesExcelInfo($id,$map);          //角色查询
                break;
            case "数据汇总数据":
                $this->summaryExcelInfo($id,$map);
                break;
            case "充值明细数据":
                $this->rechargeExcelInfo($id,$map);
                break;   
            case "充值玩家数据":
                $this->userRechargeExcelInfo($id,$map);
                break;
            case "推广员业绩":
                $this->achievementExcelInfo($id,$map);
                break;
            case "渠道管理":
                $this->childrenExcelInfo($id,$map);
                break;
            case "我的平台币":
                $this->mycoinExcelInfo($id,$map);
                break;
            case "我的平台币明细";
                $this->mycoinRecordExcelInfo($id, $map);
                break;
            case "平台币转移":
                $this->coinrecordExcelInfo($id,$map);
                break;
            case "申请测试资源":
                $this->testresourceExcelInfo($id,$map);
                break;
            case "申请测试资源记录":
                $this->testresourcelistExcelInfo($id, $map);
                break;
            case "扶持号管理":
                $this->supportNumberListExcelInfo($id, $map);
                break;
            case "ARPU统计":
                $this->arpuExcelInfo($id,$map);
                break;
            case "每日概况":
                $this->dailysummaryExcelInfo($id,$map);
                break;
            case "结算中心":
                $this->financeindexExcelInfo($id,$map);
                break;
            case "结算明细":
                $this->settlementExcelInfo($id,$map);
                break;
            case "提现记录":
                $this->withdrawRecordExcelInfo($id,$map);
                break;
            case "提现明细":
                $this->withdrawDtlExcelInfo($id,$map);
                break;
            case "汇款证明":
                $this->remitCerDownLoad($id,$map);
                break;
            default:
                break;
        }
     }
     
     //注册明细excel信息
     public function registerExcelInfo($id,$map) {
         $xlsName = "注册明细";
         $xlsCell = array(
		array('account','玩家账号'),
		array('promote_account','推广账号'),
		array('register_time','注册时间'),
		array('register_ip','注册ip'),
                array('login_time','登陆时间'),
                array('login_ip','登陆ip')
	);
        $model = M('user','tab_');
        
        $data = $model->field('account,promote_account,register_time,register_ip,login_time,login_ip')->where($map)->select();
        //var_dump($data);
        $xlsData = [];
        foreach ($data as $key1 => $value1) {
           $xlsData[] = $value1;
        }
        $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);
     }
     
     //玩家角色excel信息
     public function userRolesExcelInfo($id,$map) {
          $xlsName = "角色查询";
         $xlsCell = array(
		array('user_account','玩家账号'),
		array('promote_account','推广账号'),
		array('game_name','游戏名称'),
		array('server_name','区服'),
                array('user_nickname','游戏昵称'),
                array('role_level','等级'),
	);
        $model = M('user_play_info','tab_');
        $data = $model->field('user_account,promote_account,game_name,server_name,user_nickname,role_level')->where($map)->select();
        $xlsData = [];
        foreach ($data as $key1 => $value1) {
           $xlsData[] = $value1;
        }
        $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);
     }
     
      //数据汇总excel信息
     public function summaryExcelInfo($id,$map) {
          $xlsName = "数据汇总";
         $xlsCell = array(
		array('game_name','游戏名称'),
		array('sdk_version','平台'),
		array('role_num','创角数'),
		array('user_num','创建用户'),
                array('new_user_num','新创角用户'),
                array('new_device_num','新创角设备'),
                array('new_ip_num','新增创角ip'),
                array('login_user_num','登陆用户数'),
                array('spend_user_num','充值人数'),
                array('spend_num','充值次数'),
                array('spend_all_amount','充值总额'),
                array('spend_cash','现金充值'),
                array('spend_generic','通用币充值'),
                array('spend_binding','绑定币充值'),
                array('spend_discount','折扣币充值'),
                array('spend_voucher','代金券使用'),
             
             
	);
         if(!empty($map['tab_apply.promote_id'][1])) {
             $params['promote_ids'] = $map['tab_apply.promote_id'][1];
         }
         $serverJoin = '';
        $initBegTime = date('Y-m-d', strtotime('-6 day', strtotime($nowTime)));
        $initBegTime = empty(I('begtime')) ? $initBegTime : I('begtime');
        $initEndTime = $nowTime;
        $initEndTime = empty(I('endtime')) ? $initEndTime : I('endtime');
        $begTime = strtotime($initBegTime);
        $endTime = strtotime($initEndTime);
        $params['begin_time'] = $begTime;
        $params['end_time'] = $endTime;
         if(!empty($map['apply_time'][1])) {
             $begTime = $map['apply_time'][1][0];
             $endTime = $map['apply_time'][1][1];
             $params['begin_time'] = $begTime;
             $params['end_time'] = $endTime;
             unset($map['apply_time']);
         }
         if(!empty($map['tab_server.server_id'])) {
             $serverJoin = 'tab_server on tab_server.game_id = tab_apply.game_id';
             $params['server_id'] = $map['tab_server.server_id'];
         }
        $data = M('Apply', 'tab_')
            ->field('tab_apply.game_id,tab_apply.game_name,tab_apply.sdk_version')
            ->join('tab_game as g on g.id = tab_apply.game_id')
            ->join($serverJoin)//关联区服表
            ->where($map)
            ->group('tab_apply.game_id')
            ->order('g.sort desc,tab_apply.id desc')
            ->select();
        $records = [];
         if (!empty($data)) {  
            if (intval($endTime - $begTime) / (24 * 3600) <= 30) {
                $gameIds = [];
                foreach ($data as $list) {
                    $gameIds[] = $list['game_id'];
                }
                $params['game_ids'] = $gameIds;

                $userRepository = new UserRepository();
                $spendRepository = new SpendRepository();
                $roleNumList = $userRepository->getCreateRoleCountByGame($params);//创角数
                $userNumList = $userRepository->getCreateRoleUserCountByGame($params);//创角用户
                $newUserNumList = $userRepository->getNewCreateRoleUserCountByGame($params);//新创角用户
                $newDeviceNumList = $userRepository->getNewCreateRoleDeviceCountByGame($params);//新创角设备
                $newIpNumList = $userRepository->getNewCreateRoleIpCountByGame($params);//新创角IP
                $loginUserNumList = $userRepository->getLoginCountGroupByGame($params);//登录用户数
                $spendUserNumList = $spendRepository->getPayUserCountGroupByGame($params);//充值人数
                $spendNumList = $spendRepository->getPayCountGroupByGame($params);//充值次数
                $spendAllAmountList = $spendRepository->getPayAmountGroupByGameAndType($params);//充值总额
                $params['pay_way'] = ['in', '1,2,3,4,5,6'];
                $spendCashList = $spendRepository->getPayAmountGroupByGameAndType($params);//现金充值
                $params['pay_way'] = 0;
                $spendGenericList = $spendRepository->getPayAmountGroupByGameAndType($params);//通用币充值
                $params['pay_way'] = -1;
                $spendBindingList = $spendRepository->getPayAmountGroupByGameAndType($params);//绑定币充值
                foreach ($data as &$list) {
                    $gameId = $list['game_id'];
                    $records[] = [
                        'game_id' => $gameId,
                        'game_name' => $list['game_name'],
                        'sdk_version' => $list['sdk_version'],
                        'role_num' => $roleNumList[$gameId],
                        'user_num' => $userNumList[$gameId],
                        'new_user_num' => $newUserNumList[$gameId],
                        'new_device_num' => $newDeviceNumList[$gameId],
                        'new_ip_num' => $newIpNumList[$gameId],
                        'login_user_num' => $loginUserNumList[$gameId],
                        'spend_user_num' => $spendUserNumList[$gameId],
                        'spend_num' => $spendNumList[$gameId],
                        'spend_all_amount' => $spendAllAmountList[$gameId],
                        'spend_cash' => $spendCashList[$gameId],
                        'spend_generic' => $spendGenericList[$gameId],
                        'spend_binding' => $spendBindingList[$gameId],
                        'spend_discount' => 0,
                        'spend_voucher' => 0,
                    ];
                }
            }
        }

        
        $xlsData = [];
        foreach ($records as $key1 => $value1) {
           if($value1["sdk_version"] == 1) {
               $value1["sdk_version"] = "安卓";
           }
           if($value1["sdk_version"] == 2) {
              $value1["sdk_version"] = "苹果";
           }
           $xlsData[] = $value1;
        }
        $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);
     }
     
     /*
     *渠道管理
     */
     public function childrenExcelInfo($id,$map) {
         $xlsName = "渠道管理";
         $xlsCell = array(
             array('id','ID'),
             array('account','账号'),
             array('real_name','真实姓名'),
             array('idcard','身份证'),
             array('mobile_phone','手机号'),
             array('parent_name','上级渠道'),
             array('nickname','昵称'),
             array('promotestatus','帐号状态'),
             array('create_time','创建时间'),      
             
         );
         
        $model = M('promote','tab_');
        $data = $model->where($map)->select();
        $xlsData = [];
        foreach ($data as $key1 => $value1) { 
//           $value1['status'] = $this->payWay[$value1['pay_way']];
            $value1['promotestatus'] = "未知状态";
            if($value1['status'] == 0) {
                $value1['promotestatus'] = "审核中";
            }
            if($value1['status'] == 1) {
                $value1['promotestatus'] = "启用";
            }
            if($value1['status'] == 2) {
                $value1['promotestatus'] = "冻结中";
            }

           $value1['create_time'] = date('Y-m-d H:i:s',$value1['create_time']);
           $xlsData[] = $value1;
        }
        $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);
     }
     
     public function mycoinExcelInfo($id,$map) {
         $xlsName = "我的平台币";
         $xlsCell = array(
             array('cointype','平台币类型'),
             array('game_name','游戏名称'),
             array('num','平台币余额'),
             array('status','资产状态'),
             
         );
        $data = M('PromoteBalanceCoin', 'tab_')
            ->field('tab_promote_balance_coin.*,tab_game.game_name')
            ->join('left join tab_game on tab_promote_balance_coin.game_id = tab_game.id')
            ->where($map)
            ->select();  
        foreach($data as $key => $value) {
            if($value['game_id'] == 0) {
                $value['cointype'] = "通用币";
                $value['game_name'] = "通用";
            }else {
                $value['cointype'] = "绑定币";
                $value['game_name'] = $value['game_name'];
            }
            if($value['status'] == 1) {
                $value['status'] = "正常";
            }elseif($value['status'] == 2) {
                $value['status'] = "锁定";
            }else {
                $value['status'] = "验证失败";
            }
            $xlsData[] = $value;
        }
         $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);
     }
     
     public function mycoinRecordExcelInfo($id,$map) {
         $xlsName = "我的平台币明细";
         $xlsCell = array(
             array('sn','流水号'),
             array('type','操作类型'),
             array('sub_type','操作方式'),
             array('handle_type','账号类型'),
             array('coin','平台币数量'),
             array('balance_coin','平台币余额'),
             array('description','交易说明'),
             array('create_time','交易时间'),
         );
         $join .= ' left join tab_coin_pay_order on tab_promote_coin_record.ref_id = tab_coin_pay_order.id and tab_promote_coin_record.sub_type in (1,2)';
          $data = M('PromoteCoinRecord', 'tab_')
            ->field('tab_promote_coin_record.*,tab_promote_coin.id as coin_id,tab_promote_coin.source_type,tab_promote_coin.source_id,tab_coin_pay_order.id as pay_id')
            ->join($join)
            ->where($map)
            ->having($having)
            ->order('id desc')
            //            ->fetchSql(true)
            ->select();

     }
     
     // 我的平台币的交易明细
     public function coinrecordExcelInfo($id,$map) {
         $xlsName = "平台币转移";
         $xlsCell = array(
             array("sn","订单号"),
             array("source_name","收款方账号"),
             array("game_name","适用游戏"),
             array("handle_type","账号类型"),
             array("num","转账数量"),
             array('description',"交易说明"),
             array('create_time',"交易时间"),
             array('status',"交易状态"),
         );
         $model = M("PromoteCoin",'tab_');
         $data = $model->where($map)->order('create_time desc')->select();
         $sourcePromoteIds = [];
         $sourceUserIds = [];
         foreach ($data as $item) {
            if ($item['source_type'] == 1) {
                $sourcePromoteIds[] = $item['source_id'];
            } elseif ($item['source_type'] == 2) {
                $sourceUserIds[] = $item['source_id'];
            }
        }
        $sourceUsers = $this->getRecordsByIds(M('User', 'tab_'), $sourceUserIds, ['indexBy' => 'id']);
        $sourcePromotes = $this->getRecordsByIds(M('Promote', 'tab_'), $sourcePromoteIds, ['indexBy' => 'id']);
        $records = [];
        foreach ($data as $item) {
            $sourceName = '';
            $promote = null;
            if ($item['source_type'] == 2) {
                $sourceName = $sourceUsers[$item['source_id']]['account'];
            } elseif ($item['source_type'] == 1) {
                $promote = $sourcePromotes[$item['source_id']];
                $sourceName = $sourcePromotes[$item['source_id']]['account'];
            }
            $handleType = $this->getHandleType($item, $promote);
            $records = [
                'id' => $item['id'],
                'sn' => $item['sn'],
                'account' => $item['id'],
                'game_name' => isset($games[$item['game_id']]) ? $games[$item['game_id']] : '所有游戏',
                'create_time' => date('Y-m-d H:i:s', $item['create_time']),
                'description' => $item['description'],
                'num' => $item['num'],
                'source_name' => $sourceName,
                'handle_type' => $handleType,
                'status' => $item['status'] == 1 ? '成功' : '失败',
            ];
        }
        $xlsData[] = $records;
        $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);
         
     }
     
     public function testresourceExcelInfo($id,$map) {
         $xlsName = "测试资源";
         $xlsCell = array(
             array('game_name',"产品名称"),
             array('server_name',"区服"),
             array('user_account',"测试账号"),
             array('promote_account',"所属推广员"),
             array('role_name',"角色名称"),
             array('verify_resource_count',"累计发放资源"),
             array('verify_count',"累计发放次数"),
             array('apply_resource_count',"申请数量"),
             array('check_status',"状态"),
             array('create_time',"创建时间"),      
         );
         
         $data = M('test_resource','tab_')
                 ->field("tab_test_resource.*,user.check_status")
                 ->join('tab_user user on tab_test_resource.user_id=user.id','left')
                 ->order("create_time desc")
                ->where($map)
                ->group("user_id,game_id,server_id")
                 ->select();
         foreach ($data as $key => $value) {
            $value['create_time'] = date("Y-m-d H:i:s", $value['create_time']);
            //获取累计发放
            $where = array(
                "user_id"=>$value['user_id'],
                "game_id"=>$value['game_id'],
                "server_id"=>$value['server_id']
            );
            $where1 = array(
                "apply_status"=>2,
            );
            //获取累计
            $verify_resource = M('test_resource','tab_')->field("IFNULL(sum(verify_resource),0) verify_resource_count,count(*) verify_count")->where(array_merge($where,$where1))->find();
            //获取申请
            $where2 = array(
                "apply_status"=>0,
            );
            $apply_resource = M('test_resource','tab_')->field("IFNULL(sum(apply_resource),0) apply_resource_count")->where(array_merge($where,$where2))->find();
            $data[$key] = array_merge($value,$verify_resource,$apply_resource);
        }
        $xlsData = $data;
         $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);
        
         
     }
     
     public function testresourcelistExcelInfo($id,$map){
         $xlsName = "测试资源申请记录";
         $xlsCell = array(
             array('game_name',"游戏名称"),
             array('server_name',"区服"),
             array('user_account',"测试账号"),
             array('phone',"手机号"),
             array('role_name',"角色名称"),
             array('apply_resource',"申请数量"),
             array('verify_resource',"实际发放"),
             array('apply_remark',"备注"),
             array('apply_status',"审核状态"),
             array('verify_remark',"审核意见"),    
             array('promote_account',"申请人"),
             array('create_time',"申请时间"),
             array('verify_time',"审核时间"),
         );
         $data=M('test_resource','tab_')->where($map)->order('id desc')->select();
         foreach($data as $key => $value) {
             if($value['apply_status'] == 1) {
                 $data[$key]['apply_status'] = "审核未通过";
             }
             elseif($value['apply_status'] == 2) {
                 $data[$key]['apply_status'] = "审核通过";
             }
             else {
                 $data[$key]['apply_status'] = "待审核";
             }
             $data[$key]['create_time'] = date('Y-m-d H:i:s',$value['create_time']);
             $data[$key]['verify_time'] = date('Y-m-d H:i:s',$value['verify_time']);
         }
         $xlsData = $data;
         $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);
     }
     
     public function supportNumberListExcelInfo($id,$map) {
          $xlsName = "扶持号管理";
         $xlsCell = array(
             array('game_name',"产品名称"),
             array('server_name',"区服"),
             array('user_account',"测试账号"),
             array('promote_account',"所属推广员"),
             array('role_name',"角色名称"),
             array('device_number',"设备信息"),
             array('check_status',"状态"),
             array('create_time',"创建时间"),
         );
          $data = M('test_resource','tab_')
          ->field('tab_test_resource.id,tab_test_resource.user_id,tab_test_resource.game_name,tab_test_resource.server_name,tab_test_resource.user_account,tab_test_resource.promote_account,tab_test_resource.role_name,tab_test_resource.create_time,device_number,lock_status as check_status')
          ->join('left join tab_user as user on tab_test_resource.user_id = user.id')
          ->where($map)
          ->order('tab_test_resource.create_time DESC')
          ->select();
         foreach ($data as $key => $value) {
            $data[$key]['create_time'] = date('Y-m-d H:m:i',$value['create_time']);
            if($value['check_status'] == 1) {
                $data[$key]['check_status'] = "冻结";
            }else {
                $data[$key]['check_status'] = "启用";
            }
        }
         $xlsData = $data;
         $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);
     }
     
     public function arpuExcelInfo($id,$params) {
         $xlsName = "ARPU统计";
         $xlsCell = array(
		array('day','日期'),
                array('payGameCount','付费游戏数'),
		array('loginCount','活跃用户'),
		array('registerCount','新增用户'),
                array('payUserCount','付费用户'),          
                array('newPayUserCount','新增付费用户'),
                array('payAmount','付费总额'),
                array('payRate','付费率'),
                array('newPayAmount','新增付费额'),
                array('historyPayCount','累计付费用户'),
                array('arpu','ARPU'),
                array('arppu','ARPPU'),     
	);
         $dayList = $params["dayList"];
         $arr = explode(',', $params['promote_id'][1]);
         $params['promote_id'] = $arr;
         $records = [];
         $userRepository = new UserRepository();
            $spendRepository = new SpendRepository();
            $payGameCountList = $spendRepository->getPayGameCountGroupByDay($params);
            $payUserCountList = $spendRepository->getPayUserCountGroupByDay($params);
            $newPayUserCountList = $spendRepository->getNewPayUserCountGroupByDay($params);
            $payAmountList = $spendRepository->getPayAmountGroupByDay($params);
            $newPayAmountList = $spendRepository->getNewPayAmountGroupByDay($params);
            $historyPayCountList = $spendRepository->getHistoryPayCountGroupByDay($params);
            $loginCountList = $userRepository->getLoginCountGroupByDay($params);
            $registerCountList = $userRepository->getRegisterCountGroupByDay($params);

            foreach ($dayList as $day) {
                $records[] = [
                    'day' => $day,
                    'payGameCount' => $payGameCountList[$day],
                    'payUserCount' => $payUserCountList[$day],
                    'newPayUserCount' => $newPayUserCountList[$day],
                    'payAmount' => number_format($payAmountList[$day], 2),
                    'newPayAmount' => number_format($newPayAmountList[$day], 2),
                    'historyPayCount' => $historyPayCountList[$day],
                    'loginCount' => $loginCountList[$day],
                    'registerCount' => $registerCountList[$day],
                    'payRate' => $loginCountList[$day] == 0 ? '--' : round($payUserCountList[$day] / $loginCountList[$day] * 100, 2) . '%',
                    'ratentionOneDay' => '--',
                    'arpu' => $loginCountList[$day] == 0 ? '0.00' : number_format(round($payAmountList[$day] / $loginCountList[$day], 2), 2),
                    'arppu' => $payUserCountList[$day] == 0 ? '0.00' : number_format(round($payAmountList[$day] / $payUserCountList[$day], 2), 2),
                ];
            }
             $xlsData = [];
            foreach ($records as $key1 => $value1) {
               $xlsData[] = $value1;
            }
            $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);
            
         
     }
     
     public function remitCerDownLoad($id,$map) {
         $proof_id = $map['id'];
         $file = new FileController();
         $file->download($proof_id);
         $this->backSuccessExport($id);
     }
     
     public function withdrawDtlExcelInfo($id,$map) {
          $xlsName = "提现记录";
         $xlsCell = array(
             array('pay_order_number','充值订单号'),
             array('game_name','游戏'),
             array('sdk_version','平台'),
             array('user_account','玩家账号'),
             array('pay_amount','订单总额'),
             array('cash_base','现金分成基数'),
             array('selle_ratio','现金分成比例'),
             array('platform_base','平台币分成基数'),
             array('selle_ratio','平台币分成比例'),
             array('bind_base','绑定币分成基数'),
             array('selle_ratio','绑定币分成比例'),
             array('pay_way_name','现金支付通道'),
             array('income','收益'),
             array('status','订单状态'),
             array('pay_time','充值时间'),
        );   
        $spendModel = M('spend', 'tab_'); 
         $withdrawId = $map['withdraw_id'];
         $withdraw = M('withdraw', 'tab_')->field('promote_id,status')->where(array('id' => $withdrawId))->find();
        $data = $spendModel
            ->field('id,pay_order_number,game_name,sdk_version,user_account,pay_amount,pay_way,selle_ratio,pay_time')
            ->where($map)
            ->order('id desc')
            ->select();
         if (!empty($data)) {
            foreach ($data as &$list) {
                $list['income'] = bcmul($list['pay_amount'], bcdiv($list['selle_ratio'], 100, 2), 2);
                $list['pay_time'] = date('Y-m-d H:i:s', $list['pay_time']);
                switch ($list['pay_way']) {
                    case 2:
                    case 3:
                    case 4:
                        $list['pay_way_name'] = QueryController::$payWay[2];
                        break;
                    default:
                        $list['pay_way_name'] = QueryController::$payWay[$list['pay_way']];
                        break;
                }
                if($list['pay_way'] !== -1 && $list['pay_way'] !== 0) {
                    $list['cash_base'] = $list['pay_amount'];
                }else {
                    $list['cash_base'] = 0;
                }
                
                if($list['pay_way'] == 0) {
                   $list['platform_base']  = $list['pay_amount'];
                }else {
                    $list['platform_base']  = 0;
                }
                
                 if($list['pay_way'] == -1) {
                   $list['bind_base']  = $list['pay_amount'];
                }else {
                    $list['bind_base']  = 0;
                }
                
                $list['status'] = FinanceController::$withdrawStatus[$withdraw['status']];
                
                
            }     
        }
         $xlsData = $data;
        $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);  
     }
     
     public function withdrawRecordExcelInfo($id,$map) {
          $xlsName = "提现记录";
         $xlsCell = array(
             array('widthdraw_number','提现订单'),
             array('create_time','提现日期'),
             array('settlement_end_time','结算截止日期'),
             array('sum_money','收益金额'),
             array('sum_money','实际提现金额'),
             array('status','提现状态'),
             array('respond','说明'),
        );    
        $model = M('withdraw', 'tab_');
        $data = $model->field('id,widthdraw_number,create_time,settlement_end_time,sum_money,status,respond')
            ->where($map)
            ->order('id desc')
            ->select();
        if (!empty($data)) {
            foreach ($data as &$list) {
                $list['create_time'] = date('Y-m-d H:i:s', $list['create_time']);
                $list['settlement_end_time'] = date('Y-m-d H:i:s', $list['settlement_end_time']);
                $list['status'] = FinanceController::$withdrawStatus[$list['status']];
            }
        }
        $xlsData = $data;
        $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);     
     }
     
     public function settlementExcelInfo($id,$map) {
         $xlsName = "结算明细";
         $xlsCell = array(
             array('pay_order_number','游戏订单号'),
             array('game_name','游戏'),
             array('user_account','玩家账号'),
             array('promote_account','推广员账号'),
             array('pay_amount','订单总额'),
             array('pay_amount_zhi','直充'),
             array('pay_amount_nei','内充'),
             array('selle_ratio','分成比例(直充)'),
             array('selle_ratio','分成比例(内充)'),
             array('income','收益'),
             array('pay_time','充值时间'),
             array('selle_status','订单状态'),
        );     
          $model = M('spend', 'tab_');
          $data = $model->field('pay_order_number,game_name,user_account,promote_account,pay_amount,pay_way,if(selle_ratio >= 0,selle_ratio,0) as selle_ratio,pay_time,selle_status,pay_status,withdraw_id')
            ->where($map)
            ->order('id desc')
            ->select();   
        //提现状态
        $withdrawIds = [];
        foreach ($data as $key => $value) {
            if ($value['withdraw_id'] > 0 && !in_array($value['withdraw_id'], $withdrawIds)) {
                $withdrawIds[] = $value['withdraw_id'];
            }
        }
        if(empty($withdrawIds)) {
            $withdrawIds = "-10000";
        }
        $withdrawStatus = M('withdraw', 'tab_')
            ->where(array('id' => ['in',$withdrawIds]))
            ->getField('id,status');

        foreach ($data as &$list) {
            //提现状态
            if ($list['pay_status'] == 1) {
                switch ($list['selle_status']) {
                    case 0:
                        $list['selle_status'] = '未提现';
                        break;
                    default:
                        if ($list['withdraw_id'] > 0) {
                            $list['selle_status'] = FinanceController::$withdrawStatus[$withdrawStatus[$list['withdraw_id']]];
                        } else {
                            $list['selle_status'] = '';
                        }
                        break;
                }
            } else {
                $list['selle_status'] = '支付失败';
            }

            $list['income'] = bcmul($list['pay_amount'], bcdiv($list['selle_ratio'], 100, 2), 2);
            $list['pay_time'] = date('Y-m-d H:i:s', $list['pay_time']);
            if($list['pay_way'] == -1) {
                $list['pay_amount_zhi'] = 0;
                $list['pay_amount_nei'] = $list['pay_amount'];
            }else {
               $list['pay_amount_zhi'] = $list['pay_amount'];
                $list['pay_amount_nei'] = 0; 
            }
        }  
        
        $xlsData = $data;
        $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);     
                    
     }
     
     public function financeindexExcelInfo($id,$map) {
         $xlsName = "结算中心";
         $xlsCell = array(
             array('day','时间'),
             array('income','收益')
         );
         if(!empty($map['pay_time'])) {
             $begTime = $map['pay_time'][1][0];
             $endTime = $map['pay_time'][1][1];
         }else {
              $nowTime = date('Y-m-d');
            $initBegTime = date('Y-m-d', strtotime('-6 day', strtotime($nowTime)));
            $initBegTime = empty(I('begtime')) ? $initBegTime : I('begtime');
            $initEndTime = $nowTime;
            $initEndTime = empty(I('endtime')) ? $initEndTime : I('endtime');
            $begTime = strtotime($initBegTime);
            $endTime = strtotime($initEndTime);
            $endTime = $endTime + 3600 * 24;
         }
         $model = M('spend', 'tab_');
         $dayList = $this->getDayList($begTime, $endTime);
           $data = $model->field('FROM_UNIXTIME(pay_time, "%Y-%m-%d") as day,
        sum(if(selle_ratio > 0, pay_amount * selle_ratio, 0)) as income')
            ->where($map)
            ->group('day')
            ->select();
        $data = $this->assembleRecords($data, $dayList, 'income');
        foreach ($dayList as $day) {
            $date = date('Ymd', strtotime($day));
            $records[] = [
                'day' => $date,
                'income' => bcdiv($data[$day], 100, 2),
              
            ];
        }
         $xlsData = [];
        foreach ($records as $key1 => $value1) {
           $xlsData[] = $value1;
        }
        $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);
            
     }
     
     public function dailysummaryExcelInfo($id,$map) {
         $xlsName = "每日概况";
         $xlsCell = array(
		array('day','日期'),
                array('role_num','创角数'),
                array('user_num','创角用户'),
		array('new_user_num','新创角用户'),
		array('new_device_num','新创角设备'),
                array('new_ip_num','新增创角IP'),          
                array('login_user_num','登陆用户数'),
                array('spend_user_num','充值人数'),
                array('spend_num','充值次数'),
                array('spend_all_amount','充值总额'),
                array('spend_cash','现金充值'),
                array('spend_generic','通用币充值'),
                array('spend_binding','绑定币充值'),
                array('spend_discount','折扣币充值'),
                array('spend_voucher','代金劵使用'),
      
	);
        $nowTime = date('Y-m-d');
        $initBegTime = date('Y-m-d', strtotime('-6 day', strtotime($nowTime)));
        $initBegTime = empty(I('begtime')) ? $initBegTime : I('begtime');
        $initEndTime = $nowTime;
        $initEndTime = empty(I('endtime')) ? $initEndTime : I('endtime');
        $begTime = strtotime($initBegTime);
        $endTime = strtotime($initEndTime);
         $params['promote_id'] = $map['promote_id'];
         if(!empty($map['sdk_version']) || !empty($map['relation_game_id'])) {
             if(!empty($map['gameIds'])) {
                 $params['game_id'] = ['in',$map['gameIds']];
             }else {
                 $params['_string'] = '1=2';
             }
         }
         if(!empty($map['begin_time'])) {
             $params['begin_time'] = $map['begin_time'];
         }else {
             $params['begin_time'] = $begTime;
         }
         
         if(!empty($map['end_time'])) {
             $params['end_time'] = $map['end_time'];
         }else {
             $params['begin_time'] = $endTime;
         }
         $params['dayList'] = $map["dayList"];
         $summaryData = [];
         $records = [];
         if (intval($endTime - $begTime) / (24 * 3600) <= 30) {
            $userRepository = new UserRepository();
            $spendRepository = new SpendRepository();
            $roleNumList = $userRepository->getCreateRoleCountByDay($params);//创角数
            $userNumList = $userRepository->getCreateRoleUserCountByDay($params);//创角用户
            $newUserNumList = $userRepository->getNewCreateRoleUserCountByDay($params);//新创角用户
            $newDeviceNumList = $userRepository->getNewCreateRoleDeviceCountByDay($params);//新创角设备
            $newIpNumList = $userRepository->getNewCreateRoleIpCountByDay($params);//新创角IP
            $loginUserNumList = $userRepository->getLoginCountGroupByDayNew($params);//登录用户数
            $spendUserNumList = $spendRepository->getPayUserCountGroupByDayNew($params);//充值人数
            $spendNumList = $spendRepository->getPayCountGroupByDay($params);//充值次数
            $spendAllAmountList = $spendRepository->getPayAmountGroupByDayAndType($params);//充值总额
            $params['pay_way'] = ['in', '1,2,3,4,5,6'];
            $spendCashList = $spendRepository->getPayAmountGroupByDayAndType($params);//现金充值
            $params['pay_way'] = 0;
            $spendGenericList = $spendRepository->getPayAmountGroupByDayAndType($params);//通用币充值
            $params['pay_way'] = -1;
            $spendBindingList = $spendRepository->getPayAmountGroupByDayAndType($params);//绑定币充值

            foreach ($params['dayList'] as $day) {
                $date = date('Ymd', strtotime($day));
                $records[] = [
                    'day' => $date,
                    'role_num' => $roleNumList[$day],
                    'user_num' => $userNumList[$day],
                    'new_user_num' => $newUserNumList[$day],
                    'new_device_num' => $newDeviceNumList[$day],
                    'new_ip_num' => $newIpNumList[$day],
                    'login_user_num' => $loginUserNumList[$day],
                    'spend_user_num' => $spendUserNumList[$day],
                    'spend_num' => $spendNumList[$day],
                    'spend_all_amount' => $spendAllAmountList[$day],
                    'spend_cash' => $spendCashList[$day],
                    'spend_generic' => $spendGenericList[$day],
                    'spend_binding' => $spendBindingList[$day],
                    'spend_discount' => 0,
                    'spend_voucher' => 0,
                ];

            }
            $xlsData = [];
        foreach ($records as $key1 => $value1) {
           $xlsData[] = $value1;
        }
        $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);
            
        }
         
     }
     
     public function achievementExcelInfo($tid,$map) {
         $xlsName = "推广员业绩";
         $xlsCell = array(
		array('account','账号'),
                array('real_name','姓名'),
                array('create_role_count','创角数'),
		array('create_role_user_count','创角用户'),
		array('new_create_role_user_count','新创角用户'),
		array('new_create_role_device_count','新创角设备'),
                array('new_create_role_ip_count','新创角ip'),          
                array('login_user_count','登陆用户数'),
                array('recharge_count','充值人数'),
                array('recharge_user_count','充值次数'),
                array('recharge_amount','充值总额'),
                array('recharge_by_ban_coin','现金充值'),
                array('recharge_by_coin','通用币充值'),
             array('recharge_by_cash','绑定币充值'),
            
             
	);
        $params['isContainSubs'] =$map['isContainSubs'];
        $params['basicPromotes'] = json_decode($map['basicPromotes'],TRUE);
        $ids = $map['ids'];
        $promotes = json_decode($map["promotes"],TRUE);
        if(!empty($map['game_id'])) {
            $params['game_id'] = $map["game_id"];
        }
         if(!empty($map['server_id'])) {
            $params['server_id'] = $map["server_id"];
        }
        if(!empty($map['sdk_version'])) {
            $params['sdk_version'] = $map["sdk_version"];
        }
        if(!empty($map['lock_status'])) {
            $params['lock_status'] = $map["lock_status"];
        }
        $params['begin_time'] = $map['begin_time'];
        $params['end_time'] = $map['end_time'];
        
//        var_dump($params);die();
         $promoteRepository = new PromoteRepository();
        $createRoleCountList = $promoteRepository->getCreateRoleCountByIds($ids, $params);
        $createRoleUserCountList = $promoteRepository->getCreateRoleUserCountByIds($ids, $params);
        $newCreateRoleUserCountList = $promoteRepository->getNewCreateRoleUserCountByIds($ids, $params);
        $newCreateRoleDeviceCountList = $promoteRepository->getNewCreateRoleDeviceCountByIds($ids, $params);
        $newCreateRoleIpCountList = $promoteRepository->getNewCreateRoleIpCountByIds($ids, $params);
        $loginUserCountList = $promoteRepository->getLoginUserCountByIds($ids, $params);
        $rechargeCountList = $promoteRepository->getRechargeCountByIds($ids, $params);
        $rechargeUserCountList = $promoteRepository->getRechargeUserCountByIds($ids, $params);
        $rechargeAmountList = $promoteRepository->getRechargeAmountByIds($ids, $params);

        $records = [];
         foreach ($promotes as $promote) {
            $id = $promote['id'];
            $records[] = [
                'id' => $id,
                'account' => $promote['account'],
                'real_name' => $promote['real_name'],
                'level' => $promote['level'],
                'create_role_count' => $createRoleCountList[$id],
                'create_role_user_count' => $createRoleUserCountList[$id],
                'new_create_role_user_count' => $newCreateRoleUserCountList[$id],
                'new_create_role_device_count' => $newCreateRoleDeviceCountList[$id],
                'new_create_role_ip_count' => $newCreateRoleIpCountList[$id],
                'login_user_count' => $loginUserCountList[$id],
                'recharge_count' => $rechargeCountList[$id],
                'recharge_user_count' => $rechargeUserCountList[$id],
                'recharge_amount' => $rechargeAmountList[$id]['ban_coin'] + $rechargeAmountList[$id]['coin'] + $rechargeAmountList[$id]['cash'],
                'recharge_by_ban_coin' => $rechargeAmountList[$id]['ban_coin'],
                'recharge_by_coin' => $rechargeAmountList[$id]['coin'],
                'recharge_by_cash' => $rechargeAmountList[$id]['cash'],
                'current_display' => '',
            ];
        }
        $xlsData = [];
        foreach ($records as $key1 => $value1) {
           $xlsData[] = $value1;
        }
        $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);
     }
     
     public function rechargeExcelInfo($id,$map) {
         $xlsName = "订单查询";
         $xlsCell = array(
		array('user_account','玩家账号'),
		array('order_number','游戏订单'),
		array('pay_amount','订单金额'),
                array('pay_way','支付方式'),
                array('game_name','游戏名称'),
                array('server_name','区服'),
                array('game_player_name','角色名'),
                array('pay_time','付款时间'),
             
	);
        $model = M('spend','tab_');
        $data = $model->where($map)->select();
        $xlsData = [];
        foreach ($data as $key1 => $value1) {    
           $value1['pay_way'] = $this->payWay[$value1['pay_way']];
           $value1['pay_time'] = date('Y-m-d H:i:s',$value1['pay_time']);
           $xlsData[] = $value1;
        }
        $this->exportExcel($xlsName, $xlsCell, $xlsData,$id);
     }
     
     public function backSuccessExport($id) {        //导出成功后
         if(!$id) {
             
         }else {
             $res = M('downloadlog','tab_')->where(['id'=>$id])->select();
             $data = $res[0];
             $data['status'] = 1;
             $data['begintime'] = time();
             $updateRs = M('downloadlog','tab_')->where(['id'=>$id])->save($data); 
         }

     }
     /*
      * 汇款证明
      *       */
     public function Remittancecer() {
         $id = $_REQUEST["id"];
         $model = M("withdraw","tab_");
         $res = $model->where(['id'=>$id])->field('transfer_proof,status')->find();
         $transfer_proof = intval($res["transfer_proof"]);
         $map = ['id'=>$transfer_proof];
         $addtime = time();
         $conditions = json_encode($map,TRUE); 
         $data = [
             'logid' => 'remitrecord_'.time(),
             'admin_id' => PID,
             'type' => '/Home/Finance/withdrawRecord',
             'dataname' => '汇款证明',
             'status' => 0,
             'addtime' => $addtime,
             'begintime' => 0,
             'content' => '',
             'conditions' =>$conditions,
         ];
         $log = M('downloadlog','tab_')->add($data);
         if (!$log) {
             $this->error('添加下载失败');
            }
       $this->success('添加下载成功',U('listsIndex'));        
         
                    
     }
     
     
     
     
     
    public function encryptDecrypt($key, $string, $decrypt){       
        if($decrypt){  
            $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12");  
            return $decrypted;  
        }else{  
            $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));  
            return $encrypted;  
        }  
    }  
    
//    public function getLoginPromote()
//    {
//      $promoteId = session('promote_auth.pid');
//      return M('promote', 'tab_')->where(['id' => $promoteId])->find();
//    }
    
     private function getGroupPromotes($promote)
    {
        $promotes = [];
        if ($promote['parent_id'] == 0) {
            $promotes = M('promote', 'tab_')->field(['id', 'account', 'real_name'])->where(['parent_id' => $promote['id']])->select();
        }
        return $promotes;
    }
    
    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
      ];
      $pagination = set_pagination($count, $pageSize);
      
      return [$records, $pagination, $count];
    }
    
     private function getGamesByPromote($promote)
    {
        return M('apply', 'tab_')->field(['game_id', 'game_name'])->where(['promote_id' => $promote['id']])->select();
    }
    
    private function getBetweenTime($time, $defaultBegin = 0, $defaultEnd = 0)
    {
        $delimiter = ' 至 ';
        $begin = $defaultBegin;
        $end = $defaultEnd;
        if ($time != '') {
            if (strpos($time, $delimiter) == -1) {
                $begin = strtotime($time . ' 00:00:00');
                $end = strtotime($time . ' 23:59:59');
            } else {
                $timeRow = explode($delimiter, $time);
                $begin = strtotime($timeRow[0] . ' 00:00:00');
                $end = strtotime($timeRow[1] . ' 23:59:59');
            }
        }
        return [$begin, $end];
    }
    
       private function getQueryPromote($levelPromote)
    {
        $queryPromote = null;
        $promote = $this->getLoginPromote();
        $queryPromoteId = 0;
        foreach($levelPromote as $item) {
            if ($item != 0) {
                $queryPromoteId = $item;
            }
        }
        if ($queryPromoteId == 0) {
            $queryPromote = $this->getLoginPromote();
        } else {
            $queryPromote = M('promote', 'tab_')->where(['id' => $queryPromoteId])->find();
        }
        return $queryPromote;
    }

    public function getHandleType($promoteCoin, $promote)
    {
        if ($promoteCoin['source_type'] == 2) {
            return '玩家转账';
        } else {
            if ($promote['parent_id'] == 1) {
                return '会长转账';
            } elseif ($promote['parent_id'] > 0 && $promote['grand_id'] == 0) {
                return '组长转账';
            } elseif ($promote['grand_id'] > 0) {
                return '推广员转账';
            }
        }
    }
    
     private function getLevelPromote()
    {
        $levelPromote = [];
        $levelPromote[] = I('level_promote_2', 0);
        $levelPromote[] = I('level_promote_3', 0);
        $levelPromote[] = I('level_promote_4', 0);
        return $levelPromote;
    }
    
    private function getDayList($beginTime, $endTime)
    {
        $dayList = [];
        do {
            $dayList[] = date('Y-m-d', $beginTime);
            $beginTime += 24 * 60 * 60;
        } while ($beginTime < $endTime);

        return $dayList;
    }
    
    private function assembleRecords($items, $keys, $valueColumn, $keyColumn = 'day')
    {
        $records = [];
        foreach ($keys as $key) {
            $value = 0;
            foreach ($items as $item) {
                if ($item[$keyColumn] == $key) {
                    $value = $item[$valueColumn];
                }
            }
            $records[$key] = $value;
        }
        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;
    }
}