<?php

namespace Admin\Controller;

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){
    if(empty($_GET['promote_id']&&$_GET['promote_type'])){
        $extend['type'] = 1;
        $extend['source_id'] = 0;
        $map = $extend;
    }else{
        $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->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){
        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').'%') ;

            }

        }
        $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){
                $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){
                $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['source_id'])) {$extend['source_id'] = $_REQUEST['source_id'];}*/
				if(isset($_REQUEST['promote_id'])) {$extend['promote_id'] = $_REQUEST['promote_id'];}
        if(!empty($_REQUEST['source_id']) && !empty($_REQUEST['grand_id'])) {
            $extend['source_id'] = ['in',[$_REQUEST['source_id'],$_REQUEST['grand_id']]];
        } elseif (!empty($_REQUEST['source_id'])) {
            $extend['source_id'] = $_REQUEST['source_id'];
        } elseif (!empty($_REQUEST['grand_id'])) {
            $extend['source_id'] = $_REQUEST['grand_id'];
        }

        $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.grand_id')
                        ->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();

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

				$this->assign('list_data', $data);

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