<?php

namespace App\Http\Services;

use App\Models\Course;
use App\Models\Video;
use Illuminate\Support\Facades\DB;

class VideoService extends BaseService
{

    public function addVideoHandle($userInfo, $videoInfo) {
        $result = [
            'res' => false,
            'msg' => '添加成功',
            'data' => [],
        ];

        if (!isset($videoInfo['title']) || mb_strlen($videoInfo['title']) == 0 || mb_strlen($videoInfo['title']) > 32) {
            $result['msg'] = '标题异常';
            return $result;
        }

        if (!isset($videoInfo['url']) || mb_strlen($videoInfo['url']) == 0 || mb_strlen($videoInfo['url']) > 256) {
            $result['msg'] = '视频链接异常';
            return $result;
        }

        if (!empty($videoInfo['attribute'])) {
            if (!isValidJson($videoInfo['attribute'])) {
                $result['msg'] = '视频属性异常';
                return $result;
            }

            $videoInfo['attribute'] = json_encode($videoInfo['attribute'], JSON_UNESCAPED_UNICODE);
        }

        if (!isset($videoInfo['content_id']) || !is_numeric($videoInfo['content_id']) || $videoInfo['content_id'] <= 0) {
            $result['msg'] = '课程异常';
            return $result;
        }
        $videoInfo['content_id'] = intval($videoInfo['content_id']);

        // 判断课程是否存在
        $existedCourseInfo = (new Course())->findDataWithField(['id' => $videoInfo['content_id']], ['id']);
        if (empty($existedCourseInfo)) {
            $result['msg'] = '课程不存在';
            return $result;
        }

        // 准备写入
        $insertVideo = [
            'title' => $videoInfo['title'],
            'type' => 2,
            'url' => $videoInfo['url'],
            'content' => $videoInfo['content_id'],
            'operator' => $userInfo['id'],
        ];
        if (!empty($videoInfo['attribute'])) {
            $insertVideo['attribute'] = $videoInfo['attribute'];
        }
        $insertRes = (new Video())->insertData($insertVideo);
        if (false === $insertRes) {
            $result['msg'] = '添加失败';
            return $result;
        }

        $result['res'] = true;
        return $result;
    }

    public function getVideoListHandle($platform, $searchParam) {
        $result = [
            'res' => true,
            'msg' => '获取成功',
            'data' => [],
        ];

        $searchParam['page'] = intval($searchParam['page'] ?? 1);
        if ($searchParam['page'] <= 0) {
            $searchParam['page'] = 1;
        }

        $searchParam['page_size'] = intval($searchParam['page_size'] ?? 20);
        if ($searchParam['page_size'] <= 0 || $searchParam['page_size'] > 100) {
            $searchParam['page_size'] = 20;
        }

        $videoWhere = [];
        $field = [];
        if ($platform == 'applet') {
            $videoWhere['status'] = 2;
            $field = ['title', 'url', 'attribute', 'content as content_id'];
        } else {
            $field = ['id', 'title', 'url', 'attribute', 'content as content_id', 'status'];
        }

        $videoList = (new Video())->selectDataWithPage($videoWhere, $field, $searchParam['page_size'], 'id', 'ASC');
        foreach ($videoList['data'] as $index => $value) {
            $videoList['data'][$index]['attribute'] = json_decode($value['attribute'], true);
            $videoList['data'][$index]['content_id'] = intval($value['content_id']);
        }

        $result['data']['page'] = $searchParam['page'];
        $result['data']['page_size'] = $searchParam['page_size'];
        $result['data']['total'] = $videoList['total'];
        $result['data']['list'] = $videoList['data'];

        return $result;
    }

    public function deleteVideoHandle($userInfo, $videoInfo) {
        $result = [
            'res' => false,
            'msg' => '删除成功',
            'data' => [],
        ];

        if (!isset($videoInfo['video_id']) || !is_numeric($videoInfo['video_id']) || $videoInfo['video_id'] <= 0) {
            $result['msg'] = '视频id异常';
            return $result;
        }
        $videoInfo['video_id'] = intval($videoInfo['video_id']);

        $videoModel = new Video();
        $videoExistedInfo = $videoModel->findDataWithField(['id' => $videoInfo['video_id']], ['id']);
        if (empty($videoExistedInfo)) {
            $result['msg'] = '视频不存在';
            return $result;
        }

        $deleteRes = $videoModel->deleteData(['id' => $videoInfo['video_id']]);
        if (false === $deleteRes) {
            $result['msg'] = '删除失败';
            return $result;
        }

        $result['res'] = true;
        return $result;
    }

