<?php

namespace app\api\controller;

use app\common\model\TwoPromiseMoneyRecord;
use app\common\service\ConfigService;

class MerchantVipLevel extends BaseShopController
{
    public function list()
    {
        $data = \app\common\model\MerchantVipLevel::order('sort asc')->select();

        return show(1,'VIP列表',$data);
    }

    public function createOrder()
    {
        $params = $this->request->post();

        if (!isset($params['id'])) {
            return show(config('status.error'), '请选择VIP等级');
        }

        $vl = \app\common\model\MerchantVipLevel::where('id', $params['id'])->find();

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

        try {
            $order_data = [
                'sn' => time() . round(10000, 99999),
                'user_id' => $this->userId,
                'order_amount' => $vl['join_price'],
                'message' => isset($params['message']) ? $params['message'] : '',
                'vip_level_id' => $vl->id
            ];
            $res = \app\common\model\MerchantVipOrder::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 orderList()
    {
        $params = $this->request->param();

        $where = [];

        if (isset($params['pay_status'])) {
            $where[] = [
                'pay_status', '=', $params['pay_status']
            ];

        }

        $data = \app\common\model\MerchantVipOrder::with('vipLevel')->where($where)->where('user_id', $this->userId)->paginate()->toArray();

        foreach ($data['data'] as &$item) {
            $item['pay_time'] = date('Y-m-d H:i:s', $item['pay_time']);
        }

        return show(1,'订单列表',$data);
    }

    public function orderDetail($id)
    {
        $data = \app\common\model\MerchantVipOrder::where('id', $id)->where('user_id', $this->userId)->find()->toArray();

        if (!$data) {
            return show(config('status.error'), '订单不存在');
        }

        $data['pay_time'] = date('Y-m-d H:i:s', $data['pay_time']);

        return show(1,'订单详情',$data);
    }
}