<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\logic\admin\MailLogic;
use App\Models\AdminScore;
use App\Models\RecordPlatformData;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Storage;
use Excel;

class MailController extends Controller
{
    //邮件列表
    public function mailList(Request $request)
    {
        $type = $request->get('type');
        $GameID = $request->get('GameID');
        $amount = $request->get('amount');
        $amount_search = $request->get('amount_search');
        $admin_type = $request->get('admin_type',-1);
        !isset($type) ? $type = 0 : '';

        $startTime = str_replace('T', ' ', $request->start_time ?? "");
        $endTime = str_replace('T', ' ', $request->end_time ?? "");

        $prize = DB::connection('read')->table('QPTreasureDB.dbo.PropCfg')->select('PropID', 'PropName')->get()->toArray();
        //$prop = DB::connection('read')->table('QPAccountsDB.dbo.YN_MatchProp')->select('PropID', 'PropName')->get()->toArray();

        //$data = array_merge($prize, $prop);
//        foreach ($data as $key => $value) {
//            $prop_arr[$value->PropID] = $value->PropName;
//        }
        if ($type == 1) {
            $list = DB::connection('read')->table('QPAccountsDB.dbo.SystemMail')->orderBy('MailID', 'desc')->paginate(10);
        } else {
            $where[] = ['MailType', '=', 2];
            if (!empty($amount)) {
                $where[] = ['pm.amount', '=', $amount * 100];
            }
            if (!empty($startTime)) {
                $where[] = ['pm.createTime', '>=', $startTime];
            }
            if ($admin_type!=-1) {
//                $where[] = ['pm.admin_type', '=', $admin_type];
            }

            if (!empty($endTime)) {
                $where[] = ['pm.createTime', '<=', $endTime];
            }
            !empty($GameID) && $where[] = ['ai.GameID', '=', $GameID];

            switch ($amount_search) {
                case 100:
                    $where[] = ['pm.amount', '<', 10000];
                    break;
                case 500:
                    $where[] = ['pm.amount', '>=', 10000];
                    $where[] = ['pm.amount', '<=', 50000];
                    break;
                case 1000:
                    $where[] = ['pm.amount', '>=', 50000];
                    $where[] = ['pm.amount', '<=', 100000];
                    break;
                case 1001:
                    $where[] = ['pm.amount', '>', 100000];
                    break;
            }

            !empty($GameID) && $where[] = ['ai.GameID', '=', $GameID];
            $list = DB::connection('read')->table('QPAccountsDB.dbo.PrivateMail as pm')
                ->leftJoin('QPAccountsDB.dbo.AccountsInfo as ai', 'pm.UserID', '=', 'ai.UserID')
                ->select('pm.*', 'ai.GameID')
                ->where($where)
//                ->whereNotNull('FromAgentID')
//                ->where('type', 3)
                ->orderBy('MailID', 'desc')
                ->paginate(10);
        }
        foreach ($list as $key => &$value) {
            if (!empty($value->BonusString)) {
                $bonus = $value->BonusString;
                $bonus = explode(';', $bonus);
                $value->BonusString = '';
                foreach ($bonus as $k => &$v) {
                    $v = explode(',', $v);
                    $value->BonusString .=  '金币x' . ($v[1] / 100) . ',';
                }
            }
        }

        return view('admin.mail.list', ['list' => $list,'type_list' => ['-1' => '全部', 1 => '召回', 2=>'测试', 3=>'好评',4 => '活动奖励',5 => '补偿', 6 => '其他',0 => '默认' ], 'type' => $type, 'GameID' => $GameID, 'amount' => $amount,'amount_search' => $amount_search,'startTime' => $startTime, 'endTime' => $endTime,'admin_type' => $admin_type]);
    }

    //邮件发布页面
    public function mailAddView(Request $request)
    {
        return view('admin.mail.mail_add');
    }

