<?php
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Auth;
use App\Models\WxUserImg;
use App\Models\User;


class AdminController extends Controller
{
    private $time;

    public function __construct()
    {
        $this->time = Carbon::now()->format('Y-m-d H:i:s');
    }

    /**
     * 后台登陆页
     * @date 2021/06/02
     * @author live
     */
    public function getLogin(Request $request)
    {
        // if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        //     $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        // }else {
        //     $ip = $_SERVER['REMOTE_ADDR'];
        // }

        // $ips = explode(',',$ip);

        // if(!in_array($ips[0],['116.227.124.169','116.227.126.145','180.157.250.155','114.86.189.146','114.86.189.140'])){
        //     abort(404);
        //     exit();
        // }

        if(Auth::check()) return redirect(route('checkImg'));
        $data['ERROR'] = Session::get('error','');
        return $this->view('admin.login',$data);
    }

    /**
     * 用户登录页提交
     * @date 2021/06/02
     * @author live
     */
    public function getPostLogin(Request $request)
    {
        // if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        //     $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        // }else {
        //     $ip = $_SERVER['REMOTE_ADDR'];
        // }

        // $ips = explode(',',$ip);

        // if(!in_array($ips[0],['116.227.124.169','116.227.126.145','180.157.250.155','114.86.189.146','114.86.189.140'])){
        //     exit('页面走丢了');
        //     return false;
        // }

        $postData = $request->all();
        if( Auth::check()) return redirect(route('checkImg'));
        if($request->isMethod('post'))
        {
            if (Auth::attempt(['name' => $postData['username'], 'password' =>  $postData['password']]))
            {
                return redirect(route('checkImg'))->with( 'success', '登录成功,明信片审核后台欢迎你!' );
            }else{
                $error = '用户名或密码不正确！';
            }
        }else{
            $error = '非法登录！';
        }
        return redirect(route('adminLogin'))->with( 'error', $error );
    }

    /**
     * 用户上传图片列表
     * @date 2021/06/02
     * @author live
     */
    public function getImgList(Request $request)
    {
        $postData = $request->all();
        $pageNum = 20;
        $startTime = $postData['startTime'] ?? '';
        $endTime = $postData['endTime'] ?? '';
        $status = $postData['status'] ?? 1;
        $userName = $postData['user'] ?? '';

        $paginateAppends['status'] = $status;
        $lists = WxUserImg::when($userName != '', function ($query) use ($userName) {
            $user = User::where('account',$userName)->select('uid')->first();
            if($user){
                return $query->where('uid',$user->uid);
            }else{
                return $query->where('uid','-1');
            }
        })->when($status > 0, function ($query) use ($status) {
            $imgStatus = $status - 1;
            return $query->where('status',$imgStatus);
        })->when($startTime != '', function ($query) use ($startTime) {
            return $query->where('updated_at','>',$startTime);
        })->when($endTime != '', function ($query) use ($endTime) {
            return $query->where('updated_at','<',$endTime);
        })->when($status == 0, function ($query) use ($status) {
            return $query->orderBy('status','ASC');
        })->orderBy('updated_at','DESC')->select('id', 'uid','role_id','role', 'loacl_url','img_url', 'status','is_upload', 'updated_at')->paginate($pageNum);
        if($startTime != '') $paginateAppends['startTime'] = $startTime;
        if($endTime != '') $paginateAppends['endTime'] = $endTime;
        if($userName != '') $paginateAppends['user'] = $userName;
        if (!empty($paginateAppends)) $lists->appends($paginateAppends);

        $userInfo = [];
        $uids = [];
        foreach($lists as $list) $uids[] = $list->uid;
        if(!empty($uids)){
            $users =  User::whereIn('uid',$uids)->select('uid','account')->get();
            foreach($users as $user) $userInfo[$user->uid] = $user->account;
        }

        $data['LIST'] = $lists;
        $data['SEARCH'] = $postData;
        $data['USER_INFO'] = $userInfo;
        return $this->view('admin.img', $data);
    }

    /**
     * 审核图片
     * @date 2021/06/02
     * @author live
     */
    public function getSaveStatus(Request $request)
    {
        $postData = $request->all();
        $id = $postData['id'] ?? 0;
        $status = $postData['status'];
        if($id < 1 || !in_array($status,[1,2])) return $this->getErrorMsg('10060', '参数错误');
        $row = WxUserImg::find($id);
        if(!$row) return $this->getErrorMsg('10061', '数据异常');
        $row->status = $status;
        if($row->save()){
            Cache::forget('card:info:'.$row->uid.':'.$row->role);
            return $this->getSuccessMsg([]);
        }
        return $this->getErrorMsg('10063', '审核失败');
    }

    /**
     * 批量审核图片
     * @date 2021/06/07
     * @author live
     */
    public function getSaveStatusAll(Request $request)
    {
        $postData = $request->all();
        $ids = explode('#',$postData['ids']);
        $status = $postData['status'];
        if(!in_array($status,[1,2]) || empty($ids)) return $this->getErrorMsg('10060', '参数错误');
        $imgs = WxUserImg::whereIn('id',$ids)->select('id','uid','role','loacl_url','status')->get();
        $result = true;
        foreach($imgs as $img){
            $img->status = $status;
            if($img->save()){
                Cache::forget('card:info:'.$img->uid.':'.$img->role);
                //if($status == 2) unlink(storage_path('app').'/'.$img->loacl_url);
            }else{
                $result = false;
            }
        }
        //$result = WxUserImg::whereIn('id',$ids)->update(['status' => $status]);
        if($result) return $this->getSuccessMsg([]);
        return $this->getErrorMsg('10063', '审核失败');
    }

    /**
     * 删除角色信息
     * @date 2021/06/10
     * @author live
     */
    public function getDeleteRole(Request $request)
    {
        $postData = $request->all();
        $serverId = $postData['serverId'] ?? '';
        $roleId = $postData['roleId'] ?? '';
        $tableName = 'wx_card_role_'.$serverId;

        if($serverId == '' || $roleId == '') return $this->getErrorMsg('10060', '参数错误');
        $verity = DB::connection('wx_mysql')->table($tableName)->where('role_id',$roleId)->first();
        if(!$verity) return $this->getErrorMsg('10061', '区服角色不匹配');
        $uid = $verity->uid;
        $result = DB::connection('wx_mysql')->table($tableName)->where('role_id',$roleId)->delete();
        if($result){
            $row = WxUserImg::where('uid',$uid)->where('server_id',$serverId)->where('role',$roleId)->first();
            $row->delete();
            return $this->getSuccessMsg([]);
        }

        return $this->getErrorMsg('10062', '清除角色失败');
    }

}
