<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\helper\Helper;
use App\Http\helper\NumConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Storage;
use Excel;
use function GuzzleHttp\Psr7\uri_for;

class NoticeController extends Controller
{
    //系统公告列表
    public function systemList()
    {

        $where = ['HN_SC_NOTICE', 'SUSPENSION_NOTICE'];
        $list = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')->whereIn('StatusName', $where)->paginate(10);

        // 跑马灯
        //$hn_sc_notice = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')->where('StatusName', 'HN_SC_NOTICE')->first();
        // 停服公告
        //$suspension_notice = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')->where('StatusName', 'SUSPENSION_NOTICE')->first();
        $suspension_notice = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')->where('StatusName', 'SUSPENSION_NOTICE')->first();
        return view('admin.notice.system', compact('list'));
    }

    //公告发布页面
    public function systemAddView(Request $request)
    {
        $StatusName = $request->StatusName ?: '';
        if ($request->isMethod('post')) {
            $message = $request->input('message');
            if (!$message) {
                return $this->json(500, '必填参数不能为空');
            }
            //$time = date('Y-m-d H:i:s');
            //$publisher = $request->session()->get('admin')->account;//管理员信息
            //$result = DB::table('QPAccountsDB.dbo.SystemNotice')->insert(['publisher'=>$publisher,'message'=>$message,'created_at'=>$time]);
            $result = DB::table('QPAccountsDB.dbo.SystemStatusInfo')->where('StatusName', $StatusName)->update(['StatusString' => $message]);
            if ($result) {
                return $this->json(200, "发布成功");
            } else {
                return $this->json(500, '发布失败，请重试');
            }
        } else {
            $info = DB::table('QPAccountsDB.dbo.SystemStatusInfo')->where('StatusName', $StatusName)->first();
            return view('admin.notice.system_add', ['info' => $info]);
        }
    }

    // 修改状态
    public function updateStatus(Request $request)
    {
        $statusVal = $request->statusVal ?: '';
        $StatusName = $request->StatusName ?: '';

        DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')->where('StatusName', $StatusName)->update(['StatusValue' => $statusVal]);
        return apiReturnSuc();
    }


    //版本更新列表
    public function versionList()
    {
        $list = DB::connection('write')->table('QPAccountsDB.dbo.VersionNumInfo')->where('del', 0)->orderBy('id', 'desc')->paginate(10);
        return view('admin.notice.version', ['list' => $list]);
    }

    //版本更新添加页面
    public function versionAddView()
    {
        return view('admin.notice.version_add');
    }

    //新增版本更新内容
    public function versionAdd(Request $request)
    {
        $params = $request->post();
        if (empty($params['message']) || empty($params['time'])) {
            return $this->json(500, '请填入完整信息');
        }
        $data = [
            'version_number' => $params['version'],
            'content' => $params['message'],
            'add_time' => $params['time']
        ];
        $result = DB::table('QPAccountsDB.dbo.VersionNumInfo')->insert($data);
        if ($result) {
            return $this->json(200, "发布成功");
        } else {
            return $this->json(500, '发布失败，请重试');
        }
    }

    //版本更新修改页面
    public function versionUpdateView($id)
    {
        $version = DB::connection('write')->table('QPAccountsDB.dbo.VersionNumInfo')->select('id', 'version_number', 'content', 'add_time')->where('id', $id)->first();
        $version->add_time = substr($version->add_time, 0, 10);
        return view('admin.notice.version_update', ['version' => $version]);
    }

    //修改版本更新内容
    public function versionUpdate(Request $request, $id)
    {
        $params = $request->input();
        $params['update_time'] = date('Y-m-d H:i:s');
        $result = DB::table('QPAccountsDB.dbo.VersionNumInfo')->where('id', $id)->update($params);
        if ($result) {
            return $this->json(200, "修改成功");
        } else {
            return $this->json(500, '修改失败，请重试');
        }
    }

    //处罚公告列表
    public function punishList()
    {
        $list = DB::connection('write')->table('QPAccountsDB.dbo.punishInfo')->select('id', 'content', 'add_time', 'publish')->where('del', 0)->orderBy('id', 'desc')->paginate(10);
        return view('admin.notice.punish', ['list' => $list]);
    }

    //处罚公告添加页面
    public function punishAddView()
    {
        return view('admin.notice.punish_add');
    }

    //新增处罚公告
    public function punishAdd(Request $request)
    {
        $params = $request->post();
        if (!empty($params['message']) && !empty($params['time'])) {
            $data = [
                'add_time' => $params['time'],
                'Content' => $params['message']
            ];
            $result = DB::table('QPAccountsDB.dbo.punishInfo')->insert($data);
            if ($result) {
                return $this->json(200, "发布成功");
            } else {
                return $this->json(500, '发布失败，请重试');
            }
        } else {
            return $this->json(500, '请填入完整信息');
        }
    }

