<?php

namespace App\Http\Controllers\V1;

use App\Models\Help;
use App\Models\Region;
use Illuminate\Http\Request;
use App\Models\Advertise;
use App\Models\Setting;
use Illuminate\Support\Facades\Redis;

class IndexController extends Controller
{
    //隐私政策
    public function privacyPolice()
    {
        $info = Setting::where('key', 'privacy')->where('is_delete', 0)->select('title', 'key', 'value')->first();

        return $this->success($info);
    }

    //用户协议
    public function userAgreement()
    {
        $info = Setting::where('key', 'agreement')->where('is_delete', 0)->select('title', 'key', 'value')->first();

        return $this->success($info);
    }

    //帮助类型
    public function helpList()
    {
        $list = Help::query()->select('id', 'title')->get();

        if($list->isEmpty()){
            return [];
        }
        $list = $list->toArray();

        return $this->success($list);
    }

    //帮助类答案
    public function answer(Request $request)
    {
        $info = Help::query()->where('id', $request->id)->first();
        $info->look_num = $info->look_num +1;
        $info->save();

        return $this->success($info);
    }

    //全国地区
    public function allRegion()
    {
        $regionList = Redis::get('all_region');
        if(!empty($regionList)){
            return $this->success(json_decode($regionList, true));
        }

        $list = Region::query()
            ->where('type', 1)
            ->select('code', 'full_name')
            ->get()
            ->toArray();

        foreach ($list as $key => $val) {
            $cityList = Region::query()->where('parent_code', $val['code'])->select('code', 'full_name')->get()->toArray();
            foreach ($cityList as $k => $v) {
                $areaList = Region::query()->where('parent_code', $v['code'])->select('code', 'full_name')->get()->toArray();
                $v['area_list'] = $areaList;
                $cityList[$k] = $v;
            }
            $val['city_list'] = $cityList;
            $list[$key] = $val;
        }

        Redis::setex('all_region', 24*3600, json_encode($list));

        return $this->success($list);
    }

}
