<?php

namespace App\Http\Controllers\Api\Third;

use App\Http\Controllers\Api\ApiBaseController;
use App\Services\Common\UploadService;
use App\Validators\UploadValidatorRequest;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class HolidayController extends ApiBaseController
{
    /**
     * 法定节假日
     */
    public function index($date)
    {
        $year  = 0;
        $month = 0;
        $day   = 0;
        if (strpos($date, '-') !== false) {
            $arr   = explode('-', $date);
            $year  = $arr[0];
            $month = $arr[1];
            $day   = array_get($arr,2,0);
        }

        $where = ['year' => $year];
        if (!empty($month)) {
            $where['month'] = $month;
        }
        if (!empty($day)) {
            $where['day'] = $day;
        }

        $list = DB::table('holiday')->where($where)->get();
        $data = [];
        if (empty($day)) {
            foreach ($list as $v) {
                $data[] = [
                    'holiday' => $v->is_holiday == 1,
                    'date'    => "{$v->year}-{$v->month}-{$v->day}",
                ];
            }
        } else {
            if ($list->isEmpty()) {
                $week            = date('w', strtotime($date));
                $data['holiday'] = ($week == 0 || $week == 6);
            } else {
                $data['holiday'] = $list[0]->is_holiday == 1;
            }
        }


        return $this->sendSuccessResponse($data);
    }

    public function get($year)
    {
        if (strlen($year) != 4) {
            return $this->sendErrorResponse('请输入四位数的年份');
        }
        $info = DB::table('holiday')->where('year', $year)->first();
        if (!empty($info)) {
            return $this->sendErrorResponse('请勿重复拉数据!');
        }

        $data = file_get_contents('http://timor.tech/api/holiday/year/' . $year);
        $data = json_decode($data, true);
        $list = [];
        foreach ($data['holiday'] as $v) {
            $date   = explode('-', $v['date']);
            $list[] = [
                'is_holiday' => $v['holiday'] ? 1 : 2,
                'year'       => $date[0],
                'month'      => $date[1],
                'day'        => $date[2],
            ];
        }
        DB::table('holiday')->insert($list);

        return $this->sendSuccessResponse();
    }
}