<?php

namespace App\Services\Book;

use App\Consts\ErrorConst;
use App\Facade\Site;
use App\Libs\Utils;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use OSS\Core\OssException;
use OSS\OssClient;

class BookService
{

    public function __construct() {

    }

    public function getBookList($data) {
        $bid = getProp($data, 'bid');
        $book_name = getProp($data, 'book_name');
        $status = getProp($data, 'status');

        $query = DB::table('books as b')->leftJoin('book_configs as bc', 'b.id', '=', 'bc.bid')
        ->where('b.size', '<', 30000)->where('b.status', 1)
        ->whereIn('bc.cp_source', ['ycsd', 'yqsd'])->whereIn('bc.is_on_shelf', [1,2])->select('b.status', 'bc.*', 
        DB::raw('(select count(id) from mp_book_version where bid = b.id) as version_count'));

        if ($bid) {
            $query->where('b.id', $bid);
        }

        if ($book_name) {
            $query->where('bc.book_name', 'like', "%{$book_name}%");
        }

        if ($status !== '') {
            $query->where('b.status', $status);
        }

        $result = $query->orderBy('b.id')->paginate();

        return $result;
    }

    public function getAllBooks($data) {
        $bid = getProp($data, 'bid');
        $book_name = getProp($data, 'book_name');

        $query = DB::table('book_configs')->whereIn('is_on_shelf', [1,2])->select('bid', 'book_name');
        if ($bid) {
            $query->where('bid', $bid);
        }

        if ($book_name) {
            $query->where('book_name', 'like', "%{$book_name}%");
        }

        return $query->orderBy('bid', 'desc')->get()->map(function($value) {
            return (array)$value;
        })->toArray();
    }

    public function getBookVersion($data) {
        $bid = getProp($data, 'bid');
        if (!$bid) Utils::throwError('20003:请选择书籍');

        return DB::table('mp_book_version')->where('bid', $bid)->orderBy('id', 'desc')->select('bid', 'book_name', 'id as version_id', 'version_name')
        ->get()->map(function($value) {
            $value = (array)$value;
            $value['version_name'] = $value['book_name']."【{$value['version_name']}】";
            return $value;
        })->toArray();
    }

