<?php

namespace App\Http\Controllers\Mobile\Active;

use App\Http\Controllers\Mobile\MobileBaseController;
use App\Models\LotteryLog;
use App\Models\LotteryPrize;
use App\Models\LotteryWin;
use App\Models\Thirdlogin;
use App\Services\Common\CategoryService;
use App\Services\Common\WechatService;
use App\Services\Auth\AuthService;
use App\Services\HomeService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

class SpringController extends MobileBaseController
{
    private $wechatService;
    protected $categoryService;
    protected $authService;
    protected $homeService;

    public function __construct(WechatService $wechatService, CategoryService $categoryService, authService $authService, HomeService $homeService)
    {
        $this->wechatService   = $wechatService;
        $this->categoryService = $categoryService;
        $this->authService     = $authService;
        $this->homeService     = $homeService;
    }

    /**
     * 专题页
     */
    public function index(Request $request)
    {
        //是否登录
        $user = auth('web-member')->user();
        if (empty($user)) {
            $open_id = Session::get('open_id');
            if (empty($open_id)) {
                return redirect(route('mobile.lottery.login'));
            }
        } else {
            $third   = Thirdlogin::where('uid', $user->id)->first();
            $open_id = $third['openid'];
        }

//        $open_id = '11';
        //抽奖次数
        $type   = $request->input('type', 1);
        $date   = date('Y-m-d');
        $log    = LotteryLog::where([
            ['create_time', '=', $date],
            ['type', '=', $type],
            ['open_id', '=', $open_id],
        ])->first();
        $number = 1;
        if (!empty($log)) {
            $number = 0;
        }

        //奖品列表
        $prize       = LotteryPrize::all();
        $ids         = [];
        $restaraunts = [];
        $colors      = [];
        $images      = [];
        foreach ($prize as $v) {
            $ids[]         = $v->id;
            $restaraunts[] = $v->prize_name;
            $colors[]      = $v->prize_bg;
            $images[]      = upload_asset($v->prize_image);
        }

        //中奖记录
        $win  = [];
        $user = auth('web-member')->user();
        if (!empty($user)) {
            $win = LotteryWin::with('prize')->where('member_id', $user->id)->orderBy('status', 'asc')->orderBy('created_at', 'desc')->limit(8)->get();
        }

        $return_data = [
            'open_id'         => $open_id,
            'current_url'     => \Illuminate\Support\Facades\Request::getRequestUri(),
            'user'            => $user,
            'number'          => $number,
            'type'            => $type,
            'prize'           => $prize,
            'win'             => $win,
            'ids'             => $ids,
            'restaraunts'     => $restaraunts,
            'colors'          => $colors,
            'images'          => $images,
            'wap_title'       => '抽奖',
            'share_title'     => '【福利通知】免费找工作,抽大奖拿好礼',
            'share_desc'      => '晋江好福利!免费找工作、找人才,还能抽奖,100%中奖,万份好礼免费拿!',
            'share_link'      => route('mobile.lottery.login'),
            'share_image_url' => theme_asset('mobile/images/online2021/share_logo.jpg'),
            'live_list'       => $this->homeService->getSpringLive(),
        ];

        return view('mobile.app.active.spring', $return_data);
    }

