<?php

namespace App\Merchant\Controllers\Unionpay;

use App\Merchant\Controllers\Controller;
use Auth;
use Illuminate\Http\Request;
use XuanChen\UnionPay\Models\UnionpayCoupon;

class CouponController extends Controller
{

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

        if ($request->start) {
            $request->start = $request->start . ' 00:00:00';
        }

        if ($request->end) {
            $request->end = $request->end . ' 23:59:59';
        }

        $shop_no   = $request->shop_no;
        $shop_name = $request->shop_name;
        $coupon_no = $request->coupon_no;
        $start     = $request->start;
        $end       = $request->end;
        $action    = $request->action ?? 'search';

        $coupons = UnionpayCoupon::query()
                                 ->whereHas('outlet', function ($q) use ($shop_name, $user) {
                                     $q->where('parent_id', $user->id)
                                       ->when($shop_name, function ($q) use ($shop_name) {
                                           $q->whereHas('info', function ($q) use ($shop_name) {
                                               $q->where('nickname', 'like', "%{$shop_name}%");
                                           });
                                       });
                                 })
                                 ->when($coupon_no, function ($q) use ($coupon_no) {
                                     $q->where('coupon_no', $coupon_no);
                                 })
                                 ->when($shop_no, function ($q) use ($shop_no) {
                                     $q->where('shop_no', $shop_no);
                                 })
                                 ->when($start && $end, function ($query) use ($start, $end) {
                                     $query->whereBetween('created_at', [$start, $end]);
                                 })
                                 ->when($start && !$end, function ($query) use ($start) {
                                     $query->where('created_at', '>', $start);
                                 })
                                 ->when(!$start && $end, function ($query) use ($end) {
                                     $query->where('created_at', '<', $end);
                                 })
                                 ->where('status', UnionpayCoupon::STATUS_USED)
                                 ->latest()
                                 ->paginate();

        if ($action == 'search') {
            return view('Merchant::unionpay.coupon', compact('coupons',));
        } 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');
            $titles = [
                'ID', '手机号', '门店号', '门店名称', '优惠券券编号', '原始金额', '优惠的金额', '支付金额', '状态', '核销时间',
            ];
            fputcsv($handle, $titles);

            $shop_no   = $request->shop_no;
            $shop_name = $request->shop_name;
            $coupon_no = $request->coupon_no;
            $start     = $request->start;
            $end       = $request->end;

            UnionpayCoupon::query()
                //                          ->whereHas('outlet', function ($q) use ($shop_name, $user) {
                //                              $q->where('parent_id', $user->id)
                //                                ->when($shop_name, function ($q) use ($shop_name) {
                //                                    $q->whereHas('info', function ($q) use ($shop_name) {
                //                                        $q->where('nickname', 'like', "%{$shop_name}%");
                //                                    });
                //                                });
                //                          })
                          ->when($coupon_no, function ($q) use ($coupon_no) {
                    $q->where('coupon_no', $coupon_no);
                })
                          ->when($shop_no, function ($q) use ($shop_no) {
                              $q->where('shop_no', $shop_no);
                          })
                          ->when($start && $end, function ($query) use ($start, $end) {
                              $query->whereBetween('created_at', [$start, $end]);
                          })
                          ->when($start && !$end, function ($query) use ($start) {
                              $query->where('created_at', '>', $start);
                          })
                          ->when(!$start && $end, function ($query) use ($end) {
                              $query->where('created_at', '<', $end);
                          })
                          ->where('status', UnionpayCoupon::STATUS_USED)
                          ->latest()
                          ->chunk(5000, function ($coupons) use ($handle) {
                              foreach ($coupons as $index => $coupon) {
                                  fputcsv($handle, [
                                      $coupon->id,
                                      $coupon->mobile . "\t",
                                      $coupon->shop_no . "\t",
                                      $coupon->outlet ? $coupon->outlet->nickname : '',
                                      $coupon->coupon_no . "\t",
                                      $coupon->orig_amt / 100,
                                      $coupon->discount_amt / 100,
                                      $coupon->pay_amt / 100,
                                      //                                      $coupon->effective_date_time,
                                      //                                      $coupon->expire_date_time,
                                      $coupon->status_text,
                                      $coupon->updated_at,
                                  ]);
                              }
                          });
            fclose($handle);
        };

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

        exit();
    }

}
