<?php

namespace App\Http\Controllers\V1\User;

use App\Http\Controllers\V1\Controller;
use App\Models\Episode;
use App\Models\EpisodesList;
use App\Models\UserConsumeRecord;
use App\Models\UserEpisodesRecord;
use App\Models\UserInfo;
use Illuminate\Database\QueryException;

class EpisodeController extends Controller
{
    public function buyRecord($episode)
    {
        $lists = UserEpisodesRecord::filterUser()
            ->select(['episodes_id', 'list_id'])
            ->where('episodes_id', $episode)
            ->get()
            ->pluck('list_id');

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

    public function buy($episode, $list)
    {
        try {
            \DB::beginTransaction();

            $episode = Episode::find($episode);
            $list    = EpisodesList::find($list);
            $user    = UserInfo::find(\user()->id);

            $count = UserEpisodesRecord::filterUser()->where('list_id', $list->id)->count();
            if ($count) {
                return $this->error('请勿重复购买');
            }

            if ($user->integral < $list->sale_price) {
                return $this->success([
                    'overage' => 0,
                ], 0, '余额不足');
            }

            // 购买记录
            $record              = new UserEpisodesRecord();
            $record->user_id     = \user()->id;
            $record->episodes_id = $episode->id;
            $record->list_id     = $list->id;
            $record->price       = $list->sale_price;
            $record->status      = 1;
            $record->save();

            // 记录日志
            app(UserConsumeRecord::class)->record(
                \user()->id,
                UserConsumeRecord::TYPE_CONSUME,
                -$list->sale_price,
                "购买短剧 {$episode->name} 第{$list->sort}集"
            );
            // 扣除金币
            $user->integral = $user->integral - $list->sale_price;
            $user->save();

            \DB::commit();

            return $this->success(['episode_id' => $episode, 'list_id' => $list]);
        } catch (QueryException $e) {
            \DB::rollBack();

            return $this->error('购买失败');
        } catch (\Exception $ex) {
            \DB::rollBack();

            return $this->error('购买失败');
        }
    }
}
