<?php

namespace Admin\Controller;

use Think\Controller;

class PromoteGameRatioController extends ThinkController
{
    const MODEL_NAME = 'promote_game_ratio';
    const STATUS_REFUSE = -1;
    const STATUS_WAIT = 0;
    const STATUS_PASS = 1;

    public static $statusList = [
        self::STATUS_REFUSE => '审核未通过',
        self::STATUS_WAIT => '待审核',
        self::STATUS_PASS => '已审核',
    ];

    public function lists()
    {
        $params = I('get.');
        $promoteId = $params['promote_id'] ?? 0;
        $gameId = $params['game_id'] ?? 0;
        $status = $params['status'] ?? '';
        $page = $params['p'] ? intval($params['p']) : 1;
        $row = $params['row'] ? intval($params['row']) : 10;

        $map['_string'] = '1 = 1';
        if ($promoteId) {
            $map['promote_id'] = intval($promoteId);
        }
        if ($gameId) {
            $map['game_id'] = intval($gameId);
        }
        if ($status !== '') {
            $map['status'] = intval($status);
        }

        $field = 'create_time, update_time';
        $promoteGameRatios = D(self::MODEL_NAME)->field($field, true)
            ->where($map)
            ->page($page, $row)
            ->order('update_time desc, id desc')
            ->select();
        $count = D(self::MODEL_NAME)->where($map)->count();

        $records = [];
        if ($promoteGameRatios) {
            $promoteIds = array_column($promoteGameRatios, 'promote_id');
            $gameIds = array_column($promoteGameRatios, 'game_id');
            $promoteFiled = 'id, account, mobile_phone, create_time, status, ver_status';
            $gameFiled = 'id, game_name, ratio';
            $promotes = M('promote', 'tab_')->where(array('id' => ['in', $promoteIds]))->getField($promoteFiled, true);
            $games = M('game', 'tab_')->where(array('id' => ['in', $gameIds]))->getField($gameFiled, true);

            foreach ($promoteGameRatios as $promoteGameRatio) {
                $thisPromoteId = $promoteGameRatio['promote_id'];
                $thisGameId = $promoteGameRatio['game_id'];
                $issetPromote = isset($promotes[$thisPromoteId]);
                $issetGame = isset($games[$thisGameId]);
                $thisPromoteAccount = '未知';
                $thisPromoteMobilePhone = '未知';
                $thisPromoteCreateTime = '未知';
                $thisPromoteStatus = '未知';
                $thisPromoteVerStatus = '未知';
                $thisGameName = '未知';
                $thisGameRatio = '0.00';
                $thisLastRatio = $promoteGameRatio['last_ratio'];
                $thisLastRatioStatus = $promoteGameRatio['last_ratio_status'];
                $thisStatusText = self::$statusList[$promoteGameRatio['status']];
                $thisStatusText = ($promoteGameRatio['status'] == -1) ? '<span style="color: red;">' . $thisStatusText . '</span>' : $thisStatusText;
                $thisApplicant = get_admin_account($promoteGameRatio['applicant_id']);
                $thisReviewer = $promoteGameRatio['reviewer_id'] ? get_admin_account($promoteGameRatio['reviewer_id']) : '待确认';
                $thisBeninTime = date('Y/m/d', $promoteGameRatio['begin_time']);
                $thisEndTime = $promoteGameRatio['end_time'] ? date('Y/m/d', $promoteGameRatio['end_time']) : '永久';
                $validDate = $thisBeninTime . ' - ' . $thisEndTime;
                if ($issetPromote) {
                    $thisPromoteAccount = $promotes[$thisPromoteId]['account'];
                    $thisPromoteMobilePhone = $promotes[$thisPromoteId]['mobile_phone'];
                    $thisPromoteCreateTime = date('Y-m-d H:i:s', $promotes[$thisPromoteId]['create_time']);
                    $thisPromoteStatus = get_status_title($promotes[$thisPromoteId]['status']);
                    $thisPromoteStatus = $thisPromoteStatus ?? '未知';
                    $thisPromoteVerStatus = getPromoteVerStatus($promotes[$thisPromoteId]['status'], 2);
                }
                if ($issetGame) {
                    $thisGameName = $games[$thisGameId]['game_name'];
                    $thisGameRatio = $games[$thisGameId]['ratio'];
                    $thisGameRatio = $thisGameRatio ?? '0.00';
                }

                $records[] = [
                    'id' => $promoteGameRatio['id'],
                    'promote_id' => $promoteGameRatio['promote_id'],
                    'promote_account' => $thisPromoteAccount,
                    'promote_mobile_phone' => $thisPromoteMobilePhone,
                    'promote_create_time' => $thisPromoteCreateTime,
                    'promote_status_text' => $thisPromoteStatus,
                    'promote_ver_status_text' => $thisPromoteVerStatus,
                    'game_name' => $thisGameName,
                    'last_ratio' => (($thisLastRatioStatus == 1) ? $thisLastRatio : $thisGameRatio) . '%',
                    'ratio' => $promoteGameRatio['ratio'] . '%',
                    'valid_date' => $validDate,
                    'remark' => $promoteGameRatio['remark'],
                    'status' => $promoteGameRatio['status'],
                    'status_text' => $thisStatusText,
                    'applicant' => $thisApplicant ?? '未知',
                    'reviewer' => $thisReviewer ?? '未知',
                ];
            }
        }

        $reviewRule = $this->getReviewRule();

        $this->assign('records', $records);
        $this->assign('count', $count);
        $this->assign('gameList', getAllGameList());
        $this->assign('promoteList', getPromoteByLevel(1));
        $this->assign('statusList', self::$statusList);
        $this->assign('reviewRule', $reviewRule);
        $this->meta_title = '公会分成管理';
        $this->display();
    }

