<?php

namespace App\Merchant\Controllers\Census;

use App\Merchant\Controllers\Controller;
use App\Models\Coupon;
use Auth;
use Illuminate\Http\Request;

class IndexController extends Controller
{

    public function index(Request $request)
    {
        $user   = Auth::guard('merchant')->user();
        $action = $request->action ?? 'search';

        if ($action == 'search') {
            $month = $request->month ?? now()->format('Y-m');
            $month = explode('-', $month);

            $coupons = Coupon::where('user_id', $user->id)
                             ->whereYear('created_at', $month[0])
                             ->whereMonth('created_at', $month[1])
                             ->where('status', 2)
                             ->get(['id', 'thirdPartyGoodsId', 'created_at']);

            $rules = $user->code;

            $coupons = $coupons->groupBy('create_day')
                               ->map(function ($items, $key) use ($rules) {
                                   $data = [
                                       'day' => $key,
                                   ];
                                   foreach ($rules as $rule) {
                                       $data[$rule->code] = $items->where('thirdPartyGoodsId', $rule->code)->count();
                                   }

                                   return collect($data);
                               });

            $all = [];
            foreach ($rules as $rule) {
                $all[$rule->code] = $coupons->sum($rule->code);
            }

            $coupons = $coupons->sortByDesc('day');

            return view('Merchant::census.index', compact('coupons', 'all', 'rules'));
        } else {
            $this->excel($request, $user);
        }
    }

    //导出数据
    public function excel($request, $user)
    {
        if (!$request->end) {
            $request->end = now()->toDateTimeString();
        }

        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $filename = '核销统计' . date('YmdHis') . '.csv';

        $response = function () use ($user, $request) {
            $handle = fopen('php://output', 'w');
            $rules  = $user->code;

            $titles = collect(['日期']);

            foreach ($rules as $rule) {
                $titles->push($rule->rule->title);
            }

            fputcsv($handle, $titles->toArray());

            $month = $request->month ?? now()->format('Y-m');
            $month = explode('-', $month);

            $coupons = Coupon::where('user_id', $user->id)
                             ->whereYear('created_at', $month[0])
                             ->whereMonth('created_at', $month[1])
                             ->where('status', 2)
                             ->get(['id', 'thirdPartyGoodsId', 'created_at']);

            $coupons = $coupons->groupBy('create_day')
                               ->map(function ($items, $key) use ($rules) {
                                   $data = [
                                       'day' => $key,
                                   ];
                                   foreach ($rules as $rule) {
                                       $data[$rule->code] = $items->where('thirdPartyGoodsId', $rule->code)->count();
                                   }

                                   return collect($data);
                               });

            $all = ['全部'];
            foreach ($rules as $rule) {
                $all[$rule->code] = $coupons->sum($rule->code);
            }

            foreach ($coupons as $coupon) {
                fputcsv($handle, $coupon->toArray());
            }

            fputcsv($handle, $all);

            fclose($handle);
        };

        response()
            ->stream($response, 200, [
                'Content-Encoding'    => 'UTF-8',
                'Content-Type'        => 'text/csv;charset=UTF-8',
                'Content-Disposition' => "attachment;filename=\"{$filename}\"",
            ])->send();

        exit();
    }

}
