<?php

namespace App\Api\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use XuanChen\Coupon\Coupon;

class UserController extends Controller
{

    public function index()
    {
        $this->user = User::find(1);
        $data       = [
            'user_id'  => $this->user->id,
            'nickname' => $this->user->info->nickname,
        ];

        return $this->success($data);
    }

    public function check(Request $request)
    {
        $res = $this->checkSign($request);
        if (! is_array($res)) {
            return $this->error($res);
        }
        $user_id = $res['user_id'];
        $user    = User::find($user_id);

        return $this->success($user);
    }

    /**
     * Notes: 发券
     *
     * @Author: 玄尘
     * @Date  : 2020/6/29 13:57
     */
    public function grant(Request $request)
    {
        $inputdata = $request->all();
        $res       = $this->checkSign($request);
        //获取解密后数据
        $inputdata['jiemi'] = $res;
        $log                = $this->createLog($request->url(), 'POST', $inputdata, 'grant'); //添加日志

        if (is_string($res)) {
            return $this->error($res, $log);
        }

        $validator = \Validator::make($res, [
            'activityId' => 'required',
            'outletId'   => 'required',
            'mobile'     => 'required',
        ], [
            'activityId.required' => '缺少活动编码',
            'outletId.required'   => '缺少网点id',
            'mobile.required'     => '缺少手机号',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), $log);
        }

        $res = Coupon::Grant($res['activityId'], $res['outletId'], $res['mobile']);

        if (is_string($res)) {
            return $this->error($res, $log);
        }

        return $this->success($res, $log);

    }

    /**
     * Notes: 查询
     *
     * @Author: 玄尘
     * @Date  : 2020/7/22 11:23
     * @param  \Illuminate\Http\Request  $request
     */
    public function query(Request $request)
    {
        $inputdata          = $request->all();
        $res                = $this->checkSign($request);
        $inputdata['jiemi'] = $res;

        $log = $this->createLog($request->url(), 'POST', $inputdata, 'query'); //添加日志

        if (is_string($res)) {
            return $this->error($res, $log);
        }

        $validator = \Validator::make($res, [
            'redemptionCode' => 'required',
            'outletId'       => 'required',
        ], [
            'redemptionCode.required' => '缺少卡券兑换码',
            'outletId.required'       => '缺少网点id',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), $log);
        }

        $redemptionCode = $res['redemptionCode'];
        $outletId       = $res['outletId'];

        try {
            $res = Coupon::Query($redemptionCode, $outletId);

            if (is_string($res)) {
                return $this->error($res, $log);
            }

            if (isset($res['productItemList'])) {
                $ticket = explode('-', $res['productItemList'][0]['thirdPartyGoodsId']);

                $full  = $ticket[1]; //full100
                $price = $ticket[2];
                preg_match('/\d+/', $full, $result);
                $status = [
                              0 => 1,
                              1 => 2,
                              2 => 2,
                              3 => 3,
                              4 => 3,
                          ][$res['status']];
                $res    = [
                    'name'      => $res['couponName'],
                    'code'      => $res['redemptionCode'],
                    'full'      => $result[0],
                    'price'     => $price,
                    'status'    => $status,
                    'used_at'   => $res['issueDate'],
                    'startTime' => $res['startTime'],
                    'endTime'   => $res['endTime'],
                ];
            }

            return $this->success($res, $log);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage(), $log);
        }

    }

    //作废
    public function destroy(Request $request)
    {
        $inputdata          = $request->all();
        $res                = $this->checkSign($request);
        $inputdata['jiemi'] = $res;
        $log                = $this->createLog($request->url(), 'POST', $inputdata, 'destroy'); //添加日志

        if (is_string($res)) {
            return $this->error($res, $log);
        }

        $validator = \Validator::make($res, [
            'redemptionCode' => 'required',
            'outletId'       => 'required',
        ], [
            'redemptionCode.required' => '缺少卡券兑换码',
            'outletId.required'       => '缺少网点id',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), $log);
        }

        $redemptionCode = $res['redemptionCode'];
        $outletId       = $res['outletId'];
        $res            = Coupon::Destroy($redemptionCode, $outletId);

        if ($res !== true) {
            return $this->error($res, $log);
        }

        return $this->success('作废成功', $log);
    }

    //核销
    public function freezecoupon(Request $request)
    {
        $inputdata = $request->all();

        $res                = $this->checkSign($request);
        $inputdata['jiemi'] = $res;
        //插入日志表
        $log = $this->createLog($request->url(), 'POST', $inputdata, 'freezecoupon'); //添加日志

        if (! is_array($res)) {
            return $this->error($res, $log);
        }

        $validator = \Validator::make($res, [
            'redemptionCode' => 'required',
            'total'          => 'required',
            'outletId'       => 'required',
            //            'orderid'        => 'nullable|min:100',
        ], [
            'redemptionCode.required' => '缺少卡券兑换码',
            'total.required'          => '缺少订单总额',
            'outletId.required'       => '缺少网点id',
            'orderid.min'             => '订单id长度不能超过100个字符',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first(), $log);
        }

        $redemptionCode = $res['redemptionCode'] ?? ''; //'915400693355';
        $total          = $res['total'] ?? '';          //订单总额;
        $outletId       = $res['outletId'] ?? '';       //网点id;
        $orderid        = $res['orderid'] ?? '';        //订单id;
        $from           = $res['from'] ?? '';           //来源;

        $redemptionCode = trim($redemptionCode);
        $outletId       = trim($outletId);

        $coupon = Coupon::Redemption(
            $this->user,
            $redemptionCode,
            $total,
            $outletId,
            $orderid,
            $from
        );

        if (is_string($coupon)) {
            return $this->error($coupon, $log);
        }

        return $this->success($coupon, $log);
    }

}