    public function applyRatio()
    {
        if ($_POST) {
            $params = I('post.');
            $time = time();
            if (empty($params['begin_time'])) {
                $this->error('请选择开始时间');
            }
            if (!empty($params['end_time'])) {
                if (strtotime($params['end_time']) < strtotime($params['begin_time'])) {
                    $this->error('结束时间不得小于开始时间');
                }
            }
            $save['ratio'] = $params['ratio'] ?? 0;
            $save['begin_time'] = strtotime($params['begin_time']);
            $save['end_time'] = $params['end_time'] ? strtotime($params['end_time']) : 0;
            $save['remark'] = $params['remark'] ?? '';
            $save['status'] = 0;
            $save['update_time'] = $time;
            if (!empty($params['id'])) {//修改
                $promoteGameRatio = D(self::MODEL_NAME)->find($params['id']);
                if (empty($promoteGameRatio)) {
                    $this->error('参数异常');
                }

                $promoteId = $promoteGameRatio['promote_id'];
                $this->isWithdraw($promoteId, $save['begin_time']);//是否存在开始时间后已提现数据

                if ($promoteGameRatio['status'] == 1) {
                    $save['last_ratio'] = $promoteGameRatio['ratio'];
                    $save['last_ratio_status'] = 1;
                }
                $save['id'] = intval($params['id']);
                $result = D(self::MODEL_NAME)->save($save);
            } else {//新增
                if (empty($params['promote_id'])) {
                    $this->error('请选择会长账号');
                }
                if (empty($params['game_id'])) {
                    $this->error('请选择要申请的游戏');
                }
                $promoteId = intval($params['promote_id']);
                $gameId = intval($params['game_id']);
                $this->isWithdraw($promoteId, $save['begin_time']);//是否存在开始时间后已提现数据

                $promote = M('promote', 'tab_')->find($promoteId);
                if (empty($promote) || $promote['level'] != 1) {
                    $this->error('参数异常');
                }

                $map['promote_id'] = $promoteId;
                $map['game_id'] = $gameId;
                $promoteGameRatio = D(self::MODEL_NAME)->where($map)->find();
                if ($promoteGameRatio) {
                    $this->error('网络异常');
                }
                $save['promote_id'] = $promoteId;
                $save['game_id'] = $gameId;
                $save['applicant_id'] = is_login();
                $save['create_time'] = $time;
                $result = D(self::MODEL_NAME)->add($save);
            }

            if ($result === false) {
                $this->error('保存失败');
            } else {
                $this->success('保存成功', U('lists'));
            }
        } else {
            $params = I('get.');
            $id = $params['id'] ?? 0;
            $id = intval($id);
            $metaTitle = '游戏分成比例申请';
            if ($id) {
                $metaTitle .= '--修改';
                $map['id'] = $id;
                $promoteGameRatio = D(self::MODEL_NAME)->where($map)->find();
                if (empty($promoteGameRatio)) {
                    $this->error('数据异常');
                }
                $promoteGameRatio['begin_time'] = $promoteGameRatio['begin_time'] ? date('Y-m-d', $promoteGameRatio['begin_time']) : '';
                $promoteGameRatio['end_time'] = $promoteGameRatio['end_time'] ? date('Y-m-d', $promoteGameRatio['end_time']) : '';
                if ($promoteGameRatio['last_ratio_status'] == 1) {
                    $lastRatio = $promoteGameRatio['last_ratio'];
                } else {
                    $gameRatio = M('game', 'tab_')->where(array(['id' => $promoteGameRatio['game_id']]))->getField('ratio');
                    $lastRatio = ($gameRatio ?? '0.00') . '%';
                }

                $this->assign('record', $promoteGameRatio);
                $this->assign('lastRatio', $lastRatio);
            }

            $this->assign('gameList', getAllGameList());
            $this->assign('promoteList', getPromoteByLevel(1));
            $this->meta_title = $metaTitle;
            $this->display();
        }
    }

