<?php

namespace App\Merchant\Controllers\Coupon;

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

class IndexController extends Controller
{

    protected $query;

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

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

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

        $outlet            = $request->outlet;
        $status            = $request->status;
        $redemptionCode    = $request->redemptionCode;
        $start             = $request->start;
        $end               = $request->end;
        $thirdPartyGoodsId = $request->thirdPartyGoodsId;
        $pa_order_id       = $request->pa_order_id;
        $type              = $request->type;


        $this->query = Coupon::where('user_id', $user->id)
            ->when($outlet, function ($q) use ($outlet) {
                $q->whereHas('outlet', function ($q) use ($outlet) {
                    $q->whereHas('info', function ($q) use ($outlet) {
                        $q->where('nickname', 'like', "%{$outlet}%");
                    });
                });
            })
            ->when($redemptionCode, function ($q) use ($redemptionCode) {
                $q->where('redemptionCode', $redemptionCode);
            })
            ->when($type == 'pingan', function ($q) {
                $q->where('type', 1);
            })
            ->when($thirdPartyGoodsId, function ($q) use ($thirdPartyGoodsId) {
                $q->where('thirdPartyGoodsId', $thirdPartyGoodsId);
            })
            ->when($pa_order_id, function ($q) use ($pa_order_id) {
                $q->where('pa_order_id', $pa_order_id);
            })
            ->when(is_numeric($status), function ($query) use ($status) {
                $query->where('status', $status);
            }, function ($query) {
                $query->whereIn('status', [2, 3]);
            })
            ->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);
            })
            ->orderBy('created_at', 'desc')
            ->orderBy('id', 'desc');

        if ($action == 'search') {
            $data = [
                'all'    => $this->getData($request, 'all', $user),
                'pass'   => $this->getData($request, 'pass', $user),
                'reject' => $this->getData($request, 'reject', $user),
            ];

            $coupons = (clone $this->query)->paginate();

            return view('Merchant::coupon.index', compact('coupons', 'data', 'rules'));

        } else {
            $this->excel($request, $user);
        }
    }

    /**
     * 按照日期分润
     *
     * @param  Request  $request  [description]
     * @return array|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @author 玄尘 2020-03-11
     */
    public function profits(Request $request)
    {
        $user = Auth::guard('merchant')->user();

        if ($request->isMethod('POST')) {
            $date = $request->date;

            $list = Coupon::where('user_id', $user->id)->whereDate('created_at', $date)->where('status', 2)->get();
            if ($list->isEmpty()) {
                return $this->error('分润失败！没有可处理的数据');
            }
            if (Coupon::where('user_id', $user->id)
                ->whereDate('created_at', $date)
                ->where('status', 2)
                ->update(['status' => 4])) {
                return $this->success('分润成功！');
            } else {
                return $this->error('分润失败！');
            }
        } else {
            return view('Merchant::coupon.profits');
        }

    }

    /**
     * 分润
     *
     * @param  Coupon  $coupon  [description]
     * @return [type]         [description]
     * @author 玄尘 2020-03-11
     */
    public function profit(Coupon $coupon)
    {
        if ($coupon->status == 2) {
            $coupon->status = 4;
            $coupon->save();

            return $this->success('分润成功');
        } else {
            return $this->error('分润失败');
        }
    }

    //获取分数据
    public function getData($request, $type, $user)
    {

        switch ($type) {
            case 'all':
                return (clone $this->query)->count();
                break;
            case 'pass':
                return (clone $this->query)->where('status', 2)->count();
                break;
            case 'reject':
                return (clone $this->query)->where('status', 3)->count();
                break;
            default:
                return 0;
                break;

        }

    }

    //导出数据
    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);

            $this->query
                ->latest()
                ->chunk(5000, function ($coupons) use ($handle) {
                    foreach ($coupons as $index => $info) {
                        fputcsv($handle, [
                            $info->id,
                            $info->outlet ? $info->outlet->nickname : 'Id:'.$info->outletId,
                            $info->redemptionCode."\t",
                            ' '.$info->couponName,
                            $info->price."\t",
                            $info->pa_order_id,
                            $info->status_text,
                            $info->remark,
                            $info->created_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();
    }

}