    /**
     * 专区页
     */
    public function special(Request $request)
    {
        $offset = isset($request->page) ? $request->page : 0;
        $limit  = 8;

        $citycategory = $request->input('citycategory', '');
        $trade        = $request->input('trade', '');
        $param_array  = ['citycategory', 'trade', 'nature'];

        $params = [];
        if ($request->all()) {
            foreach ($request->all() as $k => $v) {
                if (in_array($k, $param_array) && $v) {
                    $params[$k] = $v;
                }
            }
        }

        $filter_where = [
            'AIX_trade'        => 100,
            'AIX_company_type' => 100,
        ];
        $categories   = $this->categoryService->getCategories($filter_where);

        $subsites = Cache::get('subsites_list');
        if ($subsites) {
            if (!array_has($params, 'citycategory')) {
                if (get_subsite_id() > 0) {
                    $citycategory = $subsites[get_subsite_id()]['district'];
                }
            }
        }

        $title = '晋江市新春招聘会';
        $citys = $this->categoryService->getCitys($citycategory);

        if (empty($citycategory)) {
            $district_str = "(district like ? or district like ?)";
            $district_arr = ["%.623%", "%623.%"];
        } else {
            $select_id    = $citys['select']['id'];
            $district_str = "(district like ? or district like ?)";
            $district_arr = ["%.{$select_id}%", "%{$select_id}.%"];
            $title        = $citys['select']['name'] . '专区';
        }
        $whereRaw = "jobs.updated_at > '2022-01-01 00:00:00' and jobs.deleted_at is null and jobs.valid = 1 and jobs.audit = 1 and jobs.display = 1";
        $companys = DB::table('jobs')->join('companys', 'jobs.company_id', '=', 'companys.id')->whereRaw($whereRaw)->groupBy('jobs.company_id')->select('jobs.company_id')->pluck('company_id')->toArray();

        $where   = [];
        $where[] = ['user_status', '=', 1];
        $where[] = ['audit', '=', 1];
        $where[] = ['deleted_at', '=', null];
        if (!empty($trade)) {
            $where[] = ['trade', '=', $trade];
        }

        $list = DB::table('companys')->where($where)->whereRaw($district_str, $district_arr)->whereIn('id', $companys)->orderBy('sort_index', 'desc')->orderBy('id', 'desc')->offset($limit * $offset)->limit($limit)->get();
        $more = count($list) >= $limit ? true : false;

        $res = [];
        foreach ($list as $val) {

            $item = [
                'id'          => $val->id,
                'companyname' => $val->companyname,
                'jobs'        => [],
                'tag_arr'     => [],
            ];

            //在招职位
            $jobs_where = [
                ['company_id', '=', $val->id],
                ['valid', '=', 1],
                ['display', '=', 1],
                ['audit', '=', 1],
                ['deleted_at', '=', null],
            ];

            $jobs = DB::table('jobs')->where($jobs_where)->get();
            if (!$jobs->isEmpty()) {
                foreach ($jobs as $value) {
                    $job = [
                        'id'        => $value->id,
                        'jobs_name' => $value->jobs_name,
                        'amount'    => $value->amount,
                        'wage'      => $value->wage,
                        'wage_min'  => $value->wage_min,
                        'wage_max'  => $value->wage_max,
                    ];
                    array_push($item['jobs'], $job);
                }
            }

            //企业福利
            if (!empty($val->tag)) {
                $tags            = explode(',', $val->tag);
                $tag_arr         = DB::table('categorys')->whereIn('id', $tags)->limit(3)->get(['demand'])->toArray();
                $item['tag_arr'] = $tag_arr;
            }

            array_push($res, $item);
        }

        if ($request->ajax()) {
            if (count($res)) {
                return response()->json(['status' => 1, 'data' => view('mobile.app.active.ajax.ajax_spring_special_com', [
                    'res'        => $res,
                    'city'       => $citys,
                    'params'     => $params,
                    'categories' => $categories,
                    'more'       => $more,
                ])->render()]);
            }
            return response()->json(['status' => 0]);
        }

        return view('mobile.app.active.spring_special', [
            'title'           => $title,
            'res'             => $res,
            'city'            => $citys,
            'params'          => $params,
            'categories'      => $categories,
            'more'            => $more,
            'share_title'     => "【{$title}】免费找工作",
            'share_desc'      => '晋江好福利!免费找工作、找人才,还能抽奖,100%中奖,万份好礼免费拿!',
            'share_image_url' => theme_asset('mobile/images/online2021/share_logo.jpg'),
            'share_link'      => route('mobile.active.spring_special') . '?citycategory=' . $citycategory,
        ]);
    }