    //处罚公告详情，暂未使用
    public function punishDetail(Request $request, $id)
    {
        if (isset($params['edit'])) {
            $data = DB::connection('write')->table('QPAccountsDB.dbo.PunishInfo')->where('id', $params['id'])->first();
            if ($data) {
                return array('status' => true, 'msg' => '请求成功', 'data' => $data);
            } else {
                return array('status' => false, 'msg' => '请求失败，暂无数据', 'data' => []);
            }
        }
        $data = DB::connection('write')->table('QPAccountsDB.dbo.PunishInfo')->select('id', 'content', 'add_time')->where(['del' => 0, 'id' => $params['id']])->first();
        $con = [];
        if ($data) {
            $content = explode('；', str_replace("\n", '', $data->content));
            array_pop($content);
            foreach ($content as $key => $value) {
                $value = explode('，', $value);
                if (count($value) != 3) {
                    return ['status' => false, 'message' => '请输入正确信息'];
                }
                $arr['name'] = $value[0];
                $arr['cause'] = $value[1];
                $arr['result'] = $value[2];
                $con[] = $arr;
            }
            $data->content = $con;
            return array('status' => true, 'msg' => '请求成功', 'data' => $data);
        } else {
            return array('status' => false, 'msg' => '请求失败，暂无数据', 'data' => []);
        }
    }

    //处罚公告修改页面
    public function punishUpdateView($id)
    {
        $punish = DB::connection('write')->table('QPAccountsDB.dbo.PunishInfo')->select('id', 'content', 'add_time', 'publish')->where('id', $id)->first();
        return view('admin.notice.punish_update', ['punish' => $punish]);
    }

    //修改处罚公告
    public function punishUpdate(Request $request, $id)
    {
        $params = $request->post();
        if (empty($params)) {
            $result = DB::table('QPAccountsDB.dbo.PunishInfo')->where('id', $id)->update(['publish' => 1]);
        } else {
            $result = DB::table('QPAccountsDB.dbo.PunishInfo')->where('id', $id)->update($params);
        }
        if ($result) {
            return $this->json(200, "修改成功");
        } else {
            return $this->json(500, '修改失败，请重试');
        }
    }

    public function excel(Request $request)
    {
        if ($request->isMethod('post') && $_FILES['file']) {
            //> 获取上传文件路径 $_FILES
            if ($_FILES['file']['error'] == 0) {
                //> 获取上传文件名称(已便于后面判断是否上传需要后缀文件)
                $name = $_FILES['file']['name'];
                //> 获取上传文件后缀 如(xls exe xlsx 等)
                $ext = strtolower(trim(substr($name, (strpos($name, '.') + 1))));
                //> 判断文件是否为指定的上传文件后缀
                if (!in_array($ext, array('xls', 'xlsx'))) {
                    //> 返回上一次请求位置,并携带错误消息
                    return redirect()->back()->withErrors('请输入xls或xlsx后缀文件')->withInput();
                }
                //> 获取文件上传路径
                $fileName = $_FILES['file']['tmp_name'];
                //> excel文件导入 上传文件
                Excel::load($fileName, function ($reader) {
                    $list = $reader->get();
                    Cache::put('excel', $list->toArray(), 1);
                });
                $list = Cache::get('excel');
                $str = '';
                foreach ($list as $key => $value) {
                    $str .= $value[0] . '，' . $value[1] . '，' . $value[2] . '；' . "\n";
                }
                return view('admin.notice.punish_add', ['str' => $str]);
            }
            return view('admin.notice.punish_add', ['str' => '']);
        }
    }

    // 大厅活动公告
    public function hallAnnouncement(Request $request)
    {

        $list = DB::connection('write')->table('QPAccountsDB.dbo.HallNotice')
            ->orderByDesc('Sort')
            ->paginate(10);
        foreach ($list as &$value){
            $value->Title = base64_decode($value->Title);
            if ($value->Type == 1) $value->Content = base64_decode($value->Content);
        }

        return view('admin.notice.hall_announcement', compact('list'));
    }

