<?php

namespace app\controller\manager;

use app\exception\RepositoryException;

use app\model\CouponMain;
use app\repository\CouponRepository;
use Exception;
use think\facade\Db;
use think\response\Json;
use think\response\View;

/**
 * 优惠券相关
 **/
class Coupon extends Base
{

    /**
     * 列表
     *
     * @return Json|View
     * @throws Exception
     */
    public function index()
    {

        if ($this->request->isPost()) {
            $model = new CouponMain();
            $repo = CouponRepository::getInstance($model);
            $keyword = $this->request->param('keyword/s', '');
            $on_shelf = $this->request->param('on_shelf');
            $start_time = $this->request->param('start_time',);
            $end_time = $this->request->param('end_time');
            $page = $this->request->param('page/d', 1);
            $size = $this->request->param('size/d', 30);

            $whereMap = [];
            $orders = ['id' => 'desc'];
            if (!empty($on_shelf) && in_array($on_shelf, [CouponMain::COMMON_ON, CouponMain::COMMON_OFF])) {
                $whereMap[] = ['on_shelf', '=', $on_shelf];
            }
            if (!empty($start_time)) {
                $whereMap[] = ['start_time', '>=', $start_time];
            }
            if (!empty($end_time)) {
                $whereMap[] = ['end_time', '<=', $end_time];
            }
            if (!empty($keyword)) {
                $whereMap[] = ['name', 'like', "%" . $keyword . "%"];
            }
            $list = $repo->findList($whereMap, [], $page, $size, function ($q) {

                if (!empty($keyword)) {
                    return $q::hasWhere('business', function ($q) use ($keyword) {
                        $q->where('business_name', 'like', "%" . $keyword . "%")->field("code,business_name,business_subtitle,type")
                            ->with('category');
                    });
                }
                return $q->with(["business" => function ($query) {
                    $query->field("code,business_name,business_subtitle,type")
                        ->with('category');
                }]);
            }, $orders);
            $time = time();
            $list['list']->each(function ($item) use ($time) {
                if (strtotime($item->start_time) > $time) {
                    $item->state_text = '<span >未开始</span>';
                } else if ((strtotime($item->start_time) < $time) && (strtotime($item->end_time) > $time)) {
                    $item->state_text = '<span  class="f_green">进行中</span>';
                } else {
                    $item->state_text = '<span  class="f_red">已过期</span>';
                }
            });
            return $this->json(0, 'success', $list);
        }
        return $this->view();
    }

    public function shelf()
    {
        $id = input("id/d", 0);
        $on_shelf = input("on_shelf/d", 1);
        $model = new CouponMain();
        $repo = CouponRepository::getInstance($model);
        $coupon = $repo->findById($id);

        if (empty($coupon)) {
            return $this->json(4001, "优惠券不存在");
        }

        if (!in_array($on_shelf, [CouponMain::COMMON_OFF, CouponMain::COMMON_ON])) {
            return $this->json(4001, "状态错误");
        }
        $coupon->save(["on_shelf" => $on_shelf]);
        return $this->json();
    }

    /**
     * 列表
     *
     * @return Json|View
     * @throws Exception
     */
    public function info()
    {

        if ($this->request->isPost()) {
            $model = new CouponMain();
            $repo = CouponRepository::getInstance($model);
            $id = input("id/d");
            $keyword = $this->request->param('keyword/s', '');
            $page = $this->request->param('page/d', 1);
            $size = $this->request->param('size/d', 30);

            $list = $repo->couponMainHasList($id, $keyword, $page, $size);
            $time = time();
            $list["list"]->each(function ($item) use ($time) {
                if (strtotime($item['end_time']) < $time) {
                    $item->time_state = '已过期';
                } else {
                    $item->time_state = '未过期';
                }

            });
            return $this->json(0, 'success', $list);
        }
        $id = input("id/d");
        $model = new CouponMain();
        $repo = CouponRepository::getInstance($model);
        $coupon = $repo->getModel()->with(["business" => function ($query) {
            $query->field("code,business_name,business_subtitle,type")
                ->with('category');
        }, "couponType"])->where("id", $id)->find();
        if (empty($coupon)) {
            return $this->error("优惠券不存在");
        }
        $this->data["coupon"] = $coupon;
        return $this->view();
    }

}