    public function addBookVersion($data) {
        $bid = getProp($data, 'bid');
        if (!$bid) Utils::throwError('20003:请选择书籍');

        $version_name = trim(getProp($data, 'version_name'));
        if (!$version_name) Utils::throwError('20003:请填写版本名');
        $book_name = DB::table('book_configs')->where('bid', $bid)->value('book_name');
        if (DB::table('mp_book_version')->where('bid', $bid)->where('version_name', $version_name)->exists()) Utils::throwError('20003:版本名已存在');
        
        $all_chapters = DB::table('chapters')->where('bid', $bid)->where('is_check', 1)->where('is_deleted', 0)->select('id', 'name', 'sequence', 'size', 'chapter_content_id')->get();
        try {
            DB::beginTransaction();

            $version_id = DB::table('mp_book_version')->insertGetId([
                'bid' => $bid,
                'book_name' => $book_name,
                'version_name' => $version_name,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
            if (!$version_id) {
                DB::rollBack();
                Utils::throwError('20003:创建版本失败');
            }

            $insert_data = [];
            foreach ($all_chapters as $chapter) {
                $insert_data[] = [
                    'bid'                   => $bid,
                    'book_name'             => $book_name,
                    'version_id'            => $version_id,
                    'version_name'          => $version_name, 
                    'cid'                   => getProp($chapter, 'id'),
                    'chapter_name'          => getProp($chapter, 'name'),
                    'sequence'              => getProp($chapter, 'sequence'),
                    'size'                  => getProp($chapter, 'size'),
                    'generate_status'       => '待制作',
                    'created_at'            => date('Y-m-d H:i:s'),
                    'updated_at'            => date('Y-m-d H:i:s'),
                ];
            }

            $boolen = DB::table('mp_chapter_audios')->insert($insert_data);
            if (!$boolen) {
                DB::rollBack();
                Utils::throwError('20003:带入章节失败');
            }

        }catch (\Exception $e) {
            DB::rollBack();
            Utils::throwError('20003:'.$e->getMessage());

        }

        DB::commit();
        return [
            'bid'           => $bid,
            'version_id'    => $version_id,
            'version_name'  => $book_name."【{$version_name}】",
        ];
    }

    public function editBookVersion($data) {
        $version_id = getProp($data, 'version_id');
        $version_name = trim(getProp($data, 'version_name'));
        if (!$version_id) Utils::throwError('20003:请选择版本');
        if (!$version_name) Utils::throwError('20003:请填写版本名');

        DB::beginTransaction();
        $boolen = DB::table('mp_book_version')->where('id', $version_id)->update([
            'version_name' => $version_name,
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        if (!$boolen) {
            DB::rollBack();
            Utils::throwError('20003:修改书籍版本名称失败');
        }

        $boolen1 = DB::table('mp_chapter_audios')->where('version_id', $version_id)->update([
            'version_name' => $version_name,
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        if (!$boolen1) {
            DB::rollBack();
            Utils::throwError('20003:修改章节版本名称失败');
        }

        DB::commit();
        return true;
    }

    public function getChapterList($data) {
        $bid = getProp($data, 'bid');
        $version_id = getProp($data, 'version_id');
        if (!$bid) Utils::throwError('20003:请选择书籍');
        if (!$version_id) Utils::throwError('20003:请选择版本');
        $generate_status = getProp($data, 'generate_status');
        $book = DB::table('books as b')->leftJoin('book_configs as bc', 'b.id', '=', 'bc.bid')->where('b.id', $bid)->whereIn('bc.is_on_shelf', [1,2])
        ->select('bc.book_name', 'bc.cover', 'b.size', 'b.chapter_count', 'b.intro')->first();
        if (!$book) Utils::throwError('20003:书籍不存在');
        $header = (array)$book;
        $header['cover'] = addPrefix($header['cover']);
        $header['intro'] = filterIntro($header['intro']);
        $role_info = DB::table('mp_book_version')->where('id', $version_id)->where('bid', $bid)->value('role_info');
        if ($role_info) {
            foreach(json_decode($role_info, true) as $role => $timbre) {
                // 获取音色信息
                $voice_type = getProp($timbre, 'timbre_type');
                $timbre_info = DB::table('mp_timbres')->where('timbre_type', $voice_type)->first();
                $header['role_info'][] = [
                    'role'                  => $role,
                    'voice_type'            => $voice_type,
                    'voice_name'            => getProp($timbre, 'timbre_name'),
                    'language'              => getProp($timbre_info,'language'),
                    'dialect'               => getProp($timbre_info,'dialect'),
                    'emotion'               => getProp($timbre_info,'emotion'),
                    'first_category_id'     => getProp($timbre_info,'first_category_id'),
                    'first_category_name'   => getProp($timbre_info, 'first_category_name'),
                    'second_category_id'    => getProp($timbre_info,'second_category_id'),
                    'second_category_name'  => getProp($timbre_info, 'second_category_name'),
                    'third_category_id'     => getProp($timbre_info,'third_category_id'),
                    'third_category_name'   => getProp($timbre_info,'third_category_name'),
                    'audio_url'             => getProp($timbre_info,'audio_url'),
                    'label'                 => getProp($timbre_info, 'label'),
                ];
            }
        }else {
            $header['role_info'] = [];
        }
        $query = DB::table('mp_chapter_audios')->where('bid', $bid)->where('version_id', $version_id)
        ->select('cid', 'chapter_name', 'sequence', 'size', 'generate_status', 'audio_url', 'remark');
        if ($generate_status) {
            $query->where('generate_status', $generate_status);
        }
        
        $list = $query->orderBy('sequence', 'asc')->paginate();

        return ['header' => $header, 'list' => $list];

    }

    public function getChapterContent($data) {
        $cid = getProp($data, 'cid');

        if (!$cid) Utils::throwError('20003:请选择章节');
        $content = DB::table('chapters as c')->leftJoin('chapter_contents as cc', 'c.chapter_content_id', '=', 'cc.id')->where('c.id', $cid)->value('cc.content');
        if (!$content) Utils::throwError('20003:章节内容不存在');
        $content = filterContent($content);

        return $content;
    }

    public function getVersionList($data) {
        $version_id = getProp($data, 'version_id');
        $version_name = getProp($data, 'version_name');
        $book_name = getProp($data, 'book_name');

        $query = DB::table('mp_book_version as v')->leftJoin('book_configs as bc', 'v.bid', '=', 'bc.bid');
        if ($version_id) $query->where('v.id', $version_id);
        if ($version_name) $query->where('v.version_name', 'like', '%'.$version_name.'%');
        if ($book_name) $query->where('bc.book_name', 'like', '%'.$book_name.'%');
        $list = $query->select('v.*', 'bc.book_name')->paginate();

        return $list;
    }


    public function getTaskList($data) {
        $task_id = getProp($data, 'task_id');
        $task_name = getProp($data, 'task_name');
        $generate_status = getProp($data, 'generate_status');

        $query = DB::table('mp_audio_tasks')->select('id', 'task_name', 'generate_status', 'bid', 'version_id', 'cid', 'created_at');
        if ($task_id) $query->where('id', $task_id);
        if ($task_name) $query->where('task_name', 'like', '%'.$task_name.'%');
        if ($generate_status) $query->where('generate_status',  $generate_status);
        $list = $query->orderBy('id', 'desc')->paginate();

        return $list;
    }

    public function getTaskDetail($data) {
        $task_id = getProp($data, 'task_id');

        $result = DB::table('mp_audio_tasks')->where('id', $task_id)->select('id as task_id', 'task_name', 'generate_status', 'generate_json', 'bid', 'version_id', 'cid')->first();
        if (!$result) Utils::throwError('20003:任务不存在');
        $result = (array)$result;
        $result['generate_json'] = json_decode($result['generate_json'], true);

        return $result;
    }
}
