<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Core\Auth;
use App\Models\BuyInviteModel;
use App\Models\ConfessModel;
use App\Models\User\UserModel;
use App\Models\NoticeModel;
use App\Models\PartnerModel;
use App\Models\RecodeModel;
use App\Models\TicketModel;
use Illuminate\Http\Request;
use phpDocumentor\Reflection\Types\Integer;

/**
 * 系统内部小花交易转换
 */
class Pay extends Controller
{
    public const PRICE = 5;
    /**
     * @param  int  $partner_id
     * @param  Request  $request
     * @return array
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function buyByTicket(int $partner_id, Request $request)
    {
        $this->validate($request, [
            'ticket_code' => 'required'
        ]);
        $partner = $this->look($partner_id);
        if ($partner) {
            return array(
                'code' => 200,
                'message' => 'success',
                'data' => $partner
            );
        } else {
            $partner = PartnerModel::find($partner_id);
            $uid = Auth::auth();
            $ticketObj = new Ticket();
            if ($ticketObj->checkTicket($request->input('ticket_code'))) {
                \DB::beginTransaction();
                try {
                    // 核销解锁卡
                    TicketModel::where('code', $request->input('ticket_code'))->update(['state' => 1]);
                    // 添加解锁记录
                    \DB::table('kdgx_partner_charge_recode')->insert([
                        'uid' => $uid,
                        'partner_id' => $partner->id,
                        'create_at' => time()
                    ]);
                    // 记录购买日志
                    \DB::table('kdgx_partner_charge_pay_logs')->insert([
                        'uid' => $uid,
                        'create_at' => time(),
                        'type' => 1,
                        'gold_flower' => 0,
                        'red_flower' => 0,
                        'jsk' => 1,
                        'type_id' => $partner->id,
                        'remark' => "解锁卡「{$request->input('ticket_code')}」购买对象卡片联系方式"
                    ]);
                    // 气泡双向通知
                    NoticeModel::create([
                        'uid' => $uid,
                        'title' => '解锁联系方式成功',
                        'content' => "你刚刚进行的解锁联系方式操作成功。卡片id: {$partner->id}",
                        'type' => 1,
                        'type_id' => $partner->id,
                    ]);
                    NoticeModel::create([
                        'uid' => $partner->uid,
                        'title' => '卡片被解锁通知',
                        'content' => "你上架的卡片被id: {$uid} 解锁",
                        'type' => 4,
                        'type_id' => $uid
                    ]);
                    \DB::commit();
                    return array(
                        'code' => 200,
                        'message' => 'success',
                        'data' => $partner
                    );
                } catch (\Exception $e) {
                    \DB::rollBack();
                    throw new \ApiException('数据库异常', 501);
                }
            } else {
                throw new \ApiException('卡劵错误', 101);
            }
        }
    }

    /**
     * 通过小fa解锁卡片
     * @param  int  $partner_id
     * @param  Request  $request
     * @return array
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function buyByflower(int $partner_id, Request $request)
    {
        $partner = $this->look($partner_id);
        if ($partner) {
            return array(
                'code' => 200,
                'message' => 'success',
                'data' => $partner
            );
        } else {
            $partner = PartnerModel::find($partner_id);
            $uid = Auth::auth();
            // 检验账户余额
            if ($request->input('gold_flower') < 0 || $request->input('red_flower') < 0) {
                return array(
                    'code' => 101,
                    'message' => '参数错误'
                );
            }
            $user = UserModel::find($uid);
            if (
                $user->gold_flower < $request->input('gold_flower')
                || $user->red_flower < $request->input('red_flower')
            ) {
                return response([
                    'code' => 102,
                    'message' => '账户小fa不足'
                ]);
            }
            $buyInviteModel = new BuyInviteModel();
            $dis = $buyInviteModel->effectiveInvite($uid, $partner_id);
            $price = (float)self::PRICE * (100 - $dis) / 100;
            if ($request->input('gold_flower') + $request->input('red_flower') < $price) {
                return array(
                    'code' => 103,
                    'message' => "需要{$price}朵小fa"
                );
            }
            \DB::beginTransaction();
            try {
                // 核销fa
                $user->decrement('gold_flower', $request->input('gold_flower'));
                $user->decrement('red_flower', $request->input('red_flower'));
                // 添加解锁记录
                \DB::table('kdgx_partner_charge_recode')->insert([
                    'uid' => $uid,
                    'partner_id' => $partner->id,
                    'create_at' => time()
                ]);
                // 记录购买日志
                \DB::table('kdgx_partner_charge_pay_logs')->insert([
                    'uid' => $uid,
                    'create_at' => time(),
                    'type' => 1,
                    'gold_flower' => 0,
                    'red_flower' => 0,
                    'jsk' => 1,
                    'type_id' => $partner->id,
                    'remark' => "小fa购买对象卡片联系方式"
                ]);
                // 气泡双向通知
                NoticeModel::create([
                    'uid' => $uid,
                    'title' => '解锁联系方式成功',
                    'content' => "你刚刚进行的解锁联系方式操作成功。卡片id: {$partner->id}",
                    'type' => 1,
                    'type_id' => $partner->id,
                ]);
                NoticeModel::create([
                    'uid' => $partner->uid,
                    'title' => '卡片被解锁通知',
                    'content' => "你上架的卡片被id: {$uid} 解锁",
                    'type' => 4,
                    'type_id' => $uid,
                ]);
                \DB::commit();
                return array(
                    'code' => 200,
                    'message' => 'success',
                    'data' => $partner
                );
            } catch (\Exception $e) {
                \DB::rollBack();
                throw new \ApiException('数据库异常', 501);
            }
        }
    }

    /**
     * 查看卡片详情
     * @param  int  $partner_id
     * @return PartnerModel|bool|mixed
     */
    public function look(int $partner_id)
    {
        $uid = Auth::auth();
        $partner = PartnerModel::find($partner_id);
        if (collect($partner)->isEmpty()) {
            throw new \ApiException('卡片不存在', 404);
        }
        if ($partner->is_sell != 1 || $partner->is_hide != 0) {
            throw new \ApiException('应用户要求，该卡片已经下架', 401);
        }
        // 自己上传的卡片
        if ($partner->uid == $uid) {
            return $partner;
        }
        // 已经购买过的卡片
        if (RecodeModel::where(array(['uid', $uid], ['partner_id', $partner->id]))->exists()) {
            return $partner;
        }
        // 被接收表白的卡片
        $where = array(
            ['uid', $uid],
            ['partner_id', $partner->id],
            ['receive_state', 1],
            ['state', 1]
        );
        if (ConfessModel::where($where)->exists()) {
            return $partner;
        } else {
            return false;
        }
    }

