<?php

namespace App\Http\Controllers\Service;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use App\Http\Controllers\Controller;
use App\Http\Traits\PagingTrait;

/*
 * 한국농수산식품유통공사_화훼 경매 시세
 */
class PriceController extends Controller
{
    use PagingTrait;

    const API_CLOUD_KEY = 'vQz8tIxrdhjerG6DE1w1hcVEli5S27LtIsCvx0axiieZmRgOpB4vToQ77VmvknAkIC9YjxlPx2gDZcl06S88Xw==';
    const API_CLOUD_HOST = 'https://api.odcloud.kr/api/15052544/v1/uddi:9e23a38b-3d9f-4e5c-aa4f-ecfa1b8a640a';

    const API_FLOWER_KEY = '5F70416B443241BE846D0807744FC489';
    const API_FLOWER_HOST = 'https://flower.at.or.kr/api/returnData.api';

    public function __construct()
    {
        $this->middleware('front');
    }

    /**
     * 환율 정보
     * @method GET
     * @see /service/price/flower
     */
    public function flower(Request $request)
    {
        // 공통 변수
        $page = $request->get('page', 1);
        $perPage = $request->get('per_page', 15);

        // 검색 시 필요
        $gubun = $request->get('gubun'); // 부류
        $date = $request->get("date"); // 기준일
        $pName = $request->get('p_name'); // 품목명
        $gName = $request->get('g_name'); // 품종명
        $pid = $request->get('pid');

        $total = 0;
        $maxAmt = 0;
        $minAmt = 0;
        $avgAmt = 0;
        $totQty = 0;
        $totAmt = 0;
        $list = [];

        if(!$gubun && !$date) {
            $params = [
                'serviceKey' => self::API_CLOUD_KEY,
                'page' => $page,
                'perPage' => $perPage,
                'returnType' => 'json'
            ];

            $response = Http::acceptJson()->withHeaders([
                'Authorization' => self::API_CLOUD_KEY
            ])->get(self::API_CLOUD_HOST, $params);

            if($response->ok()) {
                $result = $response->object();
                $total = $result->totalCount;

                $num = listNum($total, $page, $perPage);
                if($result && $total) {
                    foreach($result->data as $row) {
                        $row = (array)($row);
                        $maxAmt += $row['최고단가(원)'];
                        $minAmt += $row['최저단가(원)'];
                        $avgAmt += $row['평균단가(원)'];
                        $totQty += $row['총수량'];
                        $totAmt += $row['총금액(원)'];

                        $list[] = [
                            'num' => $num--,
                            'saleDate' => $row['정산일자'],
                            'flowerGubn' => $row['화훼구분명'],
                            'pumName' => $row['품목명'],
                            'goodName' => $row['품종명'],
                            'lvNm' => $row['등급명'],
                            'maxAmt' => number_format($row['최고단가(원)']),
                            'minAmt' => number_format($row['최저단가(원)']),
                            'avgAmt' => number_format($row['평균단가(원)']),
                            'totQty' => number_format($row['총수량']),
                            'totAmt' => number_format($row['총금액(원)'])
                        ];
                    }
                }
            }

        }else{

            $params = [
                'kind' => 'f001',
                'serviceKey' => self::API_FLOWER_KEY,
                'baseDate' => ($date ?? now()->format('Y-m-d')),
                'flowerGubn' => ($gubun ?? 1),
                'dataType' => 'json',
            ];

            if($pName || $gName) {
                if($pName) {
                    $params['pumName'] = $pName;
                }
                if($gName) {
                    $params['goodName'] = $gName;
                }
            }

            // total
            $params['countPerPage'] = 10000;
            $response = Http::get(self::API_FLOWER_HOST, $params);

            if($response->ok()) {
                $total = intval($response->json('response')['numOfRows']);
            }

            // list
            if(!$gName) {
                $params['currentPage'] = $page;
                $params['countPerPage'] = $perPage;
            }

            $response = Http::get(self::API_FLOWER_HOST, $params);

            if($response->ok()) {
                $result = $response->json('response');

                if($result && $result['numOfRows'] > 0) {
                    $num = listNum($total, $page, $perPage);
                    foreach($result['items'] as $i => &$row) {
                        $row['num'] = $num--;
                        $maxAmt += $row['maxAmt'];
                        $minAmt += $row['minAmt'];
                        $avgAmt += $row['avgAmt'];
                        $totQty += $row['totQty'];
                        $totAmt += $row['totAmt'];

                        $list[] = array_merge($row, [
                            'maxAmt' => number_format($row['maxAmt']),
                            'minAmt' => number_format($row['minAmt']),
                            'avgAmt' => number_format($row['avgAmt']),
                            'totQty' => number_format($row['totQty']),
                            'totAmt' => number_format($row['totAmt']),
                        ]);
                    }
                }
            }
        }

        $list = $this->getPaginator(
            $list, $total, $perPage, $page
        );

        return view(layout('service.price.flower'), [
            'menuID' => 'flower',
            'gubun' => $gubun,
            'date' => $date,
            'pName' => $pName,
            'gName' => $gName,
            'pid' => $pid,
            'total' => $total,
            'list' => $list,
            'maxAmt' => number_format($maxAmt),
            'minAmt' => number_format($minAmt),
            'avgAmt' => number_format($avgAmt),
            'totQty' => number_format($totQty),
            'totAmt' => number_format($totAmt),
            'page' => $page,
            'perPage' => $perPage
        ]);
    }
}