    // 大厅活动公告-- 添加
    public function hallAnnouncementAdd(Request $request)
    {
        if ($request->isMethod('post')) {
            $post = $request->post();
            if (!empty($post['Content'])) $post['Content'] = base64_encode($post['Content']);
            if ($post['Type'] == 2) {
                if (empty($post['avatar'])) {
                    return apiReturnFail(__('messages.admin.notice.image_required'));
                }
                $post['Content'] = $post['avatar'];
                $post['Abstract'] = $post['Url'];
            }
            if (empty($post['Content'])) {
                return apiReturnFail(__('messages.admin.notice.text_required'));
            }
            $post['Title'] = base64_encode($post['Title']);
            $count = DB::connection('write')->table('QPAccountsDB.dbo.HallNotice')
                ->count();
            if ($count >= 10) {
                return apiReturnFail(__('messages.admin.notice.max_notice_limit'));
            }
            unset($post['Url']);
            unset($post['avatar']);
            DB::connection('write')->table('QPAccountsDB.dbo.HallNotice')
                ->insert($post);
            return apiReturnSuc();
        }

        return view('admin.notice.hall_announcement_add');
    }

    // 大厅活动公告 -- 修改
    public function hallAnnouncementUpdate(Request $request, $id)
    {

        if ($request->isMethod('post')) {
            $post = $request->post();
            if (!empty($post['Content'])) $post['Content'] = base64_encode($post['Content']);
            if ($post['Type'] == 2) {
                if (empty($post['avatar'])) {
                    return apiReturnFail(__('messages.admin.notice.image_required'));
                }
                $post['Content'] = $post['avatar'];
                $post['Abstract'] = $post['Url'];
            }
            if (empty($post['Content'])) {
                return apiReturnFail(__('messages.admin.notice.text_required'));
            }
            $post['LastTime'] = date('Y-m-d H:i:s');
            unset($post['Url']);
            unset($post['avatar']);

            $post['Title'] = base64_encode($post['Title']);
            DB::connection('write')->table('QPAccountsDB.dbo.HallNotice')
                ->where('ID', $id)
                ->update($post);
            return apiReturnSuc();
        }

        $info = DB::connection('write')->table('QPAccountsDB.dbo.HallNotice')
            ->where('ID', $id)
            ->first();
        $info->Title = base64_decode($info->Title);
        if ($info->Type == 1) $info->Content = base64_decode($info->Content);
        return view('admin.notice.hall_announcement_update', compact('info'));
    }

    // 大厅活动公告 -- 修改状态开关
    public function hallAnnouncementSwitch(Request $request, $id)
    {
        $Status = $request->Status ?: 0;
        $info = DB::connection('write')->table('QPAccountsDB.dbo.HallNotice')
            ->where('ID', $id)
            ->update(['Status' => $Status]);
        return apiReturnSuc();
    }

    // 大厅活动公告 -- 删除
    public function hallAnnouncementDel($id)
    {
        DB::connection('write')->table('QPAccountsDB.dbo.HallNotice')
            ->where('ID', $id)
            ->delete();
        return apiReturnSuc();
    }

    // 跑马灯
    public function horse_race_lamp()
    {

        $list = DB::connection('write')->table('QPPlatformDB.dbo.GameKindItem')
            ->whereIn('KindID',config('games.openKGame'))
            ->get();
        foreach ($list as &$value) {
            $first = DB::connection('write')->table('QPPlatformDB.dbo.RoomRunHorse')->where('GameID', $value->KindID)->select('Gap')->first();
            $value->Gap = isset($first->Gap) ? $first->Gap / NumConfig::NUM_VALUE : 0;
        }
        return view('admin.notice.horse_race_lamp', compact('list'));
    }

    // 跑马灯修改
    public function horse_race_lamp_update(Request $request, $id)
    {

        if ($request->isMethod('post')) {
            $post = $request->post();
            $list = DB::connection('write')->table('QPPlatformDB.dbo.GameRoomInfo')
                ->where('GameID', $id)
                ->select('GameID', 'SortID')
                ->groupBy('GameID', 'SortID')
                ->get();


            $data = [];
            foreach ($list as $key => $value) {
                $data[$key]['GameID'] = $value->GameID;
                $data[$key]['SortID'] = $value->SortID;
                $data[$key]['Gap'] = $post['Gap'] * NumConfig::NUM_VALUE;
                $data[$key]['Status'] = 1;
            }
            DB::connection('write')->table('QPPlatformDB.dbo.RoomRunHorse')->where('GameID', $id)->delete();

            DB::connection('write')->table('QPPlatformDB.dbo.RoomRunHorse')->where('GameID', $id)->insert($data);

            return apiReturnSuc();
        }

        $info = DB::connection('write')->table('QPPlatformDB.dbo.RoomRunHorse')->where('GameID', $id)->first();

        if ($info) {
            $info->Gap = $info->Gap / NumConfig::NUM_VALUE;
        }
        return view('admin.notice.horse_race_lamp_update', compact('info', 'id'));
    }
}
