<?php

namespace Home\Controller;

use OT\DataDictionary;
use User\Api\PromoteApi;
use Base\Service\PromoteService;
use Base\Service\PromoteCoinRecordService;
use Base\Service\PromoteCoinTransferLogService;

/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class PromoteCoinController extends BaseController
{
    const MODEL_NAME = 'PromoteCoin';

    public static $type = [
        1 => '充值',
        2 => '消费',
    ];

    public static $subType = [
        1 => '平台充值',
        2 => '线下转账',
        3 => '转账充值',
        4 => '转账消费',
        5 => '后台扣除',
        6 => '迁移回收',
        7 => '迁移扣除',
    ];

    public static $handleType = [
        1 => '会长转账',
        2 => '组长转账',
        3 => '推广员转账',
        4 => '玩家转账',
    ];

    public function myCoin($p = 0)
    {
        $loginPromote = $this->getLoginPromote();
        $map = [];
        $map['promote_id'] = $loginPromote['id'];
        empty(I('game_id')) || $map['game_id'] = I('game_id');
        empty(I('status')) || $map['status'] = I('status');

        if (!empty(I('coin_type'))) {
            switch (I('coin_type')) {
                case 1:
                    $map['game_id'] = 0;
                    break;
                case 2:
                    $where['game_id'] = ['gt', 0];
                    break;
            }
        }
        $where['_string'] = '1 = 1';
        $map['_complex'] = $where;

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

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

        $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)
            ->page($page, $row)
            ->select();

        $count = M('PromoteBalanceCoin', 'tab_')
            ->join('left join tab_game on tab_promote_balance_coin.game_id = tab_game.id')
            ->where($map)
            ->count();

        //分页
        $parameter['p'] = I('get.p', 1);
        $parameter['row'] = I('get.row');
        empty(I('game_id')) || $parameter['game_id'] = I('game_id');
        empty(I('status')) || $parameter['status'] = I('status');
        empty(I('coin_type')) || $parameter['coin_type'] = I('coin_type');

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

        $this->meta_title = '我的平台币';
        $this->assign('data', $data);
        $this->assign('count', $count);
        $this->display();
    }

    public function coinDetails()
    {
        $type = I('type', 0);
        $subType = I('sub_type', 0);
        $targetType = I('target_type', '');
        $startTime = I('start_time', '');
        $endTime = I('end_time', '');
        $gameId = I('game_id', 0);
        $loginPromote = $this->getLoginPromote();

        $conditions = [];
        $conditions['game_id'] = $gameId;
        $conditions['promote_id'] = $loginPromote['id'];
        if ($type != 0) {
            $conditions['type'] = $type;
        }
        if ($subType != 0) {
            $conditions['sub_type'] = $subType;
        }
        if ($targetType != '') {
            $targetTypeRow = explode('_', $targetType);
            $conditions['target_type'] = $targetTypeRow[0];
            if (count($targetTypeRow) == 2) {
                $conditions['target_level'] = $targetTypeRow[1];
            }
        }
        if ($startTime != '' || $endTime != '') {
            if ($startTime != '') {
                $conditions['create_time'] = ['egt', strtotime($startTime. ' 00:00:00')];
            }
            if ($endTime != '') {
                $conditions['create_time'] = ['elt', strtotime($endTime. ' 23:59:59')];
            }
        }

        $service  = new PromoteCoinRecordService();
        $query = M('promote_coin_record', 'tab_')->where($conditions);

        list($items, $pagination, $count) = $this->paginate($query);

        $records = [];
        foreach ($items as $item) {
            $records[] = [
                'id' => $item['id'],
                'sn' => $item['sn'],
                'type_text' => $service->getTypeText($item['type']),
                'sub_type_text' => $service->getSubTypeText($item['sub_type']),
                'target_type_text' => $service->getTargetTypeText($item['target_type'], $item['target_level']),
                'coin' => $item['coin'],
                'balance_coin' => $item['balance_coin'],
                'remark' => $item['remark'],
                'description' => $item['description'],
                'create_time' => date('Y-m-d H:i:s', $item['create_time']),
            ];
        }
        $this->meta_title = '交易明细';

        $this->assign('subTypes', PromoteCoinRecordService::$subTypes);
        $this->assign('types', PromoteCoinRecordService::$types);
        $this->assign('targetTypeLevels', $service->getTargetTypeLevels());
        $this->assign('records', $records);
        $this->assign('count', $count);
        $this->assign('gameId', $gameId);
        $this->assign('pagination', $pagination);
        $this->display();
    }

    public function coinDetail()
    {
        $this->meta_title = '查看明细';
        $id = I('id', 0);
        $service  = new PromoteCoinRecordService();
        $loginPromote = $this->getLoginPromote();
        $item = M('promote_coin_record', 'tab_')->where(['promote_id' => $loginPromote['id'], 'id' => $id])->find();
        $refOrderName = '';
        $ref = $service->getRef($item);
        $refDetail = $service->getRefDetail($item, $ref);
        $record = [
            'id' => $item['id'],
            'sn' => $item['sn'],
            'type_text' => $service->getTypeText($item['type']),
            'sub_type_text' => $service->getSubTypeText($item['sub_type']),
            'target_type_text' => $service->getTargetTypeText($item['target_type'], $item['target_level']),
            'coin_type' => $item['game_id'] > 0 ? '绑定币' : '通用币',
            'coin' => $item['coin'],
            'balance_coin' => $item['balance_coin'],
            'remark' => $item['remark'],
            'description' => $item['description'],
            'create_time' => date('Y-m-d H:i:s', $item['create_time']),
        ];
        
        $this->assign('record', $record);
        $this->assign('refDetail', $refDetail);
        $this->display();
    }

    public function index($p = 0)
    {
        $map['type'] = 1;
        $map['promote_id'] = PID;
        $end_time = strtotime(I('time_end')) + 24 * 60 * 60 - 1;
        $start_time = strtotime(I('time_start'));
        if (!empty($_REQUEST['time_start']) && !empty($_REQUEST['time_end'])) {
            $map['create_time'] = array('BETWEEN', array(strtotime($_REQUEST['time_start']), strtotime($_REQUEST['time_end']) + 24 * 60 * 60 - 1));
        } elseif (!empty($_REQUEST['time_start']) && empty($_REQUEST['time_end'])) {
            $map['create_time'] = array('egt', strtotime($_REQUEST['time_start']));
        } elseif (empty($_REQUEST['time_start']) && !empty($_REQUEST['time_end'])) {
            $map['create_time'] = array('elt', strtotime($_REQUEST['time_end']) + 24 * 60 * 60 - 1);
        }
        $extend['map'] = $map;
        $this->meta_title = '平台币入账记录';
        $this->data_lists($p, self::MODEL_NAME, $extend);
    }

    public function data_lists($p, $model, $extend = [])
    {
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据


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

        $model = D($model);
        // 条件搜索
        $map = [];
        foreach (I('get.') as $name => $val) {
            $map[$name] = $val;
        }
        $map = array_merge($map, $extend['map']);
        $lists_data = $model->where($map)->order('create_time desc')->page($page, $row)->select();
        $count = $model->where($map)->count();

        //分页


        $parameter = $_POST;
        $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('lists_data', $lists_data);
        $this->assign('count', $count);
        $this->display();
    }

    /**
     * 转移平台币
     */
    public function shift()
    {
        $loginPromote = $this->getLoginPromote();
        if (IS_POST) {
            
            $num = I('num');
            $password = I('password');
            $shiftUserType = I('shift_user_type', 0);
            $targetId = I('target_id', 0);
            $gameId = I('game_id', 0);
            $remark = I('remark', '');
            $coinType = I('coin_type', 1);

            if (!is_numeric($num)) {
                $this->ajaxReturn(['status' => 0, 'msg' => '发送数量必须是数字']);
            }

            if ($num <= 0) {
                $this->ajaxReturn(['status' => 0, 'msg' => '发送数量不正确']);
            }

            $promoteService = new PromoteService();
            if ($loginPromote['second_pwd'] !== $promoteService->password($password, UC_AUTH_KEY)) {
                $this->ajaxReturn(['status' => 0, 'msg' => '安全密码错误']);
            }
            if ($shiftUserType == 0) {
                $this->ajaxReturn(['status' => 0, 'msg' => '请选择帐号类型']);
            }
            if ($shiftUserType == 4 && $gameId == 0) {
                $this->ajaxReturn(['status' => 0, 'msg' => '请选择游戏']);
            }

            $params = [
                'from_promote_id' => $loginPromote['id'],
                'num' => $num,
                'remark' => $remark,
                'game_id' => $gameId,
                'is_use_bind' => $coinType == 1 ? false : true,
            ];

            $result = [];
            if ($shiftUserType == 1 || $shiftUserType == 2 || $shiftUserType == 3) {
                $params['promote_id'] = $targetId;
                $result = $promoteService->shiftPromoteCoin($params);
            } elseif ($shiftUserType == 4) {
                $params['user_id'] = $targetId;
                $result = $promoteService->shiftUserCoin($params);
            }

            if ($result['status']) {
                $this->ajaxReturn(['status' => 1, 'msg' => '转账成功!']);
            } else {
                $this->ajaxReturn(['status' => -1, 'msg' => $result['msg']]);
            }
        } else {
            $this->meta_title = "平台币转移";
            $this->display();
        }
    }

    /**
     * 获取渠道平台币
     * @param $id
     */
    public function getCoin()
    {
        $gameId = I('game_id', 0);
        $map = [
            'promote_id' => session('promote_auth.pid'),
            'game_id' => ['in', [$gameId, 0]],
        ];
        $records = M('PromoteBalanceCoin', 'tab_')->where($map)->select();

        $gameCoin = 0;
        $commonCoin = 0;
        foreach ($records as $record) {
            if ($record['game_id'] == 0) {
                $commonCoin = $record['num'];
            } elseif ($gameId > 0 && $record['game_id'] == $gameId) {
                $gameCoin = $record['num'];
            }
        }
        $data = [
            'commonCoin' => $commonCoin,
            'gameCoin' => $gameCoin
        ];
        $this->ajaxReturn(['status' => true, 'msg' => '成功', 'data' => $data]);
    }

    public function get_coin($id)
    {
        $data = D('promote')->find($id);
        $res['coin'] = $data['balance_coin'];
        $this->ajaxReturn($res);
    }

    public function transferLogs()
    {
        $this->meta_title = "平台币转移记录";

        $gameId = I('game_id', -1);
        $account = I('account', '');
        $sn = I('sn', '');
        $startTime = I('time_end', '');
        $endTime = I('time_start', '');

        $loginPromote = $this->getLoginPromote();
        $conditions = ['promote_id' => $loginPromote['id']];
        if ($startTime != '' || $endTime != '') {
            if ($startTime != '') {
                $conditions['create_time'] = ['egt', strtotime($startTime. ' 00:00:00')];
            }
            if ($endTime != '') {
                $conditions['create_time'] = ['elt', strtotime($endTime. ' 23:59:59')];
            }
        }
        if($sn) {
            $conditions['sn'] = $sn;
        }
        if($account) {
            $map1['account'] = ['like','%'.$account.'%'];
            $promotesRs = M('promote','tab_')->field('id')->where($map1)->select();
            $idArr = "";
            foreach ($promotesRs as $key => $value) {
                $idArr .= intval($value['id']).',';
            }
            $idArr1 = rtrim($idArr,',');
            $conditions['target_id'] = ['in',$idArr1];
         }

        $query = M('promote_coin_transfer_log', 'tab_')->where($conditions)->order('create_time desc');
        list($logs, $pagination, $count) = $this->paginate($query);
        $service = new PromoteCoinTransferLogService();

        $gameIds = [];
        $promoteIds = [];
        $uesrIds = [];
        foreach ($logs as $log) {
            $gameIds[] = $log['game_id'];
            if ($log['target_type'] == 1) {
                $promoteIds[] = $log['target_id'];
            }
            if ($log['target_type'] == 2) {
                $uesrIds[] = $log['target_id'];
            }
        }
        $games = [];
        $promotes = [];
        $users = [];
        if (count($gameIds) > 0) {
            $games = M('game', 'tab_')->field(['id', 'game_name'])->where(['id' => ['in', $gameIds]])->select();
        }
        if (count($promoteIds) > 0) {
            $promotes = M('promote', 'tab_')->field(['id', 'account'])->where(['id' => ['in', $promoteIds]])->select();
        }
        if (count($uesrIds) > 0) {
            $users = M('user', 'tab_')->field(['id', 'account'])->where(['id' => ['in', $uesrIds]])->select();
        }
        $users = index_by_column('id', $users);
        $promotes = index_by_column('id', $promotes);
        $games = index_by_column('id', $games);
        $records = [];
        foreach ($logs as $log) {
            $targetAccount = '';
            if ($log['target_type'] == 1) {
                $targetAccount = isset($promotes[$log['target_id']]) ? $promotes[$log['target_id']]['account'] : '未知推广账号';
            }
            if ($log['target_type'] == 2) {
                $targetAccount = isset($users[$log['target_id']]) ? $users[$log['target_id']]['account'] : '未知玩家';
            }
            $records[] = [
                'id' => $log['id'],
                'sn' => $log['sn'],
                'target_account' => $targetAccount,
                'game_name' => isset($games[$log['game_id']]) ? $games[$log['game_id']]['game_name'] : '所有游戏',
                'target_type_text' => $service->getTargetTypeText($log['target_type'], $log['target_level']),
                'num' => $log['num'],
                'description' => $log['description'],
                'status_text' => '成功',
                'create_time' => date('Y-m-d H:i:s', $log['create_time'])
            ];
        }
        $this->assign('pagination', $pagination);
        $this->assign('count', $count);
        $this->assign('records', $records);
        $this->display();
    }

    public function detail()
    {
        $id = I('id', 0);
        $record = M('promote_coin_transfer_log', 'tab_')->where(['id' => $id])->find();
        $targetName = '';
        $sourceAccount = '';
        $sourcePromote = null;
        if ($record['target_type'] == 2) {
            $targetUser = M('user', 'tab_')->where(['id' => $record['target_id']])->find();
            $targetName = $targetUser['real_name'];
            $targetAccount = $targetUser['account'];
        } elseif ($record['target_type'] == 1) {
            $targetPromote = M('promote', 'tab_')->where(['id' => $record['target_id']])->find();
            $targetName = $targetPromote['real_name'];
            $targetAccount = $targetPromote['account'];
        }
        $service = new PromoteCoinTransferLogService();
        $targetTypeText = $service->getTargetTypeText($record['target_type'], $record['target_level']);
        $gameName = '所有游戏';
        if ($record['game_id'] > 0) {
            $game = M('Game', 'tab_')->field('game_name')->where(['id' => $record['game_id']])->find();
            $gameName = $game['game_name'];
        }

        $item = [
            'id' => $record['id'],
            'sn' => $record['sn'],
            'game_name' => $gameName,
            'create_time' => date('Y-m-d H:i:s', $record['create_time']),
            'target_name' => $targetName,
            'target_account' => $targetAccount,
            'target_type_text' => $targetTypeText,
            'description' => $record['description'],
            'remark' => $record['remark'],
            'status' => $record['status'] == 1 ? '成功' : '失败',
            'num' => $record['num'],
        ];
        $this->assign('item', $item);
        $this->display();
    }

    public function getHandleType($promoteCoin, $promote)
    {
        if ($promoteCoin['source_type'] == 2) {
            return '玩家转账';
        } else {
            $promoteService = new PromoteService();
            $levelName = $promoteService->getLevelName($promote['level']);
            return $levelName . '转账';
        }
    }


    /*
    * 平台币记录
    * @author 鹿文学
    */
    public function lists($p = 1)
    {
        $page = intval($p);

        $page = $page ? $page : 1;

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

        SafeFilter($_REQUEST);

        switch ($_REQUEST['source']) {
            case 1:
                {/* 后台发放 */
                    $data = D(self::MODEL_NAME)->grant($map, $page, $row);
                };
                break;
            case 2:
            case 3:
            case 4:
            case 5:
                {
                    $data = D('Balance')->recharge($map, $page, $row, $_REQUEST['source'] - 1);
                };
                break;
            default:
            {

                $data = D(self::MODEL_NAME)->all_coin($page, $row);

            }
        }


        $count = $data['count'];

        $parameter = array(
            'p' => I('get.p', 1),
            'row' => I('get.row'),
            'source' => I('request.source'),
            'order_number' => I('request.order_number'),
            'account' => I('request.account'),
        );

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


        $this->assign('lists_data', $data['list']);
        $this->meta_title = '平台币记录';
        $this->display();

    }

    /*
    * 批量删除平台币记录
    * @author 鹿文学
    */
    public function del_promote_coin()
    {

        if (empty($_REQUEST['ids'])) {
            $this->ajaxReturn(['status' => 0, 'info' => '请选择要删除的数据']);
        } else {

            $pids = '';
            $bids = '';
            foreach ($_REQUEST['ids'] as $k => $v) {
                $arr = explode(',', $v);
                if ($arr[1] && $arr[1] != '--') {
                    $bids[] = $arr[0];
                } else {
                    $pids[] = $arr[0];
                }
            }

            if (is_array($bids)) {
                $res1 = D('Balance')->del($bids);
            }

            if (is_array($pids)) {
                $res2 = D(self::MODEL_NAME)->del($pids);
            }

            if ($res1 + $res2 > 0) {
                $this->ajaxReturn(['status' => 1, 'info' => '删除成功']);
            } else {
                $this->ajaxReturn(['status' => 1, 'info' => '删除失败']);
            }

        }

    }

    /*
    * 删除平台币记录
    * @author 鹿文学
    */
    public function del_promote_coin_id()
    {
        if ($_REQUEST['order_number'] && $_REQUEST['order_number'] != '--') {
            $res = D('Balance')->del($_REQUEST['id']);
        } else {
            $res = D(self::MODEL_NAME)->del($_REQUEST['id']);
        }

        if ($res) {
            $this->ajaxReturn(['status' => 1, 'info' => '删除成功']);
        } else {
            $this->ajaxReturn(['status' => 1, 'info' => '删除失败']);
        }
    }


    public function subPromotes()
    {
        $level = I('level', 0);
        $account = I('account', '');
        $mobile = I('mobile', '');
        $promote = $this->getLoginPromote();
        $map = [];
        if ($level > 0) {
            $map['level'] = $level;
        }
        $map['chain'] = ['like', $promote['chain'] . $promote['id'] . '/%'];

        if ($account) {
            $map['account'] = ['like', '%' . $account . '%'];
        }
        if ($mobile) {
            $map['mobile_phone'] = ['like', '%' . $mobile . '%'];
        }
        $query = M('promote', 'tab_')->field(['id', 'account', 'real_name', 'mobile_phone'])->where($map);
        list($promotes, $pagination, $count) = $this->paginate($query);
        $records = [];
        foreach ($promotes as $promote) {
            $records[] = [
                'account' => $promote['account'],
                'mobile' => $promote['mobile_phone'],
                'real_name' => $promote['real_name'],
                'id' => $promote['id'],
            ];
        }
        $this->assign('records', $records);
        $this->assign('pagination', $pagination);
        $this->display('sub_promotes');
    }

    public function promoteUsers()
    {
        $account = I('account', '');
        $mobile = I('mobile', '');
        $promote = $this->getLoginPromote();
        $map = ['chain' => ['like', $promote['chain'] . $promote['id'] . '/%']];
        $promoteIds = D('Promote')->field('id')->where($map)->getField('id', true);
        $promoteIds[] = $promote['id'];
        if ($account) {
            $map['account'] = ['like', '%' . $account . '%'];
        }
        if ($mobile) {
            $map['mobile_phone'] = ['like', '%' . $mobile . '%'];
        }
        $map['promote_id'] = ['in',$promoteIds];
        $query = M('User', 'tab_')->field(['id', 'phone', 'account', 'real_name'])->where($map);

        list($users, $pagination, $count) = $this->paginate($query);
        $records = [];
        foreach ($users as $user) {
            $records[] = [
                'account' => $user['account'],
                'mobile' => $user['phone'],
                'real_name' => $user['real_name'],
                'id' => $user['id'],
            ];
        }
        $this->assign('records', $records);
        $this->assign('pagination', $pagination);
        $this->display('promote_users');
    }

    public function promoteGames()
    {
        $promoteId = I('promote_id', 0);
        $rows = M('Apply', 'tab_')->field(['game_id'])->where(['promote_id' => $promoteId, 'status' => 1])->select();
        $ids = array_column($rows, 'game_id');
        $name = I('name', '');
        $map = [];
        if ($name) {
            $map['game_name'] = ['like', '%' . $name . '%'];
        }

        $records = [];
        $records[] = [
            'game_name' => '全部',
            'icon' => '',
            'sdk_version' => '全平台',
            'id' => 0,
        ];

        if (count($ids) > 0) {
            $map['id'] = ['in', $ids];
        } else {
            $map['_string'] = '1<>1';
        }

        $query = M('Game', 'tab_')->field(['id', 'game_name', 'sdk_version', 'icon'])->where($map);
        list($games, $pagination, $count) = $this->paginate($query);

        foreach ($games as $game) {
            $records[] = [
                'game_name' => $game['game_name'],
                'icon' => get_cover($game['icon'], 'path'),
                'sdk_version' => getSDKTypeName($game['sdk_version']),
                'id' => $game['id'],
            ];
        }

        $this->assign('records', $records);
        $this->assign('pagination', $pagination);
        $this->display('promote_games');
    }

    public function userGames()
    {
        $userId = I('user_id', 0);
        $rows = D('UserPlay')->field(['game_id'])->where(['user_id' => $userId])->select();
        $ids = array_column($rows, 'game_id');

        $name = I('name', '');
        $map = [];
        if ($name) {
            $map['game_name'] = ['like', '%' . $name . '%'];
        }

        $records = [];

        if (count($ids) > 0) {
            $map['id'] = ['in', $ids];
        } else {
            $map['_string'] = '1<>1';
        }
        $query = M('Game', 'tab_')->field(['id', 'game_name', 'sdk_version', 'icon'])->where($map);
        list($games, $pagination, $count) = $this->paginate($query);

        foreach ($games as $game) {
            $records[] = [
                'game_name' => $game['game_name'],
                'icon' => get_cover($game['icon'], 'path'),
                'sdk_version' => getSDKTypeName($game['sdk_version']),
                'id' => $game['id'],
            ];

        }

        $this->assign('records', $records);
        $this->assign('pagination', $pagination);
        $this->display('user_games');
    }
}