<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Core\Auth;
use App\Models\FlowerTicketModel;
use Illuminate\Http\Request;

class FlowerTicket extends Controller
{
    /**
     * @param  Request  $request
     * @return array
     * @api {Post} /api/msy/flowerticket/store 创建兑换卡
     * @apiName 兑换卡生成
     * @apiGroup flowerticket
     *
     * @apiParam {int} validity_at 过期时间
     * @apiParam {int} red_flower 红花数量
     * @apiParam {int} gold_flower 金花数量
     * @apiParam {int} jsk 解锁卡
     * @apiParam {int} count 生成数量
     *
     * @apiSuccess {json}
     * {
     *      'code': 200,
     *      'message': 'success',
     *      'data': {
     *          'success': 2,
     *          'fail': 1,
     *          'ticket_ids': [1, 2, 3]
     *      }
     * }
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'validity_at' => 'required',
            'red_flower' => 'required',
            'gold_flower' => 'required',
            'jsk' => 'required',
            'count' => 'required',
        ]);
        $count = $request->input('count');
        $ticketids = array();
        for ($i = 0; $i < $count; $i++) {
            try {
                $data = array(
                    'validity_at' => $request->input('validity_at'),
                    'code' => bin2hex(\openssl_random_pseudo_bytes(4)),
                    'red_flower' => $request->input('red_flower'),
                    'gold_flower' => $request->input('gold_flower'),
                    'jsk' => $request->input('jsk')
                );
                $flowerTicketModel = new FlowerTicketModel();
                $ticket = $flowerTicketModel->fill($data);
                if ($ticket->save()) {
                    array_push($ticketids, $ticket->id);
                }
            } catch (\Exception $e) {
            }
        }
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => [
                'success' => count($ticketids),
                'fail' => $count - count($ticketids),
                'ticket_ids' => $ticketids
            ],
        );
    }

    /**
     * @param  Request  $request
     * @param  int  $ticket_id
     * @return array
     * @api {Post} /api/msy/flowerticket/:ticket_id/update ticket_id 兑换码id
     * @apiName 更新兑换码
     * @apiGroup flowerticket
     *
     * @apiParam {int} validity_at 过期时间
     * @apiParam {int} red_flower 红花数量
     * @apiParam {int} gold_flower 金花数量
     * @apiParam {int} jsk 解锁卡
     * @apiParam {int} count 生成数量
     *
     * @apiSuccess {json}
     * {
     *      'code': 200,
     *      'message': 'success'
     * }
     */
    public function update(Request $request, int $ticket_id)
    {
        $this->validate($request, [
            'validity_at' => '',
            'red_flower' => '',
            'gold_flower' => '',
            'jsk' => '',
        ]);
        $flowerTicketModel = new FlowerTicketModel();
        $ticket = $flowerTicketModel->find($ticket_id);
        if (collect($ticket)->isEmpty()) {
            return array(
                'code' => 101,
                'message' => '参数错误'
            );
        }
        $ticket->fill($request->toArray());
        if ($ticket->save()) {
            return array(
                'code' => 200,
                'message' => 'success'
            );
        } else {
            return array(
                'code' => 501,
                'message' => '数据库错误'
            );
        }
    }

    /**
     * @param  int  $ticket_id
     * @return array
     * @throws \Exception
     * @api {Get} /api/msy/flowerticket/:ticket_id/delete ticket_id 兑换码id
     * @apiName 删除兑换码
     * @apiGroup flowerticket
     *
     * @apiSuccess {json}
     * {
     *      'code': 200,
     *      'message': 'success'
     * }
     *
     * @apiFail {json}
     * {
     *      'code': 102,
     *      'message': '该兑换码已被领取'
     * }
     */
    public function delete(int $ticket_id)
    {
        $flowerTicketModel = new FlowerTicketModel();
        $ticket = $flowerTicketModel->find($ticket_id);
        if (collect($ticket)->isEmpty()) {
            return array(
                'code' => 101,
                'message' => '参数错误'
            );
        }
        if (!empty($ticket->uid)) {
            return array(
                'code' => 102,
                'message' => '该兑换码已被领取'
            );
        }
        if ($ticket->delete()) {
            return array(
                'code' => 200,
                'message' => 'success'
            );
        } else {
            return array(
                'code' => 501,
                'message' => '数据库错误'
            );
        }
    }

    /**
     * @param  int  $page
     * @return array
     * @api {Get} /api/msy/flowerticket/list/:page page 页数
     * @apiName 获取兑换码列表
     * @apiGroup flowerticket
     *
     * @apiSuccess {json}
     * {
     *      'code': 200,
     *      'message': 'success',
     *      'data': {
     *          'count': '总数',
     *          'page':  '页数',
     *          'limit': '每页数量',
     *          'tickets': [{
     *            'id': '兑换码id',
     *            'uid': '领取人uid',
     *            'code': '兑换码'
     *          }]
     *      }
     * }
     */
    public function getList(int $page = 1)
    {
        $flowerTicketModel = new FlowerTicketModel();
        $tickets = $flowerTicketModel->take(100)->skip(($page - 1) * 100)->get();
        $count = $flowerTicketModel->count();
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => [
                'count' => $count,
                'page' => $page,
                'limit' => 100,
                'tickets' => $tickets
            ]
        );
    }

    /**
     * @param  Request  $request
     * @return array
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     * @api {Get} api/msy/flowerticket/claim 领取兑换码
     * @apiName 领取兑换码
     * @apiGroup flowerticket
     *
     * @apiParam {string} code 兑换码code
     *
     * @apiSuccess {json}
     * {
     *      'code': 200,
     *      'message': 'success'
     * }
     */
    public function claim(Request $request)
    {
        $uid = Auth::auth();
        $this->validate($request, [
            'code' => 'required'
        ]);
        $code = $request->input('code');
        $flowerTicketModel = new FlowerTicketModel();
        $ticket = $flowerTicketModel->where('code', $code)->first();
        if (collect($ticket)->isEmpty()) {
            return array(
                'code' => 101,
                'message' => '兑换码错误'
            );
        }
        if ($ticket->validity_at < time() || !empty($ticket->uid)) {
            return array(
                'code' => 102,
                'message' => '兑换码失效'
            );
        }
        \DB::beginTransaction();
        try {
            \DB::table('kdgx_msy_flower_ticket')->where('id', $ticket->id)->update(['uid' => $uid]);
            \DB::table('kdgx_partner_charge_user')->where('uid', $uid)->increment('red_flower', $ticket->red_flower);
            \DB::table('kdgx_partner_charge_user')->where('uid', $uid)->increment('gold_flower', $ticket->gold_flower);
            $ticketController = new Ticket();
            for ($i = 0; $i < $ticket->jsk; $i++) {
                $ticketController->create(5, $uid);
            }
            \DB::table('kdgx_partner_charge_pay_logs')->create([
                'uid' => $uid,
                'create_at' => time(),
                'type' => 11,
                'red_flower' => $ticket->red_flower,
                'gold_flower' => $ticket->gold_flower,
                'jsk' => $ticket->jsk
            ]);
            \DB::commit();
            return array(
                'code' => 200,
                'message' => 'success'
            );
        } catch (\Exception $e) {
            \DB::rollBack();
            return array(
                'code' => 501,
                'message' => $e->getMessage()
            );
        }
    }
}