    private function isWithdraw($promoteId, $beginTime)
    {
        $promote = M('promote', 'tab_')->find($promoteId);
        if (empty($promote)) {
            $this->error("数据异常");
        }
        if ($promote['level'] != 1) {
            $this->error("该推广员不是会长账号,无法执行此操作");
        }

        $withdrawMap['promote_id'] = $promoteId;
        $withdrawMap['status'] = ['neq', -2];
        $withdrawMap['settlement_end_time'] = ['egt', $beginTime];
        $withdraw = M('withdraw', 'tab_')->where($withdrawMap)->order('create_time desc')->find();
        if (!empty($withdraw) && $withdraw['status'] != -2) {
            $time = date('Y-m-d', $withdraw['create_time']);
            $this->error("{$time}之前的订单已经申请提现, 无法变更分成比例,请重新选择开始时间");
        }
    }

    public function setStatus($status)
    {
        $params = I('post.');
        $ids = $params['ids'] ?? [];
        $remark = $params['remark'] ?? '';
        if (empty($ids)) {
            $this->error('操作失败');
        }
        if (empty($status) || !in_array($status, [-1, 1])) {
            $this->error('操作失败');
        }

        $time = time();
        $map['id'] = ['in', $ids];
        $map['status'] = 0;
        $save['status'] = $status;
        $save['reviewer_id'] = is_login();
        $save['review_time'] = $time;
        $save['update_time'] = $time;
        if ($remark) {
            $save['remark'] = $remark;
        }
        $result = D(self::MODEL_NAME)->where($map)->save($save);
        if ($result) {
            if ($status == 1) {
                foreach ($ids as $id) {
                    $promoteGameRatio = D(self::MODEL_NAME)->find($id);
                    if (!empty($promoteGameRatio)) {
                        if ($promoteGameRatio['begin_time'] <= strtotime(date('Y-m-d', time()))) {
                            $promoteId = $promoteGameRatio['promote_id'];
                            $promoteMap['chain'] = ['like', "/{$promoteId}/%"];
                            $promoteIds = M('promote', 'tab_')->where($promoteMap)->getField('id', true);
                            $promoteIds[] = $promoteId;

                            $spendMap['promote_id'] = ['in', $promoteIds];
                            $spendMap['game_id'] = $promoteGameRatio['game_id'];
                            if ($promoteGameRatio['end_time'] > 0) {
                                $spendMap['pay_time'] = ['between', [$promoteGameRatio['begin_time'], $promoteGameRatio['end_time'] + 3600 * 24 - 1]];
                            } else {
                                $spendMap['pay_time'] = ['egt', $promoteGameRatio['begin_time']];
                            }
                            $spendMap['pay_status'] = 1;
                            $spendMap['selle_status'] = 0;

                            $spendSave['selle_ratio'] = $promoteGameRatio['ratio'];
                            M('spend', 'tab_')->where($spendMap)->save($spendSave);
                        }
                    }
                }
            }
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    private function getPromoteApplyCreateTime($promoteId, $gameId)
    {
        $map['promote_id'] = $promoteId;
        $map['game_id'] = $gameId;
        $createTime = $apply = M('apply', 'tab_')->where($map)->getField('apply_time');
        return $createTime;
    }

    private function getReviewRule()
    {
        $rules = getAdminRules(is_login());
        $rulesName = BIND_MODULE . '/' . CONTROLLER_NAME . '/setStatus';
        $ruleId = getRule($rulesName, 'admin');
        $reviewRule = in_array($ruleId, $rules) ? true : false;
        $reviewRule = (is_login() == 1) ? true : $reviewRule;
        return $reviewRule;
    }

    public function getPromoteGameRatio()
    {
        $promoteId = I('post.promote_id', 0);
        $promoteId = intval($promoteId);
        $gameId = I('post.game_id', 0);
        $gameId = intval($gameId);
        $record['last_ratio'] = '';
        $status = 0;
        if ($promoteId || $gameId) {
            if ($promoteId && $gameId) {
                $map['promote_id'] = $promoteId;
                $map['game_id'] = $gameId;
                $record = D(self::MODEL_NAME)->where($map)->find();
                if ($record) {
                    $status = 2;
                    $record['begin_time'] = date('Y-m-d', $record['begin_time']);
                    $record['end_time'] = empty($record['end_time']) ? '' : date('Y-m-d', $record['end_time']);
                    if ($record['last_ratio_status'] == 0) {
                        $record['last_ratio'] = $this->getGameRatio($gameId);
                    }
                } else {
                    $status = 1;
                    $record['last_ratio'] = $this->getGameRatio($gameId);
                }
            } elseif ($gameId) {
                $status = 1;
                $record['last_ratio'] = $this->getGameRatio($gameId);
            }
        }
        $data = [
            'status' => $status,
            'record' => $record,
        ];
        $this->ajaxReturn($data);
    }

    public function getGameRatio($gameId)
    {
        $gameId = intval($gameId);
        $gameRatio = '0.00';
        if ($gameId) {
            $map['id'] = $gameId;
            $gameRatio = M('game', 'tab_')->where($map)->getField('ratio');
            $gameRatio = ($gameRatio ?? '0.00') . '%';
        }
        return $gameRatio;
    }
}