    /**
     * 经开区专区页
     */
    public function special_jkq(Request $request)
    {
        $source = $request->input('source', 0);
        $type   = $request->input('type', 1);
        if (!$request->ajax()) {
            //是否登录
            $user = auth('web-member')->user();
            if (empty($user)) {
                $open_id = Session::get('open_id');
                if (empty($open_id)) {
                    return redirect(route('mobile.active.spring_jkq_login', ['type' => $type, 'source' => $source]));
                }
            } else {
                $third   = Thirdlogin::where('uid', $user->id)->first();
                $open_id = $third['openid'];
            }

//            $open_id = '11';
            //抽奖次数
            $date   = date('Y-m-d');
            $log    = LotteryLog::where([
                ['create_time', '=', $date],
                ['type', '=', $type],
                ['open_id', '=', $open_id],
            ])->first();
            $number = 1;
            if (!empty($log)) {
                $number = 0;
            }

            //奖品列表
            $prize       = LotteryPrize::all();
            $ids         = [];
            $restaraunts = [];
            $colors      = [];
            $images      = [];
            foreach ($prize as $v) {
                $ids[]         = $v->id;
                $restaraunts[] = $v->prize_name;
                $colors[]      = $v->prize_bg;
                $images[]      = upload_asset($v->prize_image);
            }

            //中奖记录
            $win  = [];
            $user = auth('web-member')->user();
            if (!empty($user)) {
                $win = LotteryWin::with('prize')->where('member_id', $user->id)->orderBy('status', 'asc')->orderBy('created_at', 'desc')->limit(8)->get();
            }
        }

        $offset = isset($request->page) ? $request->page : 0;
        $limit  = 8;

        $citycategory = 'jjkfq';
        $whereRaw     = "jobs.updated_at > '2022-01-01 00:00:00' and jobs.deleted_at is null and jobs.valid = 1 and jobs.audit = 1 and jobs.display = 1";
        $companys     = DB::table('jobs')->join('companys', 'jobs.company_id', '=', 'companys.id')->whereRaw($whereRaw)->groupBy('jobs.company_id')->select('jobs.company_id')->pluck('company_id')->toArray();


        $citys        = $this->categoryService->getCitys($citycategory);
        $select_id    = $citys['select']['id'];
        $district_str = "(district like ? or district like ?)";
        $district_arr = ["%.{$select_id}%", "%{$select_id}.%"];

        $where   = [];
        $where[] = ['user_status', '=', 1];
        $where[] = ['audit', '=', 1];
        $where[] = ['deleted_at', '=', null];

        $list = DB::table('companys')->where($where)->whereRaw($district_str, $district_arr)->whereIn('id', $companys)->orderBy('sort_index', 'desc')->orderBy('id', 'desc')->offset($limit * $offset)->limit($limit)->get();
        $more = count($list) >= $limit ? true : false;

        $res = [];
        foreach ($list as $val) {

            $item = [
                'id'          => $val->id,
                'companyname' => $val->companyname,
                'jobs'        => [],
                'tag_arr'     => [],
            ];

            //在招职位
            $jobs_where = [
                ['company_id', '=', $val->id],
                ['valid', '=', 1],
                ['display', '=', 1],
                ['audit', '=', 1],
                ['deleted_at', '=', null],
            ];

            $jobs = DB::table('jobs')->where($jobs_where)->get();
            if (!$jobs->isEmpty()) {
                foreach ($jobs as $value) {
                    $job = [
                        'id'        => $value->id,
                        'jobs_name' => $value->jobs_name,
                        'amount'    => $value->amount,
                        'wage'      => $value->wage,
                        'wage_min'  => $value->wage_min,
                        'wage_max'  => $value->wage_max,
                        'wage_str'  => $value->wage_str,
                    ];
                    array_push($item['jobs'], $job);
                }
            }

            //企业福利
            if (!empty($val->tag)) {
                $tags            = explode(',', $val->tag);
                $tag_arr         = DB::table('categorys')->whereIn('id', $tags)->limit(3)->get(['demand'])->toArray();
                $item['tag_arr'] = $tag_arr;
            }

            array_push($res, $item);
        }

        if ($request->ajax()) {
            if (count($res)) {
                return response()->json(['status' => 1, 'data' => view('mobile.app.active.ajax.ajax_spring_special_com', [
                    'res'  => $res,
                    'more' => $more,
                ])->render()]);
            }
            return response()->json(['status' => 0]);
        }

        return view('mobile.app.active.spring_special_jkq', [
            'source'          => $source,
            'params'          => ['citycategory' => 'jjkfq'],
            'open_id'         => $open_id,
            'current_url'     => \Illuminate\Support\Facades\Request::getRequestUri(),
            'user'            => $user,
            'number'          => $number,
            'type'            => $type,
            'prize'           => $prize,
            'win'             => $win,
            'ids'             => $ids,
            'restaraunts'     => $restaraunts,
            'colors'          => $colors,
            'images'          => $images,
            'res'             => $res,
            'more'            => $more,
            'share_title'     => '【福利通知】免费找工作,抽大奖拿好礼',
            'share_desc'      => '晋江好福利!免费找工作、找人才,还能抽奖,100%中奖,万份好礼免费拿!',
            'share_image_url' => theme_asset('mobile/images/online2021/share_logo.jpg'),
            'live_list'       => $this->homeService->getSpringLive(),
        ]);
    }

