<?php

namespace Admin\Controller;

use User\Api\UserApi as UserApi;

/**
 * 推广查询控制器
 * @author 王贺
 */
class QueryController extends ThinkController
{
    public function settlement($p = 0)
    {

        $group = I('group', 1);
        $this->assign('group', $group);
        if (isset($_REQUEST['total_status'])) {
            unset($_REQUEST['total_status']);
        }

        $this->m_title = '推广结算';
        $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'Query/settlement', 'status' => 1])->find());

        if ($group == 1) {
            if ($_REQUEST['unum'] == 2) {
                $order = 'unum';
                $order_type = SORT_ASC;
            } else if ($_REQUEST['unum'] == 1) {
                $order = 'unum';
                $order_type = SORT_DESC;
            }
            if ($_REQUEST['spay_amount'] == 2) {
                $order = 'spay_amount';
                $order_type = SORT_ASC;
            } else if ($_REQUEST['spay_amount'] == 1) {
                $order = 'spay_amount';
                $order_type = SORT_DESC;
            }
            $model = array(
                'title' => '渠道结算',
                'template_list' => 'settlement',
                'order' => $order,
                'order_type' => $order_type//0倒序  1 正序
            );
            $start = $_REQUEST['timestart'];
            $end = $_REQUEST['timeend'];
            if (I('group') != '') {
                if ($start == '' || $end == '' && $_REQUEST['promote_account'] == '') {
                    $this->error('结算周期、所属渠道不能为空!', '', 1);
                }
                if ($start == '' || $end == '') {
                    $this->error('请选择结算周期!', '', 1);
                }
                if ($_REQUEST['promote_account'] == '') {
                    $this->error('请选择渠道!', '', 1);
                }
            }
            $smap['tab_spend.pay_status'] = 1;
            //判断是否结算绑币
            if ($_REQUEST['bind_coin'] == 0) {
                $smap['tab_spend.pay_way'] = array('neq', -1);
            }

            $this->meta_title = '渠道结算列表';
            $this->assign('setdate', date("Y-m-d", strtotime("-1 day")));
            $this->assign('is_admin', is_administrator());
            if ($start && $end) {
                if ((strtotime($end) + 24 * 60 * 60 - 1) < strtotime($start)) {
                    $this->error('时间选择不正确!', U('Query/settlement'), '');
                }
                $umap['register_time'] = array('BETWEEN', array(strtotime($start), strtotime($end) + 24 * 60 * 60 - 1));
                if (isset($_REQUEST['game_name']) && $_REQUEST['game_name'] != '') {
                    $umap['fgame_id'] = get_game_id($_REQUEST['game_name']);
                    $smap['tab_spend.game_id'] = get_game_id($_REQUEST['game_name']);
                }
                if (isset($_REQUEST['promote_account']) && $_REQUEST['promote_account'] != '') {
                    $allid = get_subordinate_promote_($_REQUEST['promote_account']);
                    $allid[] = $_REQUEST['promote_account'];
                    $umap['tab_user.promote_account'] = array('in', $allid);
                    $smap['tab_spend.promote_account'] = array('in', $allid);
                } else {
                    $this->error('未选择渠道!', '', 1);
                }
                $umap['is_check'] = 1;
                $umap['settle_check'] = 0;
                $smap['pay_time'] = array('BETWEEN', array(strtotime($start), strtotime($end) + 24 * 60 * 60 - 1));
                $smap['is_check'] = 1;
                $smap['settle_check'] = 0;
                //为数据权限添加
                setPowerPromoteIds($umap, 'tab_user.promote_id');
                setPowerPromoteIds($smap, 'tab_spend.promote_id');
                $map['umap'] = $umap;
                $map['smap'] = $smap;

                $user = A('Settlement', 'Event');


                $user->settlement($model, $p, $map);
            } else {
                $this->display();
            }
        }
        if ($group == 2) {
            if (isset($_REQUEST['stimestart']) && isset($_REQUEST['stimeend'])) {
                $map['create_time'] = array('BETWEEN', array(strtotime($_REQUEST['stimestart']), strtotime($_REQUEST['stimeend']) + 24 * 60 * 60 - 1));
            } elseif (isset($_REQUEST['stimestart'])) {
                $map['create_time'] = array('BETWEEN', array(strtotime($_REQUEST['stimestart']), time()));
            } elseif (isset($_REQUEST['stimeend'])) {
                $map['create_time'] = array('LT', (strtotime($_REQUEST['stimeend']) + 24 * 60 * 60 - 1));
            }
            if (isset($_REQUEST['timestart']) && isset($_REQUEST['timeend'])) {
                $map['starttime'] = ['GT', strtotime($_REQUEST['timestart'])];
                $map['endtime'] = ['LT', strtotime($_REQUEST['timeend']) + 24 * 60 * 60];
            } elseif (isset($_REQUEST['timestart'])) {
                $map['starttime'] = ['GT', strtotime($_REQUEST['timestart'])];
            } elseif (isset($_REQUEST['timeend'])) {
                $map['endtime'] = ['LT', strtotime($_REQUEST['timeend']) + 24 * 60 * 60];
            }
            if (isset($_REQUEST['game_name'])) {
                if ($_REQUEST['game_name'] == '全部') {
                    unset($_REQUEST['game_name']);
                } else {
                    $map['game_name'] = $_REQUEST['game_name'];
                }
            }
            if (isset($_REQUEST['promote_account'])) {
                if ($_REQUEST['promote_account'] == '全部') {
                    unset($_REQUEST['promote_account']);
                } else {
                    $map['promote_account'] = $_REQUEST['promote_account'];
                }
            }
            if (!empty($_REQUEST['settlement_number'])) {
                $map['settlement_number'] = $_REQUEST['settlement_number'];
            }

            $map['developers'] = 0;

            $model = array(
                'm_name' => 'settlement',
                'fields' => array(
                    'settlement_number',
                    'starttime', 'endtime',
                    'promote_id', 'promote_account',
                    'sum(total_money) as total_money',
                    'sum(total_number) as total_number',
                    'sum(sum_money) as sum_money',
                    'bind_coin_status',
                    'create_time'),
                'group' => 'promote_id,starttime,endtime,create_time,bind_coin_status',
                'order' => 'create_time desc ',
                'title' => '结算账单',
                'template_list' => 'settlement',
            );
            //为数据权限添加
            setPowerPromoteIds($map);
            $map1 = $map;

            $ztotal = null_to_0(D('settlement')->where($map1)->sum('sum_money*10000') / 10000);
            $this->assign('ztotal', $ztotal);
            $ttotal = null_to_0(D('settlement')->where('create_time' . total(1))->sum('sum_money*10000') / 10000);
            $this->assign('ttotal', $ttotal);
            $ytotal = null_to_0(D('settlement')->where('create_time' . total(5))->sum('sum_money*10000') / 10000);
            $this->assign('ytotal', $ytotal);
            $user = A('Bill', 'Event');

            $user->money_list($model, $p, $map);
        }

    }

    public function cpsettlement($p = 0)
    {
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据

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

        $this->assign('setdate', date("Y-m-d", strtotime("-1 day")));
        if ($_REQUEST['sum_money'] == 2) {
            $order = 'total desc';
        } else if ($_REQUEST['sum_money'] == 1) {
            $order = 'total asc';
        }
        $group = I('group', 1);
        $this->assign('group', $group);


        $this->m_title = '开发者结算';
        $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'Query/cpsettlement', 'status' => 1])->find());

        if (isset($_REQUEST['timestart']) && $_REQUEST['timestart'] != '' && $_REQUEST['group'] == 1) {
            $starttime = strtotime($_REQUEST['timestart']);
            $endtime = strtotime($_REQUEST['timeend']) + 24 * 3600 - 1;

            if (isset($_REQUEST['developers_id'])) {
                $map['g.developers'] = $_REQUEST['developers_id'];
            } else {
                $this->error('请选择开发者');
            }

            if (isset($_REQUEST['selle_status'])) {
                if ($_REQUEST['selle_status'] == "未结算") {
                    $map['s.selle_status'] = 0;
                } else if ($_REQUEST['selle_status'] == "已结算") {
                    $map['s.selle_status'] = 1;
                }
            } else {
                $map['s.selle_status'] = 0;
            }
            //判断是否结算绑币
            if ($_REQUEST['bind_coin'] == 0) {
                $map['s.pay_way'] = array('neq', -1);
            }
            $map['s.pay_status'] = 1;
            $map['pay_time'] = array('BETWEEN', array($starttime, $endtime));
            $model = array(
                'm_name' => 'Spend as s',
                'order' => $order,
                'title' => '渠道结算',
                'group' => 'g.developers,g.id',
                'fields' => 'sum(s.pay_amount) as total,s.selle_ratio,s.id,g.developers,s.selle_status,g.id as gid,g.game_name,s.pay_status,s.pay_amount',
                'template_list' => 'cpsettlement',
            );

            $user = A('Spend', 'Event');
            $this->meta_title = '开发者结算';
            $user->cpsettl_list($model, $p, $map);
        } else if ($_REQUEST['group'] == 2) {

            if (isset($_REQUEST['timestart']) && $_REQUEST['timeend'] != '') {
                $starttime = strtotime($_REQUEST['timestart']);
                $endtime = strtotime($_REQUEST['timeend']) + 24 * 3600 - 1;
                $map['starttime'] = array('egt', $starttime);
                $map['endtime'] = array('elt', $endtime);
            } elseif (isset($_REQUEST['timestart'])) {
                $starttime = strtotime($_REQUEST['timestart']);
                $map['starttime'] = array('egt', $starttime);
            } elseif (isset($_REQUEST['timeend'])) {
                $endtime = strtotime($_REQUEST['timeend']) + 24 * 3600 - 1;
                $map['endtime'] = array('elt', $endtime);

            }

            if (isset($_REQUEST['start']) && $_REQUEST['end'] != '') {
                $starttime = strtotime($_REQUEST['start']);
                $endtime = strtotime($_REQUEST['end']) + 24 * 3600 - 1;
                $map['create_time'] = array('BETWEEN', array($starttime, $endtime));
            } elseif (isset($_REQUEST['start'])) {
                $starttime = strtotime($_REQUEST['start']);
                $map['create_time'] = array('BETWEEN', array($starttime, time()));
            } elseif (isset($_REQUEST['end'])) {
                $endtime = strtotime($_REQUEST['end']) + 24 * 3600 - 1;
                $map['create_time'] = array('LT', $endtime);
            }

            if (isset($_REQUEST['developers_id'])) {
                $map['developers'] = $_REQUEST['developers_id'];
            } else {
                $map['developers'] = array('neq', 0);
            }

            $data = M('TotalSettlement', 'tab_')->where($map)->order('create_time desc')->page($page, $row)->select();
            $count = M('TotalSettlement', 'tab_')->where($map)->order('create_time desc')->count();

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

            $this->assign('data', $data);
            $this->assign('meta_title', '开发者结算记录');
            $this->display();
        } else {
            $this->meta_title = '开发者结算列表';
            $this->display();
        }
    }

    public function generatesettlementAll()
    {
        $request = I('request.ids');

        if (empty($request)) {
            $this->error('请选择要操作的数据');
        }
        if (is_array($request)) {
            foreach ($request as $k => $v) {
                $query = explode(',', $v);
                $ids[] = $k;
                $_REQUEST[$k]['cooperation'] = $query[0];
                $_REQUEST[$k]['cps_ratio'] = $query[1];
                $_REQUEST[$k]['cpa_price'] = $query[2];
                $_REQUEST[$k]['unum'] = $query[3];
                $_REQUEST[$k]['spay_amount'] = $query[4];
                $_REQUEST[$k]['game_id'] = $query[5];
            }
            unset($_REQUEST['ids']);
        } elseif (is_numeric($request)) {
            $id = $ids[] = $request;
            $_REQUEST[$id]['ids'] = $id;
            $_REQUEST[$id]['cooperation'] = $_REQUEST['cooperation'];
            $_REQUEST[$id]['cps_ratio'] = $_REQUEST['cps_ratio'];
            $_REQUEST[$id]['cpa_price'] = $_REQUEST['cpa_price'];
            $_REQUEST[$id]['unum'] = $_REQUEST['unum'];
            $_REQUEST[$id]['spay_amount'] = $_REQUEST['spay_amount'];
        } else {
            $this->error('参数有误!!!');
        }
        sort(array_unique($ids));
        if (is_array($ids)) {
            $promote_id = get_promote_id($_REQUEST['promote_account']);
            $create_time = time();
            foreach ($ids as $k => $v) {
                if (get_settlement($_REQUEST['timestart'], $_REQUEST['timeend'], $promote_id, $_REQUEST[$v]['game_id'])) {
                    continue;
                }

                $data[$k]['game_id'] = $_REQUEST[$v]['game_id'];
                $data[$k]['game_name'] = get_game_name($_REQUEST[$v]['game_id']);
                $data[$k]['promote_account'] = $_REQUEST['promote_account'];
                $data[$k]['promote_id'] = $promote_id;
                $data[$k]['total_money'] = $_REQUEST[$v]['spay_amount'];
                $data[$k]['total_number'] = $_REQUEST[$v]['unum'];
                $data[$k]['starttime'] = strtotime($_REQUEST['timestart']);
                $data[$k]['endtime'] = strtotime($_REQUEST['timeend']) + 24 * 60 * 60 - 1;
                $data[$k]['pattern'] = $_REQUEST[$v]['cooperation'] == 'CPS' ? 0 : 1;
                $data[$k]['ratio'] = $_REQUEST[$v]['cps_ratio'];
                $data[$k]['money'] = $_REQUEST[$v]['cpa_price'];
                $data[$k]['create_time'] = $create_time;
                $data[$k]['bind_coin_status'] = $_REQUEST['bind_coin'];
                $data[$k]['settlement_number'] = 'JS-' . date('Ymd') . date('His') . sp_random_string(4);

                if (get_settlement($data[$k]['starttime'], $data[$k]['endtime'], $data[$k]['promote_id'], $data[$k]['game_id'])) {
                    $this->error('该结算周期不可结算,请重新选择');
                }
                if ($data[$k]['pattern']) {
                    $data[$k]['sum_money'] = $data[$k]['total_number'] * $data[$k]['money'];
                } else {
                    $data[$k]['sum_money'] = $data[$k]['total_money'] * $data[$k]['ratio'] / 100;
                }
                if ($data[$k]['game_id'] == '' || $data[$k]['promote_id'] == '' || $data[$k]['starttime'] == '' || $data[$k]['endtime'] == '') {
                    $this->error('必要参数不存在');
                }

                $map['fgame_id'] = $data[$k]['game_id'];
                // $map['is_check']=1;
                $map['puid'] = 0;
                $map['register_time'] = array('BETWEEN', array($data[$k]['starttime'], $data[$k]['endtime']));
                $allid = get_subordinate_promote_($data[$k]['promote_account']);
                $allid[] = $data[$k]['promote_account'];
                $map['promote_account'] = array('in', $allid);
                $u = M('User', 'tab_');
                $user = $u->where($map)->setField('settle_check', 1);
                unset($map['register_time']);
                unset($map['puid']);
                $map['pay_status'] = 1;
                $map['pay_time'] = array('BETWEEN', array($data[$k]['starttime'], $data[$k]['endtime']));
                $s = M('spend', 'tab_');
                $spend = $s->where($map)->setField('settle_check', 1);
            }
        }
        $data = array_values($data);
        $result = M('settlement', 'tab_')->addAll($data);
        if ($result) {
            $settMap['promote_id'] = $promote_id;
            $settMap['starttime'] = strtotime($_REQUEST['timestart']);
            $settMap['endtime'] = strtotime($_REQUEST['timeend']) + 24 * 60 * 60 - 1;
            $settMap['create_time'] = $data[0]['create_time'];
            $settMap['bind_coin_status'] = $_REQUEST['bind_coin'];
            $dataSett = M('settlement', 'tab_')->field(array(
                'settlement_number',
                'starttime', 'endtime',
                'promote_id', 'promote_account',
                'sum(total_money) as total_money',
                'sum(total_number) as total_number',
                'sum(sum_money) as sum_money',
                'status',
                'ti_status',
                'bind_coin_status',
                'create_time'))->where($settMap)
                ->group('promote_id,starttime,endtime,create_time,bind_coin_status')
                ->order('create_time desc')
                ->select();
            M('TotalSettlement', 'tab_')->addAll($dataSett);
            $this->success('结算成功', U('Query/settlement', array('group' => 2)));
        } else {

            /*if (is_array($ids)) {
                $promote_id  = get_promote_id($_REQUEST['promote_account']);
                foreach ($ids as $k => $v) {
                    if(get_settlement($_REQUEST['timestart'],$_REQUEST['timeend'],$promote_id,$_REQUEST[$v]['game_id'])){
                        continue;
                    }

                    $errorStartTime = strtotime($_REQUEST['timestart']);
                    $errorEndTime = strtotime($_REQUEST['timeend'])+24*60*60-1;

                    $game_id = $_REQUEST[$v]['game_id'];

                    $map['fgame_id']=$game_id;
                    $map['register_time']=array('BETWEEN',array($errorStartTime,$errorEndTime));
                    $map['promote_id']=array('in',$promote_id);
                    $u=M('User','tab_');
                    $user=$u->where($map)->setField('settle_check',0);
                    unset($map['register_time']);
                    $map['pay_time']=array('BETWEEN',array($errorStartTime,$errorEndTime));
                    $s=M('spend','tab_');
                    $spend=$s->where($map)->setField('settle_check',0);
                }
            }*/


            $this->error('结算失败');
        }
    }

    public function generatesettlement()
    {
        //批量结算要加判断
        $data['game_id'] = $_REQUEST['game_id'];
        $data['game_name'] = get_game_name($_REQUEST['game_id']);
        $data['promote_id'] = $_REQUEST['promote_id'];
        $data['promote_account'] = get_promote_name($_REQUEST['promote_id']);
        $data['total_money'] = $_REQUEST['spay_amount'];
        $data['total_number'] = $_REQUEST['unum'];
        $data['starttime'] = strtotime($_REQUEST['starttime']);
        $data['endtime'] = strtotime($_REQUEST['endtime']) + 24 * 60 * 60 - 1;
        $data['pattern'] = $_REQUEST['cooperation'] == 'CPS' ? 0 : 1;
        $data['ratio'] = $_REQUEST['cps_ratio'];
        $data['money'] = $_REQUEST['cpa_price'];
        $data['create_time'] = time();
        $data['settlement_number'] = 'JS-' . date('Ymd') . date('His') . sp_random_string(4);
        if (get_settlement($data['starttime'], $data['promote_id'], $data['game_id'])) {
            $this->error('该结算周期不可结算,请重新选择');
        }
        if ($data['pattern']) {
            $data['sum_money'] = $data['total_number'] * $data['money'];
        } else {
            $data['sum_money'] = $data['total_money'] * $data['ratio'] / 100;
        }
        if ($data['game_id'] == '' || $data['promote_id'] == '' || $data['starttime'] == '' || $data['endtime'] == '') {
            $this->error('必要参数不存在');
        }
        $map['fgame_id'] = $data['game_id'];
        // $map['is_check']=1;
        $map['register_time'] = array('BETWEEN', array($data['starttime'], $data['endtime']));
        $allid = get_subordinate_promote_($data['promote_account']);
        $allid[] = $data['promote_account'];
        $map['promote_id'] = array('in', $data['promote_id']);
        $u = M('User', 'tab_');
        $user = $u->where($map)->setField('settle_check', 1);
        unset($map['register_time']);
        $map['pay_time'] = array('BETWEEN', array($data['starttime'], $data['endtime']));
        $s = M('spend', 'tab_');
        $spend = $s->where($map)->setField('settle_check', 1);
        $result = M('settlement', 'tab_')->add($data);
        if ($result) {
            $this->success('结算成功');
        } else {
            $this->error('结算失败');
        }
    }

    public function generatecpsettlement()
    {//cp结算

        $request = I('request.ids');
        if (empty($request)) {
            $this->error('请选择要操作的数据');
        }
        $starttime = strtotime($_REQUEST['timestart']);
        $endtime = strtotime($_REQUEST['endtime']) + 24 * 3600 - 1;
        $map['s.pay_status'] = 1;
        $map['s.selle_status'] = 0;
        foreach ($request as $key => $value) {
            $query = explode(',', $value);

            $ids[] = $query[0];
            $requestData[$key]['game_id'] = $query[0];
            $requestData[$key]['selle_ratio'] = $query[1];
            $requestData[$key]['total'] = $query[2];
        }

        $map['s.game_id'] = array('in', $ids);
        $map['pay_time'] = array('BETWEEN', array($starttime, $endtime));
        $spe = M('spend as s', 'tab_');
        $smap = array('s.selle_time' => date('Y-m-d', time()), 's.selle_status' => 1);
        $data = $spe
            ->field('s.id,s.selle_status,s.selle_time')
            ->join('tab_game as g on g.id=s.game_id', 'LEFT')
            ->where($map)
            ->setField($smap);
        if ($data) {
            $create_time = time();
            foreach ($requestData as $key => $value) {
                $datas[$key]['game_id'] = $value['game_id'];
                $datas[$key]['game_name'] = get_game_name($value['game_id']);
                $datas[$key]['promote_id'] = '0';
                $datas[$key]['promote_account'] = '0';
                $datas[$key]['total_money'] = $value['total'];
                $datas[$key]['total_number'] = 0;
                $datas[$key]['starttime'] = $starttime;
                $datas[$key]['endtime'] = $endtime;
                $datas[$key]['pattern'] = 0;//$_REQUEST['cooperation']=='CPS'?0:1;
                $datas[$key]['ratio'] = $value['selle_ratio'];
                $datas[$key]['sum_money'] = $value['selle_ratio'] * $value['total'] / 100;
                $datas[$key]['money'] = 0;
                $datas[$key]['developers'] = $_REQUEST['developers_id'];
                $datas[$key]['create_time'] = $create_time;
                $datas[$key]['settlement_number'] = 'JS-' . date('Ymd') . date('His') . sp_random_string(4);
                $datas[$key]['bind_coin_status'] = $_REQUEST['bind_coin'];
            }
            $datas = array_values($datas);
            $result = M('settlement', 'tab_')->addAll($datas);
            $settMap['developers'] = $_REQUEST['developers_id'];
            $settMap['starttime'] = $starttime;
            $settMap['endtime'] = $endtime;
            $settMap['create_time'] = $create_time;
            $dataSett = M('settlement', 'tab_')->field(array(
                'settlement_number',
                'starttime', 'endtime',
                'promote_id', 'promote_account',
                'sum(total_money) as total_money',
                'sum(total_number) as total_number',
                'sum(sum_money) as sum_money',
                'status',
                'ti_status',
                'bind_coin_status',
                'developers',
                'create_time',))->where($settMap)
                ->group('developers,starttime,endtime,create_time,bind_coin_status')
                ->order('create_time desc')
                ->select();
            M('TotalSettlement', 'tab_')->addAll($dataSett);
            \Think\Log::actionLog('Query/generatecpsettlement', 'Query', 1);
            $this->success('结算成功', U('Query/cpsettlement', array('group' => 2)));
        } else {
            $this->error('结算失败');
        }
        $map1 = array('status' => 1, 'selle_status' => 1);
        $total = null_to_0(D('spend')->where($map1)->sum('pay_amount'));
        $ttotal = null_to_0(D('spend')->where('pay_time' . total(1))->where($map1)->sum('pay_amount'));
        $ytotal = null_to_0(D('spend')->where('pay_time' . total(5))->where($map1)->sum('pay_amount'));
        $this->assign('total', $total);
        $this->assign('ttotal', $ttotal);
        $this->assign('ytotal', $ytotal);

    }

    public function changeratio()
    {
        $gid = I('request.game_id');
        if (empty($gid)) {
            $this->ajaxReturn(0, "请选择要操作的数据", 0);
            exit;
        }
        $starttime = strtotime($_REQUEST['timestart'] . '-01');
        $endtime = strtotime($_REQUEST['timestart'] . "+1 month -1 day") + 24 * 3600 - 1;
        $map['s.pay_status'] = 1;
        $map['s.selle_status'] = 0;
        $map['s.game_id'] = $_REQUEST['game_id'];
        $map['pay_time'] = array('BETWEEN', array($starttime, $endtime));
        $spe = M('spend as s', 'tab_');
        $data = $spe
            ->field('s.id,s.selle_status,s.selle_ratio')
            ->join('tab_game as g on g.id=s.game_id', 'LEFT')
            ->where($map)
            ->setField('s.selle_ratio', $_POST['ratio']);
        if ($data === false) {
            $this->ajaxReturn(array('status' => 0));
        } else {
            $this->ajaxReturn(['status' => 1, 'data' => $data]);
        }
    }

    public function cp_withdraw($p = 0)
    {
        if (isset($_REQUEST['settlement_number'])) {
            $map['settlement_number'] = array('like', '%' . $_REQUEST['settlement_number'] . '%');
        }
        if (isset($_REQUEST['status'])) {
            $map['status'] = $_REQUEST['status'];
        }
        if (isset($_REQUEST['developers'])) {
            if ($_REQUEST['developers'] == '全部') {
                unset($_REQUEST['developers']);
            } else {
                $map['developers'] = $_REQUEST['developers'];
            }
        } else {
            $map['developers'] = array('neq', 0);

        }

        if (isset($_REQUEST['timestart']) && isset($_REQUEST['timeend'])) {
            $starttime = strtotime($_REQUEST['timestart']);
            $endtime = strtotime($_REQUEST['timeend']) + 24 * 3600 - 1;
            $map['audit_time'] = array('BETWEEN', array($starttime, $endtime));
            unset($_REQUEST['timestart']);
            unset($_REQUEST['timeend']);
        } elseif (isset($_REQUEST['timestart'])) {
            $map['audit_time'] = ['GT', strtotime(I('timestart'))];
            unset($_REQUEST['timestart']);
        } elseif (isset($_REQUEST['timeend'])) {
            $map['audit_time'] = ['LT', strtotime(I('timeend')) + 86399];
            unset($_REQUEST['timeend']);
        }

        if ($_REQUEST['create_time'] == 2) {
            $order = 'create_time desc';
        } elseif ($_REQUEST['create_time'] == 1) {
            $order = 'create_time asc';
        } else {
            $order = 'create_time desc';
        }
        if ($_REQUEST['sum_money'] == 2) {
            $order = 'sum_money desc';
        } elseif ($_REQUEST['sum_money'] == 1) {
            $order = 'sum_money asc';
        }
        $model = array(
            'm_name' => 'withdraw',
            'order' => $order,
            'title' => '渠道提现',
            'template_list' => 'cp_withdraw',
        );
        $map1 = $map;
        $map1['status'] = 1;
        if (isset($_REQUEST['status']) && $_REQUEST['status'] == 0) {
            $total = '0.00';
            $ttotal = '0.00';
            $ytotal = '0.00';
        } else {
            $total = null_to_0(D('withdraw')->where($map1)->sum('sum_money'));
            $ttotal = null_to_0(D('withdraw')->where('audit_time' . total(1))->where($map1)->sum('sum_money'));
            $ytotal = null_to_0(D('withdraw')->where('audit_time' . total(5))->where($map1)->sum('sum_money'));
        }
        $this->assign('stotal', $total);
        $this->assign('ttotal', $ttotal);
        $this->assign('ytotal', $ytotal);
        $user = A('Bill', 'Event');

        $this->m_title = '开发者提现';
        $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'Query/cp_withdraw', 'status' => 1])->find());


        $user->money_list($model, $p, $map);
    }

    public function withdraw()
    {
        $adminid = C('USER_ADMINISTRATOR');//获取超管id
        $adminmobile = M('UcenterMember')->field('mobile')->find($adminid);
        $this->assign('adminmobile', $adminmobile['mobile']);
        if (isset($_REQUEST['widthdraw_number'])) {
            $map['widthdraw_number'] = $_REQUEST['widthdraw_number'];
        }
        if (isset($_REQUEST['ti_status'])) {
            $map['status'] = $_REQUEST['ti_status'];
        }
        if (isset($_REQUEST['promote_account'])) {
            if ($_REQUEST['promote_account'] == '全部') {
                unset($_REQUEST['promote_account']);
            } else {
                $map['promote_account'] = $_REQUEST['promote_account'];
            }
        } else {
            $map['promote_id'] = array('gt', 0);

        }

        $order = 'create_time desc';
        if (isset($_REQUEST['data_order'])) {
            $dataOrder = explode(',', $_REQUEST['data_order']);
            if (count($dataOrder) == 2 && in_array($dataOrder[1], ['create_time', 'sum_money'])) {
                if (intval($dataOrder[0]) == 4) {
                    $order = $dataOrder[1] . ' desc';
                } elseif (intval($dataOrder[0]) == 3) {
                    $order = $dataOrder[1] . ' asc';
                }
            }
        }
        $model = array(
            'm_name' => 'withdraw',
            'order' => $order,
            'title' => '渠道提现',
            'template_list' => 'withdraw',
        );
        $map1 = array('status' => ['neq', -1]);
        //为数据权限添加
        setPowerPromoteIds($map1);

        $total = null_to_0(D('withdraw')->where($map1)->sum('sum_money'));
        $ttotal = null_to_0(D('withdraw')->where('create_time' . total(1))->where($map1)->sum('sum_money'));
        $ytotal = null_to_0(D('withdraw')->where('create_time' . total(5))->where($map1)->sum('sum_money'));
        $this->assign('total', $total);
        $this->assign('ttotal', $ttotal);
        $this->assign('ytotal', $ytotal);
        $user = A('Bill', 'Event');

        $this->m_title = '推广提现';
        $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'Query/withdraw', 'status' => 1])->find());

        //为数据权限添加
        setPowerPromoteIds($map);
        $this->assign('is_admin', is_administrator());
        $user->money_list($model, $p, $map);

    }

    public function set_withdraw_status()
    {
        $withdraw = M('withdraw', "tab_");
        $ids = I('ids', 0);
        $status = 1;
        if (empty($ids)) {
            $this->error('参数异常');
        }
        if (is_array($ids)) {
            $map['id'] = ['in', $ids];
        } else {
            $map['id'] = $ids;
        }
        $map['status'] = 0;
        $save['audit_time'] = time();
        $save['status'] = $status;
        $res = $withdraw->where($map)->save($save);
        if ($res === false) {
            $this->error('审核失败');
        } else {
            $this->success('审核成功', U('withdraw'));
        }
    }

    public function set_withdraw()
    {
        $case = I('case', '');
        if (empty($case)) {
            $data['status'] = 0;
            $data['msg'] = '参数异常';
            $this->ajaxReturn($data);
        }
        switch ($case) {
            case 'deny':
                $data = $this->set_withdraw_deny();
                break;
            case 'upload_transfer_proof':
                $data = $this->set_withdraw_transfer_proof();
                break;
            default:
                $data['status'] = 0;
                $data['msg'] = '参数异常';
                break;
        }
        $this->ajaxReturn($data);
    }

    public function set_withdraw_deny()
    {
        $withdraw = M('withdraw', "tab_");
        $ids = I('ids', 0);
        $respond = I('respond', '');
        $status = -1;
        if (empty($ids)) {
            $data['status'] = 0;
            $data['msg'] = '参数异常';
            return $data;
        }
        if (empty($respond)) {
            $data['status'] = 0;
            $data['msg'] = '请填写驳回说明';
            return $data;
        }
        $idsData = explode(',', $ids);
        if (is_array($ids) || (is_array($idsData) && count($idsData) > 1)) {
            $map['id'] = ['in', $ids];
        } else {
            $map['id'] = $ids;
        }
        $map['status'] = 0;
        $save['audit_time'] = time();
        $save['status'] = $status;
        $save['respond'] = $respond;
        $res = $withdraw->where($map)->save($save);
        if ($res === false) {
            $data['status'] = 0;
            $data['msg'] = '驳回失败';
        } else {
            $data['status'] = 1;
            $data['msg'] = '驳回成功';
        }

        return $data;
    }

    public function set_withdraw_transfer_proof()
    {
        $withdraw = M('withdraw', "tab_");
        $ids = intval(I('ids', 0));
        $transferProof = intval(I('transfer_proof', 0));
        $status = 2;
        if (empty($ids)) {
            $data['status'] = 0;
            $data['msg'] = '参数异常';
            return $data;
        }
        if (empty($transferProof)) {
            $data['status'] = 0;
            $data['msg'] = '请上传汇款证明';
            return $data;
        }
        $downloadId = M('document_download')->where(array('file_id' => $transferProof))->getField('id');
        if (empty($downloadId)) {
            $fileData = M('File')->field('size,ext')->find($transferProof);
            $downloadSave['content'] = '推广员提现订单汇款证明';
            $downloadSave['file_id'] = $transferProof;
            $downloadSave['size'] = $fileData['size'];
            $downloadRes = M('document_download')->add($downloadSave);
            if (!$downloadRes) {
                $data['status'] = 0;
                $data['msg'] = '保存失败';
                return $data;
            }
            $downloadId = $downloadRes;
        }
        $map['id'] = $ids;
        $map['status'] = 1;
        $save['audit_time'] = time();
        $save['status'] = $status;
        $save['transfer_proof'] = $downloadId;
        $res = $withdraw->where($map)->save($save);
        if ($res === false) {
            $data['status'] = 0;
            $data['msg'] = '保存失败';
        } else {
            $data['status'] = 1;
            $data['msg'] = '保存成功';
        }

        return $data;
    }

    private function set_total_settlement_ti_status($settlement_number)
    {
        $totalSettlementMap['settlement_number'] = $settlement_number;
        $totalSettlement = M('TotalSettlement', 'tab_');
        $totalSettlement->where($totalSettlementMap)->save(array("ti_status" => $_REQUEST['status']));
        $dataTotalSettlement = $totalSettlement->where($totalSettlementMap)->find();
        $settMap['promote_id'] = $dataTotalSettlement['promote_id'];
        $settMap['starttime'] = $dataTotalSettlement['starttime'];
        $settMap['endtime'] = $dataTotalSettlement['endtime'];
        $settMap['create_time'] = $dataTotalSettlement['create_time'];
        M("settlement", "tab_")->where($settMap)->save(array('ti_status' => $_REQUEST['status']));
    }


    protected function upPromote($promote_id)
    {
        $model = D('Promote');
        $data['id'] = $promote_id;
        $data['money'] = 0;
        return $model->save($data);
    }

    public function details($promote_id = 0, $create_time = 0)
    {
        $map['promote_id'] = $promote_id;
        $map['create_time'] = $create_time;
        $data = M('settlement', 'tab_')->where($map)->select();
        $total = M('settlement', 'tab_')->where($map)->sum('sum_money');
        $this->assign('total', $total);
        $this->assign('list_data', $data);
        $this->display();
    }

    public function detailscps($developers_id = 0, $create_time = 0, $p = 0)
    {
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $row = !empty(C('ADMIN_LIST_ROW')) ? C('ADMIN_LIST_ROW') : 10;
        $map['developers_id'] = $developers_id;
        $map['create_time'] = $create_time;
        $data = M('settlement', 'tab_')->where($map)->page($page, $row)->select();
        $count = M('settlement', 'tab_')->where($map)->count();
        if ($count > $row) {
            $page = new \Think\Page($count, $row);
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
            $this->assign('_page', $page->show());
        }
        $total = M('settlement', 'tab_')->where($map)->sum('sum_money');
        $this->assign('total', $total);
        $this->assign('list_data', $data);
        $this->display();
    }

    public function withdrawDetails($id)
    {
        $page = intval(I('p', 1));
        $row = intval(I('row', 10));
        $id = intval($id);
        $map['withdraw_id'] = $id;
        $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')
            ->page($page, $row)
            ->select();
        $count = $model->where($map)->count('id');

        //提现状态
        $withdrawStatus = M('withdraw', 'tab_')
            ->where(array('id' => $id))
            ->getField('status');
        $withdrawStatus = \Home\Controller\FinanceController::$withdrawStatus[$withdrawStatus];

        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']);
        }

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

    /**
     * 审核推广提现
     * @author <jszsl001@163.com>
     */

    public function set_withdraw_agree()
    {
        //行为日志判断
        if (I('status') == 1 && I('msg_type') == 5 && I('field') == 'status') {
            //同意推广提现
            action_log('tg_tx_agree', 'withdraw', UID, UID);
        }
        if (I('status') == 2 && I('msg_type') == 6 && I('field') == 'status') {
            //拒绝推广提现
            action_log('tg_tx_disagree', 'withdraw', UID, UID);
        }

        //判断打款类型
        if (I('withdraw_type', 0, 'intval') == 1) {
            //手动打款,直接就改状态
            $this->set_withdraw_status();
        } else {
            $adminid = C('USER_ADMINISTRATOR');//获取超管id
            $adminmobile = M('UcenterMember')->field('mobile')->find($adminid);

            $dx = A('Phone');
            $res = -1;
            $res = $dx->check_tel_code($adminmobile['mobile'], $_POST['code']);
            switch ($res) {
                case '-1':
                    $this->error('短信验证码无效,请重新获取');
                    break;
                case '-2':
                    $this->error('时间超时,请重新获取短信验证码');
                    break;
                case '-3':
                    $this->error('短信验证码不正确,请重新输入');
                    break;
            }
            $withdraw = M('withdraw', "tab_");
            $pay = new \Think\Pay('alipay', C('alipay'));
            $withdraw_way = $_POST['withdraw_way'];
            //支付宝
            if ($withdraw_way == 1) {
                $map['id'] = $_POST['ids'];
                $dind = $withdraw->where($map)->find();
                if ($dind['status'] == 1) {
                    $this->ajaxReturn(['status' => -1, 'info' => '请不要重复打款']);
                }
                $widthdrawNo = "TX_" . date('Ymd') . date('His') . sp_random_string(4);
                $vo = new \Think\Pay\PayVo();
                $vo->setOrderNo($dind['settlement_number'])
                    ->setBatchNo($widthdrawNo)
                    ->setTable('Withdraw')
                    ->setPayMethod("transfer")
                    ->setDetailData('渠道结算提现,订单' . $dind["settlement_number"]);
                $res = $pay->buildRequestForm($vo);
                if ($res == 10000) {
                    $this->ajaxReturn(['status' => 1, 'info' => '打款成功']);
                } else {
                    $this->ajaxReturn(['status' => 0, 'info' => '打款失败']);
                }
            }

        }
    }
}