    /**
     * 兑换解锁卡
     * @param  Request  $request
     * @return array
     */
    public function exchangeTicket(Request $request)
    {
        $uid = Auth::auth();
        if ($request->input('gold_flower') < 0 || $request->input('red_flower') < 0) {
            return array(
                'code' => 101,
                'message' => '参数错误'
            );
        }
        $user = UserModel::find($uid);
        if (
            $user->gold_flower < $request->input('gold_flower')
            || $user->red_flower < $request->input('red_flower')
        ) {
            return array(
                'code' => 102,
                'message' => '账户小fa不足'
            );
        }
        if ($request->input('gold_flower') + $request->input('red_flower') < self::PRICE) {
            return array(
                'code' => 103,
                'message' => "需要{self::PRICE}朵小fa"
            );
        }
        \DB::beginTransaction();
        try {
            $ticketObj = new Ticket();
            $ticket_id = $ticketObj->create(5, $uid);
            $user->decrement('gold_flower', $request->input('gold_flower'));
            $user->decrement('red_flower', $request->input('red_flower'));
            \DB::table('kdgx_partner_charge_pay_logs')->insert([
                'uid' => $uid,
                'create_at' => time(),
                'type' => 1,
                'gold_flower' => $request->input('gold_flower'),
                'red_flower' => $request->input('red_flower'),
                'jsk' => 0,
                'type_id' => 0,
                'remark' => "兑换一张解锁卡"
            ]);
            \DB::commit();
            return array(
                'code' => 200,
                'message' => 'success',
                'data' => [
                    'ticket_id' => $ticket_id
                ],
            );
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \ApiException('数据库异常', 501);
        }
    }
}