    //邮件发布
    public function mailAdd(Request $request)
    {
        $admin = $request->session()->get('admin');//管理员信息
        $params = $request->all();
        $bonus_arr = $params['bonus'];
        if (count($bonus_arr) > 5) {
            return $this->json(500, '奖品最多不超过五件');
        }
        $bonus = '';
        if (empty($params['title']) || empty($params['text'])) {
            return $this->json(500, '请确认数据完整');
        }

        $params['type']  = 2;

        $type = 0;
        $amount = 0;
        $change_score = 0;
        if (isset($bonus_arr[0]['id']) && !empty($bonus_arr[0]['id'])) {

            foreach ($bonus_arr as $key => $value) {

//                if (empty($value['id']) || empty($value['number'])) {
//                    return $this->json(500, '奖品不能为空');
//                }
                if ($value['id'] == "30000" && $value['number'] > 1000000) {
                    return $this->json(500, '金币不能超过一百万');
                }
                if ($value['id'] == 10000 && $value['number'] > 200) {
                    return $this->json(500, '房卡不能超过二百');
                }
                if ($value['id'] == 40000 && $value['number'] > 100000) {
                    return $this->json(500, '福卡不能超过十万');
                }
//                if (!empty($value['number']) && $value['number'] < 0.1) {
//                    return $this->json(500, '奖品数量最小值为0.1');
//                }

                // 判断彩金管理员够不够
                $admin_id = session('admin')->id;

                $admin = DB::table('agent.dbo.admin_users')->where('id',$admin_id)->first();
                $lottery_amount = $admin->lottery_amount ?: 0;

                if ($lottery_amount < $value['number']) {
                    return $this->json(500, '彩金额度不足');
                }
                $change_score = $value['number'];

                $value['number'] = $value['number'] * 100;
                $bonus .= implode(',', $value) . ';';
                $type = 3;

                if ($value['id'] === "30000") {
                    $amount = $value['number'];
                }
            }
        }
        $bonus = trim($bonus, ';');

        //个人公告
        if ($params['type'] == 2) {
            $uids = [];
            if(strstr($params['game_id'],';')){
                $uids = explode(';',$params['game_id']);
            }else{
                $uids = [trim($params['game_id'])];
            }
            foreach ($uids as $game_id){
                $UserInfo = DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')->where('GameID', $game_id)
                    ->select('UserID','Channel')
                    ->first();

                if (!$UserInfo) {
                    return $this->json(500, '未查询到该用户');
                }
                $user_id = $UserInfo->UserID;
                $Channel = $UserInfo->Channel;
                $data = [
                    'MailType' => $params['type'],
                    'MailStatus' => 1,
                    'UserID' => $user_id,
                    'CreateTime' => date('Y-m-d H:i:s', time()),
                    'TitleString' => $params['title'],
                    'TextString' => $params['text'],
                    'BonusString' => $bonus,
                    'FromAgentID' => $admin->id,
                    'type' => $type,
                    'amount' => $amount,
//                    'admin_type' => @$params['admin_type']?:0
                ];


                $result = DB::table('QPAccountsDB.dbo.PrivateMail')->insert($data);

                if($amount){
                    // 添加管理员变化额度
                    AdminScore::add_score($admin, $change_score, 1);

                    // 添加赠送金币
                    RecordPlatformData::addGiveGold($amount,$Channel);
                }

            }


            //系统公告
        } else {
            $data = [
                'CreateTime' => date('Y-m-d H:i:s', time()),
                'TitleString' => $params['title'],
                'TextString' => $params['text'],
                'BonusString' => '',
                'FromAgentID' => $admin->id,
            ];
            $result = DB::table('QPAccountsDB.dbo.SystemMail')->insert($data);
        }
        if ($result) {
            return $this->json(200, "发布成功");
        } else {
            return $this->json(500, '发布失败，请重试');
        }
    }

    // 邮件充值记录
    public function mailRecord(Request $request)
    {

        $GameID = $request->GameID ?: '';
        $amount = $request->amount ?: '';
        $amount_search = $request->amount_search ?: '';


        $list = (new MailLogic())->mailRecord(1, $GameID, $amount, $amount_search);
        return view('admin.mail.mailRecord', compact('list', 'GameID', 'amount', 'amount_search'));
    }

    // 提现返还邮件记录
    public function back_mailRecord(Request $request)
    {

        $GameID = $request->GameID ?: '';
        $amount = $request->amount ?: '';
        $amount_search = $request->amount_search ?: '';


        $list = (new MailLogic())->mailRecord(2, $GameID, $amount, $amount_search);
        return view('admin.mail.back_mailRecord', compact('list', 'GameID', 'amount', 'amount_search'));
    }


}
