<?php

namespace app\api\controller;

class MerchantTop extends BaseShopController
{
    public function createOrder()
    {
        $params = $this->request->post();

        $merchant = \app\common\model\Merchant::where('user_id', $this->userId)->find();

        if (!$merchant) {
            return show(config('status.error'), '商户不存在');
        }

        $vipLevel = \app\common\model\MerchantVipLevel::where('id', $merchant->vip_id)->find();

        if (!$vipLevel) {
            return show(config('status.error'), '会员等级不存在');
        }

        if (!isset($params['days'])) {
            return show(config('status.error'), '请选择天数');
        }

        $lists = explode(',', $vipLevel->top_money_list);

        $found = false;
        $price = null;

        foreach ($lists as $list) {
            [$dayCount, $currentPrice] = explode('=', $list);

            if ($dayCount == $params['days']) {
                $found = true;
                $price = $currentPrice;
                break;
            }
        }

        if (!$found || $price == null) {
            return show(config('status.error'), '请选择正确的天数');
        }

        try {
            $order_data = [
                'sn' => time() . round(10000, 99999),
                'user_id' => $this->userId,
                'order_amount' => $price,
                'message' => isset($params['message']) ? $params['message'] : '',
                'merchant_id' => $merchant->id,
                'days' => $params['days']
            ];
            $res = \app\common\model\MerchantTopOrder::create($order_data);

            if (!$res) {
                return show(config('status.error'), '订单创建失败');
            }

            return show(config('status.success'), '订单创建成功', [
                'order_id' => $res->id,
            ]);
        } catch (\Exception $e) {
            return show(config('status.error'), $e->getMessage());
        }
    }

    public function listOrder()
    {
        $data = \app\common\model\MerchantTopOrder::where('user_id', $this->userId)->select();

        return show(config('status.success'), '获取成功', $data);
    }

    public function orderDetail($id)
    {
        $data = \app\common\model\MerchantTopOrder::where('id', $id)->find();
        if (!$data) {
            return show(config('status.error'), '订单不存在');
        }
        return show(config('status.success'), '获取成功', $data);
    }

    public function list()
    {
        $data = \app\common\model\MerchantTopList::with(['merchant'])
            ->where([
                [
                    'expire_time', '>', time()
                ]
            ])
            ->select();

        return show(config('status.success'), '获取成功', $data);
    }
}