    /**
     * 微信登录
     */
    public function jkq_login(Request $request)
    {
        //type:web-电脑端,mobile-手机端,
        $app_id       = subsite_config('aix.system.oauth.wechat_official.app_id');
        $redirect_uri = urlencode(route('mobile.active.spring_jkq_wechat_back'));
        $type         = $request->input('type', 1);
        $source       = $request->input('source', 0);
        $wechat_url   = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$app_id}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state={$type}_{$source}#wechat_redirect";
        return redirect($wechat_url);
    }

    /**
     * 微信回调
     */
    public function jkq_wechat_back(Request $request)
    {
        //微信登录
        $officialAccount = $this->wechatService->getOfficialAccount();
        $wechatUser      = $officialAccount->oauth->user()->getOriginal();
        $thirdlogin      = Thirdlogin::where('openid', $wechatUser['openid'])->first();
        if (!$thirdlogin && $wechatUser['unionid']) {
            $thirdlogin = Thirdlogin::where('unionid', $wechatUser['unionid'])->first();
        }
        if ($thirdlogin) {
            $member = $thirdlogin->member()->withTrashed()->first();
            $this->authService->login($member, 1);
        } else {
            Session::put('open_id', $wechatUser['openid']);
            Session::put('union_id', $wechatUser['unionid'] ?: '');
            Session::save();
        }
        $state = $request->input('state', '');
        $state = explode('_', $state);
        $url   = route('mobile.active.spring_special_jkq', ['type' => $state[0], 'source' => $state[1]]);
        return redirect($url);
    }

    /**
     * 直播专用页
     */
    public function special_live(Request $request)
    {
        if (!$request->ajax()) {
            //奖品列表
            $prize = LotteryPrize::all();
        }
        $offset = isset($request->page) ? $request->page : 0;
        $limit  = 8;

        $citycategory = 'jjkfq';
        $whereRaw     = "jobs.updated_at > '2022-01-01 00:00:00' and jobs.deleted_at is null and jobs.valid = 1 and jobs.audit = 1 and jobs.display = 1";
        $companys     = DB::table('jobs')->join('companys', 'jobs.company_id', '=', 'companys.id')->whereRaw($whereRaw)->groupBy('jobs.company_id')->select('jobs.company_id')->pluck('company_id')->toArray();


        $citys        = $this->categoryService->getCitys($citycategory);
        $select_id    = $citys['select']['id'];
        $district_str = "(district like ? or district like ?)";
        $district_arr = ["%.{$select_id}%", "%{$select_id}.%"];

        $where   = [];
        $where[] = ['user_status', '=', 1];
        $where[] = ['audit', '=', 1];
        $where[] = ['deleted_at', '=', null];

        $list = DB::table('companys')->where($where)->whereRaw($district_str, $district_arr)->whereIn('id', $companys)->orderBy('sort_index', 'desc')->orderBy('id', 'desc')->offset($limit * $offset)->limit($limit)->get();
        $more = count($list) >= $limit ? true : false;

        $res = [];
        foreach ($list as $val) {

            $item = [
                'id'          => $val->id,
                'companyname' => $val->companyname,
                'jobs'        => [],
                'tag_arr'     => [],
            ];

            //在招职位
            $jobs_where = [
                ['company_id', '=', $val->id],
                ['valid', '=', 1],
                ['display', '=', 1],
                ['audit', '=', 1],
                ['deleted_at', '=', null],
            ];

            $jobs = DB::table('jobs')->where($jobs_where)->get();
            if (!$jobs->isEmpty()) {
                foreach ($jobs as $value) {
                    $job = [
                        'id'        => $value->id,
                        'jobs_name' => $value->jobs_name,
                        'amount'    => $value->amount,
                        'wage'      => $value->wage,
                        'wage_min'  => $value->wage_min,
                        'wage_max'  => $value->wage_max,
                        'wage_str'  => $value->wage_str,
                    ];
                    array_push($item['jobs'], $job);
                }
            }

            //企业福利
            if (!empty($val->tag)) {
                $tags            = explode(',', $val->tag);
                $tag_arr         = DB::table('categorys')->whereIn('id', $tags)->limit(3)->get(['demand'])->toArray();
                $item['tag_arr'] = $tag_arr;
            }

            array_push($res, $item);
        }

        if ($request->ajax()) {
            if (count($res)) {
                return response()->json(['status' => 1, 'data' => view('mobile.app.active.ajax.ajax_spring_special_com', [
                    'res'  => $res,
                    'more' => $more,
                ])->render()]);
            }
            return response()->json(['status' => 0]);
        }

        return view('mobile.app.active.spring_special_live', [
            'params'          => ['citycategory' => 'jjkfq'],
            'current_url'     => \Illuminate\Support\Facades\Request::getRequestUri(),
            'res'             => $res,
            'more'            => $more,
            'prize'           => $prize,
            'share_title'     => '【福利通知】免费找工作,抽大奖拿好礼',
            'share_desc'      => '晋江好福利!免费找工作、找人才,还能抽奖,100%中奖,万份好礼免费拿!',
            'share_image_url' => theme_asset('mobile/images/online2021/share_logo.jpg'),
            'live_list'       => $this->homeService->getSpringLive(),
        ]);
    }

    /**
     * 线上招聘
     */
    public function recruit(Request $request)
    {
        $offset = isset($request->page) ? $request->page : 0;
        $limit  = 8;

        $citycategory = $request->input('citycategory', '');
        $trade        = $request->input('trade', '');
        $param_array  = ['citycategory', 'trade', 'nature'];

        $params = [];
        if ($request->all()) {
            foreach ($request->all() as $k => $v) {
                if (in_array($k, $param_array) && $v) {
                    $params[$k] = $v;
                }
            }
        }

        $filter_where = [
            'AIX_trade'        => 100,
            'AIX_company_type' => 100,
        ];
        $categories   = $this->categoryService->getCategories($filter_where);

        $subsites = Cache::get('subsites_list');
        if ($subsites) {
            if (!array_has($params, 'citycategory')) {
                if (get_subsite_id() > 0) {
                    $citycategory = $subsites[get_subsite_id()]['district'];
                }
            }
        }

        $title = '晋江市新春招聘会';
        $citys = $this->categoryService->getCitys($citycategory);

        if (empty($citycategory)) {
            $district_str = "(district like ? or district like ?)";
            $district_arr = ["%.623%", "%623.%"];
        } else {
            $select_id    = $citys['select']['id'];
            $district_str = "(district like ? or district like ?)";
            $district_arr = ["%.{$select_id}%", "%{$select_id}.%"];
            $title        = $citys['select']['name'] . '专区';
        }
        $whereRaw = "jobs.updated_at > '2022-01-01 00:00:00' and jobs.deleted_at is null and jobs.valid = 1 and jobs.audit = 1 and jobs.display = 1";
        $companys = DB::table('jobs')->join('companys', 'jobs.company_id', '=', 'companys.id')->whereRaw($whereRaw)->groupBy('jobs.company_id')->select('jobs.company_id')->pluck('company_id')->toArray();

        $where   = [];
        $where[] = ['user_status', '=', 1];
        $where[] = ['audit', '=', 1];
        $where[] = ['deleted_at', '=', null];
        if (!empty($trade)) {
            $where[] = ['trade', '=', $trade];
        }

        $list = DB::table('companys')->where($where)->whereRaw($district_str, $district_arr)->whereIn('id', $companys)->orderBy('sort_index', 'desc')->orderBy('id', 'desc')->offset($limit * $offset)->limit($limit)->get();
        $more = count($list) >= $limit ? true : false;

        $res = [];
        foreach ($list as $val) {

            $item = [
                'id'          => $val->id,
                'companyname' => $val->companyname,
                'jobs'        => [],
                'tag_arr'     => [],
            ];

            //在招职位
            $jobs_where = [
                ['company_id', '=', $val->id],
                ['valid', '=', 1],
                ['display', '=', 1],
                ['audit', '=', 1],
                ['deleted_at', '=', null],
            ];

            $jobs = DB::table('jobs')->where($jobs_where)->get();
            if (!$jobs->isEmpty()) {
                foreach ($jobs as $value) {
                    $job = [
                        'id'        => $value->id,
                        'jobs_name' => $value->jobs_name,
                        'amount'    => $value->amount,
                        'wage'      => $value->wage,
                        'wage_min'  => $value->wage_min,
                        'wage_max'  => $value->wage_max,
                    ];
                    array_push($item['jobs'], $job);
                }
            }

            //企业福利
            if (!empty($val->tag)) {
                $tags            = explode(',', $val->tag);
                $tag_arr         = DB::table('categorys')->whereIn('id', $tags)->limit(3)->get(['demand'])->toArray();
                $item['tag_arr'] = $tag_arr;
            }

            array_push($res, $item);
        }

        if ($request->ajax()) {
            if (count($res)) {
                return response()->json(['status' => 1, 'data' => view('mobile.app.active.ajax.ajax_spring_special_com', [
                    'res'        => $res,
                    'city'       => $citys,
                    'params'     => $params,
                    'categories' => $categories,
                    'more'       => $more,
                ])->render()]);
            }
            return response()->json(['status' => 0]);
        }

        return view('mobile.app.active.spring_special', [
            'title'           => $title,
            'res'             => $res,
            'city'            => $citys,
            'params'          => $params,
            'categories'      => $categories,
            'more'            => $more,
            'share_title'     => "【{$title}】免费找工作",
            'share_desc'      => '晋江好福利!免费找工作、找人才,还能抽奖,100%中奖,万份好礼免费拿!',
            'share_image_url' => theme_asset('mobile/images/online2021/share_logo.jpg'),
            'share_link'      => route('mobile.active.spring_special') . '?citycategory=' . $citycategory,
        ]);
    }
}