<?php

namespace Admin\Controller;

use Admin\Model\UserModel;
use Think\Model;
use Base\Service\PromoteService;

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

    const model_name = 'PromoteCoin';

    public function send_lists($p = 0)
    {
//        $promoteRoot = getPowerPromoteIds();
//        if ($promoteRoot) {
//            $extend['promote_id'] =array('in',$promoteRoot);
//        }

//        $promoteRoot = getPowerPromoteIds();
//        $data_empower_type = session('user_auth')['data_empower_type'];
//
//        if ($promoteRoot) {
//            $extend['promote_id'] =array('in',$promoteRoot);
//        } else if(!$promoteRoot&&$data_empower_type!=1){
//            $extend['id'] = array('lt',1);
//        }
        setPowerPromoteIds($extend,'promote_id');

        if (empty($_GET['promote_id'] && $_GET['promote_type'])) {
            $extend['type'] = 1;
            $extend['source_id'] = 0;
            $map = $extend;
        } else {
            $extend['type'] = 1;
            $extend['promote_id'] = $_GET['promote_id'];
            $extend['promote_type'] = $_GET['promote_type'];

        }

        $map['create_time'] = total(1, false);
        $sum['to_day'] = D(self::model_name)->where($map)->sum('num');
        $map['create_time'] = total(5, false);
        $sum['yst_day'] = D(self::model_name)->where($map)->sum('num');

        $sum['all_num'] = D(self::model_name)->where($extend)->sum('num');
        // echo  D(self::model_name)->getLastSql();exit;
        $this->checkListOrCountAuthRestMap($map,[]);
        $this->assign('sum', $sum);

        $this->m_title = '平台币发放(推广员)';
        $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'PromoteCoin/send_lists', 'status' => 1])->find());


        parent::order_lists(self::model_name, $_GET["p"], $extend);
    }

    public function deduct_lists($p = 0)
    {
        ini_set('memory_limit', '512M');
//        var_dump(session('user_auth')['uid']);die();
        if (isset($_GET['type']) && $_GET['type'] == 2) {
            $extend['type'] = 2;
            $extend['source_id'] = 0;
            $map = $extend;
            $model_name = self::model_name;
        } else {
            $model_name = "user_coin";
            if (isset($_GET['account'])) {
                $extend['user_account'] = array('like', '%' . I('account') . '%');

            }

        }
        $extend['op_id'] = session('user_auth')['uid'];
//        $promoteRoot = getPowerPromoteIds();
//        if ($promoteRoot) {
//            $map['promote_id'] =array('in',$promoteRoot);
//        }

//        $promoteRoot = getPowerPromoteIds();
//        $data_empower_type = session('user_auth')['data_empower_type'];
//
//        if ($promoteRoot) {
//            $map['promote_id'] =array('in',$promoteRoot);
//        } else if(!$promoteRoot&&$data_empower_type!=1){
//            $map['id'] = array('lt',1);
//        }
        setPowerPromoteIds($map,'promote_id');
        $this->checkListOrCountAuthRestMap($map,[]);

        $map['create_time'] = total(1, false);
        $sum['to_day'] = D(self::model_name)->where($map)->sum('num');
        $map['create_time'] = total(5, false);
        $sum['yst_day'] = D(self::model_name)->where($map)->sum('num');
        $model_name = empty($model_name) ? self::model_name : $model_name;
        $sum['all_num'] = D($model_name)->where($extend)->sum('num');
        $this->assign('sum', $sum);
        $this->m_title = '平台币收回';
        $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'PromoteCoin/deduct_lists', 'status' => 1])->find());
        parent::order_lists($model_name, $_GET["p"], $extend);
    }

    /**
     *扣除绑定币记录列表
     */
    public function deductBindBanlanList()
    {
        if (isset($_GET['type']) && $_GET['type'] == 2) {
            $extend['type'] = 2;
            $extend['source_id'] = 0;
            $map = $extend;
            $model_name = self::model_name;
        } else {
            $model_name = "user_coin";
            if (isset($_GET['user_id'])) {
                $extend['user_id'] = I('user_id');
            }

        }
        $map['create_time'] = total(1, false);
        $sum['to_day'] = D(self::model_name)->where($map)->sum('num');
        $map['create_time'] = total(5, false);
        $sum['yst_day'] = D(self::model_name)->where($map)->sum('num');
        $sum['all_num'] = D(self::model_name)->where($extend)->sum('num');
        $this->assign('sum', $sum);
        parent::order_lists($model_name, $_GET["p"], $extend);
    }

    /**
     * 发放平台币
     */
    public function send()
    {
        $this->m_title = '平台币发放(推广员)';

        $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'PromoteCoin/send_lists', 'status' => 1])->find());
        $this->add(1, 'send_lists', 2);
    }

    public function deduct()
    {
        $this->m_title = '平台币收回';
        $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'PromoteCoin/deduct_lists', 'status' => 1])->find());
        $this->add(2, 'deduct_lists', $_REQUEST['typee'] ? $_REQUEST['typee'] : 1);
    }

    public function add($type, $url, $tt = 1)
    {
        $model = M('Model')->getByName(self::model_name);
        $model || $this->error('模型不存在!');
        if (IS_POST) {
            //验证二级密码
            $pwd = I('second_pwd');
            $res = D('Member')->check_sc_pwd($pwd);
            if (!$res) {
                $this->error('二级密码错误');
            }
            $model_name = $tt == 1 ? "UserCoin" : "PromoteCoin";

            $res = D($model_name)->create();
            if (!$res) {
                $this->error(D($model_name)->getError());
            }
            //平台币修改
            if ($tt == 1) {
                if (empty(I('user_id'))) {
                    $this->error('请输入正确的玩家账号');
                }
                $res = D('User')->edit_user_balance_coin(I('user_id'), abs(I('num')));
            } else {
                $promoteService = new PromoteService();
                if ($type == 1) {
                    $res = $promoteService->adminIncCoin(I('promote_id'), abs(I('num')), session('user_auth.uid'));
                } elseif ($type == 2) {
                    $res = $promoteService->adminDecCoin(I('promote_id'), abs(I('num')), session('user_auth.uid'));
                }
            }

            if ($res) {
                //------操作日志-begin
                if($type == 1){
                    //发放
                    $keyname = getPromoteAccount(I('promote_id'));
                    $keyname .= ("/".abs(I('num')));
                    $optionarr = array(
                        "op_type"=>1,
                        "key"=>$keyname,
                        "menu"=>"充值-平台币订单-后台发放(推广员)-",
                        "url"=>U("PromoteCoin/send_lists",array("model"=>"PromoteCoin","promote_id"=>I('promote_id')))
                    );
                    $promote_type = $_GET['promote_type'];
                    if($promote_type == '1'){
                        $optionarr['menu'] .= "给会长发放";
                    }elseif($promote_type == '2'){
                        $optionarr['menu'] .= "给部门长发放";
                    }elseif($promote_type == '3'){
                        $optionarr['menu'] .= "给组长发放";
                    }elseif($promote_type == '4'){
                        $optionarr['menu'] .= "给组员发放";
                    }
                }else{
                    //收回
                    $optionarr = array(
                        "op_type"=>1,
                        "menu"=>"充值-平台币订单-平台币收回-",
                        "url"=>U("PromoteCoin/send_lists",array("model"=>"PromoteCoin","promote_id"=>I('promote_id')))
                    );
                    if($tt == 1){
                        //收回玩家
                        $userid = I('user_id');
                        $user_account = M("User","tab_")->where("id={$userid}")->field("account")->find()['account'];
                        $keyname = ($user_account."/".abs(I('num')));
                        $optionarr['key'] = $keyname;
                        $optionarr['menu'] .= "玩家收回";
                        $optionarr['url'] = U("PromoteCoin/deduct_lists",array("type"=>"1","account"=>$user_account));
                    }else{
                        //收回推广员
                        $optionarr['key'] = (getPromoteAccount(I('promote_id'))."/".abs(I('num')));
                        $optionarr['menu'] .= "推广员收回";
                        $optionarr['url'] = U("PromoteCoin/deduct_lists",array("type"=>"2","promote_id"=>I('promote_id')));
                    }
                }
                addOperationLog($optionarr);
                //-------操作日志-end
                
                $this->success('操作成功!', U($url, array('model' => $model['name'], 'type' => $tt)));
            } else {
                $this->error('操作失败!', U($url, array('model' => $model['name'], 'type' => $tt)));
            }
        } else {
            $fields = get_model_attribute($model['id']);

            $this->assign('model', $model);
            $this->assign('fields', $fields);
            $this->meta_title = '平台币操作';
            $this->display($model['template_add'] ? $model['template_add'] : '');
        }
    }

    /**
     * 平台币转移记录
     */
    public function record($p = 0)
    {
        $extend['type'] = 2;
        $extend['source_id'] = ['neq', 0];

        if (isset($_REQUEST['promote_id'])) {
            $extend['promote_id'] = $_REQUEST['promote_id'];
        }
        $source_ids = [];
        if (!empty($_REQUEST['source_id'])) $source_ids[] = $_REQUEST['source_id'];
        if (!empty($_REQUEST['grand_id'])) $source_ids[] = $_REQUEST['grand_id'];
        if (!empty($_REQUEST['child_id'])) $source_ids[] = $_REQUEST['child_id'];
        if (!empty($source_ids)) $extend['source_id'] = ['in', $source_ids];
        //为数据权限添加
        setPowerPromoteIds($extend);
        $map = $extend;
        $map['create_time'] = total(1, false);
        $sum['to_day'] = D(self::model_name)->where($map)->sum('num');
        $map['create_time'] = total(5, false);
        $sum['yst_day'] = D(self::model_name)->where($map)->sum('num');
        $sum['all_num'] = D(self::model_name)->where($extend)->sum('num');
        $this->assign('sum', $sum);
        $this->meta_title = '平台币转移记录';
        $this->m_title = '平台币转移记录';
        $this->assign('commonset', M('Kuaijieicon')->where(['url' => 'PromoteCoin/record', 'status' => 1])->find());


        /* //parent::order_lists(self::model_name,$_GET["p"],$extend); */

        $page = intval($p);
        $page = $page ? $page : 1;

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

        $pc = D(self::model_name);
        $data = $pc->alias('c')
            ->field('c.*,p.account as source_name, p.parent_id, p.level')
            ->join('tab_promote p on c.source_id = p.id', 'left')
            ->where($extend)
            ->order('id desc')
            ->page($page, $row)
            ->select();

        $count = $pc->where($extend)->count();

        $this->checkListOrCountAuthRestMap($map,[]);

        $page = set_pagination($count, $row);
        if ($page) {
            $this->assign('_page', $page);
        }
        $this->assign('list_data', $data);
        $show_data_power = (is_administrator()|| session('user_auth')['show_data']);
        $this->assign('show_data_power', $show_data_power);
        $this->display();

    }

    //获取线下充值列表
    public function offlineList($p = 0)
    {
        //获取记录
        $map = array();
        $map['pay_type'] = 2;
        $map['is_del'] = 0;
        //其他条件查询
        if (isset($_REQUEST['promote_account'])) {
            $map['promote_account'] = array('like', '%' . trim($_REQUEST['promote_account']) . '%');
            unset($_REQUEST['promote_account']);
        }
        if (isset($_REQUEST['time-start']) && isset($_REQUEST['time-end'])) {
            $map['create_time'] = array('BETWEEN', array(strtotime($_REQUEST['time-start']), strtotime($_REQUEST['time-end']) + 24 * 60 * 60 - 1));
            unset($_REQUEST['time-start']);
            unset($_REQUEST['time-end']);
        } elseif (isset($_REQUEST['time-start'])) {
            $map['create_time'] = ['GT', strtotime(I('time-start'))];
            unset($_REQUEST['time-start']);
        } elseif (isset($_REQUEST['time-end'])) {
            $map['create_time'] = ['LT', strtotime(I('time-end')) + 86399];
            unset($_REQUEST['time-end']);
        }
        if (isset($_REQUEST['order_status'])) {
            $map['order_status'] = $_REQUEST['order_status'];
            unset($_REQUEST['order_status']);
        }

//        $promoteRoot = getPowerPromoteIds();
//        $data_empower_type = session('user_auth')['data_empower_type'];
//
//        if ($promoteRoot) {
//            $map['promote_id'] =array('in',$promoteRoot);
//        } else if(!$promoteRoot&&$data_empower_type!=1){
//            $map['id'] = array('lt',1);
//        }
        setPowerPromoteIds($map,'promote_id');

        $data = D("CoinPayOrder")->lists($_GET["p"], $map, $order);
        // dump($data);
        //执行查询
        // parent::order_lists("CoinPayOrder",$_GET["p"],$extend);
        $this->meta_title = '线下充值审核列表';
        $this->assign('list_data', $data['data']);
        $this->assign('_page', $data['page']);
        $this->display();
        # code...
    }

    public function offlineOrderInfo()
    {
        if (!isset($_REQUEST['id'])) {
            exit("参数错误");
        }
        $id = $_REQUEST['id'];
        $data = D("CoinPayOrder")->info($id);
        $this->meta_title = '线下充值审核详情';
        $this->assign('data', $data);
        $this->display();
        # code...
    }

    //审核通过
    public function offlineAgree()
    {
        if (!isset($_REQUEST['ids']) || count($_REQUEST['ids']) < 1) {
            exit("参数错误");
        }
        $ids = I("ids");
        $count = count($ids);
        //执行操作
        for ($i = 0; $i < $count; $i++) {
            $this->doOfflineAgree($ids[$i]);
        }
        $this->success("批量通过成功");
        # code...
    }

    //批量审核拒绝
    public function offlineReject()
    {
        if (!isset($_REQUEST['ids']) || count($_REQUEST['ids']) < 1) {
            exit("参数错误");
        }
        $ids = I("ids");
        $count = count($ids);
        //执行操作
        for ($i = 0; $i < $count; $i++) {
            $this->orderReject($ids[$i]);
        }
        $this->success("批量拒绝成功");
        # code...
    }

    public function doOfflineAgree($id)
    {
        //获取记录
        $order = D("CoinPayOrder")->info($id);
        if ($order['order_status'] != 2) {
            return;
        }
        //
        $balance_map['promote_id'] = $order['promote_id'];
        $balance_map['game_id'] = 0;
        $balance = M('promote_balance_coin', 'tab_')->where($balance_map)->find();
        $this->balance_coin_update($order, $balance);//更新汇总
        $this->coin_record_add($order, $balance); //添加流水
        $this->promote_balance_coin_update($order); //更新推广员平台币余额
        $this->orderAgree($id);//更新表
    }

    public function orderReject($id)
    {
        $order = D("CoinPayOrder")->info($id);
        if ($order['order_status'] != 2) {
            return;
        }
        $savedata = array();
        $auth = $_SESSION['onethink_admin']['user_auth'];
        $savedata['auditor_id'] = $auth['uid'];
        $savedata['auditor_account'] = $auth['username'];
        $savedata['auditor_time'] = time();
        $savedata['order_status'] = -1;
        D("CoinPayOrder")->updateData($savedata, $id);
        # code...
    }

    public function orderAgree($id)
    {
        $savedata = array();
        $auth = $_SESSION['onethink_admin']['user_auth'];
        $savedata['auditor_id'] = $auth['uid'];
        $savedata['auditor_account'] = $auth['username'];
        $savedata['auditor_time'] = time();
        $savedata['order_status'] = 4;
        D("CoinPayOrder")->updateData($savedata, $id);
        # code...
    }

    // 添加流水
    public function coin_record_add($order, $balance)
    {
        $data['sn'] = date('Ymd') . date('His') . sp_random_num(6);
        $data['type'] = 1;
        $data['sub_type'] = 1;
        $data['target_id'] = $order['promote_id'];
        $data['target_type'] = 1;
        $data['ref_id'] = $order['id'];
        $data['coin'] = $order['real_amount'];
        $data['balance_coin'] = $balance['num'] + $order['coin_num'];
        $data['remark'] = $order['remark'];
        $data['create_time'] = time();
        $data['description'] = '线下充值';
        M('promote_coin_record', 'tab_')->data($data)->add();
    }

    //更新汇总
    public function balance_coin_update($order, $balance)
    {
        if (!empty($balance)) {
            $map['promote_id'] = $order['promote_id'];
            $map['game_id'] = 0;
            M('promote_balance_coin', 'tab_')->where($map)->setInc('num', $order['coin_num']);
        } else {
            $balance['promote_id'] = $order['promote_id'];
            $balance['game_id'] = 0;
            $balance['num'] = $order['coin_num'];
            M('promote_balance_coin', 'tab_')->data($balance)->add();
        }
    }

    //更新推广员平台币余额
    public function promote_balance_coin_update($order)
    {
        $map['id'] = $order['promote_id'];
        M('promote', 'tab_')->where($map)->setInc('balance_coin', $order['coin_num']);
    }

    //玩家账号查询
    public function getUserAccount()
    {
        $account = trim(I('post.account', ''));
        if (empty($account)) {
            $data['status'] = -1;
            $data['msg'] = '请输入玩家账号';
            $this->ajaxReturn($data);
        }
        $map['account'] = $account;
        setPowerPromoteIds($map,'promote_id');

        $user = M('user', 'tab_')->field('id,account,balance')->where($map)->find();
        if (empty($user)) {
            $data['status'] = 0;
            $data['msg'] = '该玩家账号不存在';
        } else {
            $data['status'] = 1;
            $data['user'] = $user;
        }
        $this->ajaxReturn($data);
    }

    public function checkUsername($account)
    {
        $model = new UserModel();
        return $model->checkUsername($account);
    }
}