    public function getVideoInfoHandle($userInfo, $videoId) {
        $result = [
            'res' => false,
            'msg' => '获取成功',
            'data' => [],
        ];

        if ($videoId <= 0) {
            $result['msg'] = '视频id异常';
            return $result;
        }

        $videoModel = new Video();
        $videoInfo = $videoModel->findDataWithField(['id' => $videoId], ['id', 'title', 'url', 'attribute', 'content as content_id']);
        if (empty($videoInfo)) {
            $result['msg'] = '视频不存在';
            return $result;
        }
        $videoInfo['attribute'] = json_decode($videoInfo['attribute'], true);

        // 获取课程的名称
        $courseInfo = (new Course())->findDataWithField(['id' => $videoInfo['content_id']], ['name']);
        $videoInfo['content_name'] = $courseInfo['name'] ?? '';

        $result['res'] = true;
        $result['data'] = $videoInfo;
        return $result;
    }

    public function updateVideoHandle($userInfo, $videoInfo) {
        $result = [
            'res' => false,
            'msg' => '更新成功',
            'data' => [],
        ];

        if (!isset($videoInfo['video_id']) || !is_numeric($videoInfo['video_id']) || $videoInfo['video_id'] <= 0) {
            $result['msg'] = '视频id异常';
            return $result;
        }
        $videoInfo['video_id'] = intval($videoInfo['video_id']);

        $videoModel = new Video();
        $videoExistedInfo = $videoModel->findDataWithField(['id' => $videoInfo['video_id']], ['id']);
        if (empty($videoExistedInfo)) {
            $result['msg'] = '视频不存在';
            return $result;
        }

        // 需要更新的字段
        $updateData = [];

        if (isset($videoInfo['title'])) {
            if (mb_strlen($videoInfo['title']) == 0 || mb_strlen($videoInfo['title']) > 32) {
                $result['msg'] = '标题异常';
                return $result;
            }

            $updateData['title'] = $videoInfo['title'];
        }

        if (isset($videoInfo['url'])) {
            if (mb_strlen($videoInfo['url']) == 0 || mb_strlen($videoInfo['url']) > 256) {
                $result['msg'] = '视频链接异常';
                return $result;
            }

            $updateData['url'] = $videoInfo['url'];
        }

        if (!empty($videoInfo['attribute'])) {
            if (!isValidJson($videoInfo['attribute'])) {
                $result['msg'] = '视频属性异常';
                return $result;
            }

            $updateData['attribute'] = json_encode($videoInfo['attribute'], JSON_UNESCAPED_UNICODE);
        }

        if (isset($videoInfo['content_id'])) {
            if (!is_numeric($videoInfo['content_id']) || $videoInfo['content_id'] <= 0) {
                $result['msg'] = '课程异常';
                return $result;
            }

            $updateData['content'] = intval($videoInfo['content_id']);

            // 判断课程是否存在
            $existedCourseInfo = (new Course())->findDataWithField(['id' => $updateData['content']], ['id']);
            if (empty($existedCourseInfo)) {
                $result['msg'] = '课程不存在';
                return $result;
            }
        }

        if (!empty($updateData)) {
            $updateRes = $videoModel->updateData(['id' => $videoExistedInfo['id']], $updateData);
            if (false === $updateRes) {
                $result['msg'] = '更新失败';
                return $result;
            }
        }

        $result['res'] = true;
        return $result;
    }

    public function updateVideoStatusHandle($userInfo, $videoInfo) {
        $result = [
            'res' => false,
            'msg' => '更新成功',
            'data' => [],
        ];

        if (!isset($videoInfo['video_id']) || !is_numeric($videoInfo['video_id']) || $videoInfo['video_id'] <= 0) {
            $result['msg'] = '视频id异常';
            return $result;
        }
        $videoInfo['video_id'] = intval($videoInfo['video_id']);

        if (!isset($videoInfo['status']) || !is_numeric($videoInfo['status']) || ($videoInfo['status'] != 1 && $videoInfo['status'] != 2)) {
            $result['msg'] = '视频status异常';
            return $result;
        }
        $videoInfo['status'] = intval($videoInfo['status']);

        $videoModel = new Video();
        $videoExistedInfo = $videoModel->findDataWithField(['id' => $videoInfo['video_id']], ['id']);
        if (empty($videoExistedInfo)) {
            $result['msg'] = '视频不存在';
            return $result;
        }

        $deleteRes = $videoModel->updateData(['id' => $videoInfo['video_id']], ['status' => $videoInfo['status']]);
        if (false === $deleteRes) {
            $result['msg'] = '更新失败';
            return $result;
        }

        $result['res'] = true;
        return $result;
    }

}
