<?php
/**
 * Created by PhpStorm.
 * User: durong
 * Date: 2019/7/8
 * Time: 下午23:50
 */
namespace App\Repositories;
use Acekyd\LaravelMP3\LaravelMP3;
use App\Models\PostMusic;
use App\Models\PostMusicCategory;
use App\Models\PostMusicCategoryRel;
use App\Models\PostMusicUser;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Dingo\Api\Http\Response;
use Illuminate\Database\QueryException;


class MusicRepository
{
    public function __construct(PostMusicCategoryRel $postMusicCategoryRel,PostMusicCategory $postMusicCategory,PostMusic $postMusic,PostMusicUser $postMusicUser)
    {
        $this->postMusicCategoryRel = $postMusicCategoryRel;
        $this->postMusicCategory = $postMusicCategory;
        $this->postMusic = $postMusic;
        $this->postMusicUser = $postMusicUser;
    }

    public function category_list($request)
    {
        $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
        $where = [];
        if(isset($request['id'])){
            $where[] = ['id', '=', $request['id']];
        }

        return $this->postMusicCategory->where($where)->orderBy('sort', 'asc')->paginate($perPage);
    }

    public function categoryCreate($request)
    {
        if($this->postMusicCategory->where('name', $request['name'])->exists()){
            throw new HttpException(500, '该分类已经存在');
        }

        $data = [
            'name' => $request['name'],
            'is_open' => $request['is_open'] ?? 0,
            'sort' => $request['sort'] ?? 999,
        ];

        if (!$this->postMusicCategory->create($data)) {
            throw new HttpException(500, '添加失败');
        }
    }

    public function categoryEdit($request)
    {
        $post_music_category = $this->postMusicCategory->where('id', $request['id'])->first();
        $post_music_category->name = $request['name'];
        $post_music_category->is_open = $request['is_open'] ?? 0;
        $post_music_category->sort = $request['sort'] ?? 999;
        $post_music_category->updated_at = date('Y-m-d H:i:s');

        $res = $post_music_category->save();
        if (!$res) {
            throw new HttpException(500, '音乐分类更新失败');
        }
    }

    public function editStatus($request)
    {
        $post_music_category = $this->postMusicCategory->find($request['id']);
        $post_music_category->is_open = $request['is_open'];
        $post_music_category->updated_at = date('Y-m-d H:i:s');

        $res = $post_music_category->save();

        if (!$res) {
            throw new HttpException(500, '修改状态失败');
        }
    }

    public function categoryDelete($request)
    {
         if ($this->postMusicCategoryRel->where('music_category_id',$request['id'])->exists()) {
             throw new HttpException(500, '当前分类下含有音乐,不能删除');
         }

        $post_music_category = $this->postMusicCategory->where('id', $request['id'])->first();
        $res = $post_music_category->delete();
        if (!$res){
            return Response::create([
                'message'  => '删除失败,请重试',
                'status_code'   => 500
            ]);
        }
    }

    public function musicList($request)
    {
        $perPage = isset($request['per_page']) ? $request['per_page'] : 20;
        $where = [];
        if(isset($request['id'])){
            $where[] = ['post_music_category_rel.id', '=', $request['id']];
        }
        if(isset($request['name'])){
            $where[] = ['post_music.name', 'like', "%{$request['name']}%"];
        }
        if(isset($request['category_id'])){
            $where[] = ['post_music_category.id', '=', $request['category_id']];
        }

        $postMusicList = $this->postMusicCategoryRel
            ->join('post_music_category', 'post_music_category.id', '=', 'post_music_category_rel.music_category_id')
            ->join('post_music', 'post_music.id', '=', 'post_music_category_rel.mid')
            ->select('post_music_category_rel.id','post_music_category_rel.sort','post_music.name','post_music.url','post_music.music_duration','post_music.created_at','post_music_category.name as category_name','post_music_category.id as category_id')
            ->where($where)
            ->orderBy('post_music_category_rel.sort', 'asc')
            ->paginate($perPage);

        return $postMusicList;

    }

    public function musicCreate($request)
    {
        $url = $request['url'];
        $data = [
            'name' => $request['name'],
            'url' => $url,
            'music_duration' => $request['music_duration'],
        ];
        $date = date('Y-m-d H:i:s');
        DB::beginTransaction();
        try {
            $res = $this->postMusic->create($data);
            if ($res) {
                $mid = $res->id;
                $create_category_rel = [
                    'mid' => $mid,
                    'music_category_id' => $request['category_id'],
                    'sort' => $request['sort'] ?? 999,
                    'created_at' => $date,
                    'updated_at' => $date
                ];
                $result = $this->postMusicCategoryRel->insert($create_category_rel);
                if (!$result) {
                    throw new HttpException(500, '音乐与分类关联-添加失败');
                }
            }

            DB::commit();
            return Response::create();

        } catch (QueryException $exception) {
            DB::rollBack();
            return Response::create([
                'message' => '添加失败,请重试',
                'error' => $exception->getMessage(),
                'status_code' => 500
            ]);
        }
    }

    public function musicEdit($request)
    {
        $post_music_rel = $this->postMusicCategoryRel->select('mid')->where('id', $request['id'])->first();
        $post_music = $this->postMusic->where('id',$post_music_rel->mid)->first();
        if (!$post_music) {
            throw new HttpException(500, '没有找到对应的音乐');
        }
        $date = date('Y-m-d H:i:s');
        $post_music->name = $request['name'];
        $post_music->url = $request['url'];
        $post_music->music_duration = $request['music_duration'];
        $post_music->updated_at = $date;
        DB::beginTransaction();
        try{
                $res = $post_music->save();
                if ($res) {
                    $create_category_rel = [
                        'mid' => $post_music->id,
                        'music_category_id' => $request['category_id'],
                        'sort' => $request['sort'] ?? 999,
                        'created_at' => $date,
                        'updated_at' => $date,
                    ];
                    $result = $this->postMusicCategoryRel->where('id',$request['id'])->update($create_category_rel);
                    if (!$result){
                        throw new HttpException(500, '音乐与分类关联-修改失败');
                    }
                }

            DB::commit();
            return Response::create();

        }catch (QueryException $exception){
            DB::rollBack();
            return Response::create([
                'message'  => '修改失败,请重试',
                'error' => $exception->getMessage(),
                'status_code'   => 500
            ]);
        }

    }

    public function musicDelete($request)
    {
        $post_music_rel = $this->postMusicCategoryRel->where('id', $request['id'])->first();
        DB::beginTransaction();
        try {
            $res = $post_music_rel->delete();
            if ($res) {
                $post_music = $this->postMusic->where('id',$post_music_rel->mid)->delete();
                if (!$post_music){
                    throw new HttpException(500, '音乐删除失败');
                }
            }
            DB::commit();
            return Response::create();

        } catch (QueryException $exception) {
            DB::rollBack();
            return Response::create([
                'message' => '删除失败,请重试',
                'error' => $exception->getMessage(),
                'status_code' => 500
            ]);
        }
    }

    public function userMusic($request)
    {
        $perPage = isset($request['per_page']) ? $request['per_page'] : 20;

        return $this->postMusicUser->orderBy('id', 'asc')->paginate($perPage);

    }


}