<?php

declare(strict_types=1);

namespace app\admin\controller\v1;

use app\admin\model\v1\VideoModel;
use app\admin\validate\v1\VideoValidate;
use think\facade\Config;

/**
 * 视频管理控制器
 */
class Video
{
    /**
     * 视频信息分页数据
     */
    public function index()
    {
        $params = request()->param([
            'name',
            'category_id',
            'created_at',
            'page/d' => 1,
            'size/d' => 10
        ]);

        $videos = VideoModel::field([
                'id',
                'image',
                'name',
                'category_id',
                'sort',
                'recommend',
                'created_at'
            ])
            ->with(['category' => function ($query) {
                $query->field(['id', 'name' => 'category_name']);
            }])
            ->withSearch(['name', 'created_at'], [
                'name'       => $params['name'] ?? null,
                'created_at' => !empty($params['created_at']) ? explode(",", $params['created_at']) : null
            ])
            ->language(request()->lang_id)
            ->categoryId($params['category_id'] ?? null)
            ->order(['sort' => 'desc', 'id' => 'desc'])
            ->paginate([
                'list_rows' => $params['size'],
                'page'      => $params['page'],
            ])
            ->bindAttr('category', ['category_name'])
            ->hidden(['category', 'category_id'])
            ?->each(fn($item) => $item->image = thumb($item->image));

        return success('获取成功', $videos);
    }

    /**
     * 视频信息详情
     */
    public function read()
    {
        $video = VideoModel::with(['category' => function($query) {
                $query->field(['id', 'name' => 'category_name']);
            }])
            ->withoutField([
                'created_at',
                'updated_at',
                'deleted_at'
            ])
            ->bypk(request()->param('id'))
            ->find()
            ->bindAttr('category', ['category_name'])
            ->hidden(['category']);
        if (empty($video)) {
            return error('视频不存在');
        }

        return success('获取成功', $video);
    }

    /**
     * 添加视频信息
     */
    public function save()
    {
        $post = request()->post([
            'name',
            'category_id',
            'sort',
            'recommend',
            'desc',
            'image',
            'video',
            'link',
            'seo_title',
            'seo_keywords',
            'seo_desc'
        ]);
        $data = array_merge($post, ['language_id' => request()->lang_id]);

        $validate = new VideoValidate;
        if (!$validate->scene('create')->check($data)) {
            return error($validate->getError());
        }

        $video = VideoModel::create($data);
        if ($video->isEmpty()) {
            return error('操作失败');
        }

        return success('操作成功');
    }

    /**
     * 更新视频信息
     */
    public function update()
    {
        $id  = request()->param('id');
        $put = request()->put([
            'name',
            'category_id',
            'sort',
            'recommend',
            'desc',
            'image',
            'video',
            'link',
            'seo_title',
            'seo_keywords',
            'seo_desc'
        ]);

        $validate = new VideoValidate;
        if (!$validate->scene('update')->check(array_merge($put, ['id' => $id]))) {
            return error($validate->getError());
        }

        $video = VideoModel::bypk($id)->find();
        if (empty($video)) {
            return error('请确认操作对象是不是存在');
        }

        if (!$video->save($put)) {
            return error('操作失败');
        }
        return success('操作成功');
    }

    /**
     * 设置排序值
     */
    public function sort()
    {
        $id   = request()->param('id');
        $sort = request()->post('sort');

        $validate = new VideoValidate;
        if (!$validate->scene('sort')->check(['id' => $id, 'sort' => $sort])) {
            return error($validate->getError());
        }

        $video = VideoModel::bypk($id)->find();
        if (empty($video)) {
            return error('请确认操作对象是不是存在');
        }

        $video->sort = $sort;
        if (!$video->save()) {
            return error('操作失败');
        }
        return success('操作成功');
    }

    /**
     * 导出接口
     */
    public function export()
    {
        $schema = [
            'category_name' => '分类',
            'name'          => '视频名称',
            'desc'          => '描述',
            'image'         => '封面图片',
            'video'         => '视频URL',
            'link'          => '外链',
            'sort'          => '排序',
            'recommend'     => '是否推荐',
            'seo_title'     => 'seo标题',
            'seo_keywords'  => 'seo关键词',
            'seo_desc'      => 'seo描述',
            'created_at'    => '创建时间'
        ];

        // 获取导出数据
        $data = $this->getExportVideoData();

        // 导出
        return xlsx_writer($data, $schema, '视频列表' . date('YmdHis'));
    }
    private function getExportVideoData()
    {
        $params = request()->param([
            'name',
            'category_id',
            'created_at'
        ]);

        $domain     = request()->domain();
        return  VideoModel::withoutField([
                'language_id',
                'updated_at',
                'deleted_at'
            ])
            ->with(['category' => function ($query) {
                $query->field(['id', 'name']);
            }])
            ->withSearch(['name', 'created_at'], [
                'name'       => $params['name']??null,
                'created_at' => !empty($params['created_at']) ? explode(',', $params['created_at']) : null,
            ])
            ->language(request()->lang_id)
            ->categoryId($params['category_id']??null)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->select()
            ->bindAttr('category', ['category_name' => 'name'])
            ->hidden(['category_id', 'category'])
            ->each(function ($item) use($domain) {
                $item->image     = !empty($item->image) ? url_join($domain, $item->image) : '';
                $item->video     = !empty($item->video) ? url_join($domain, $item->video) : '';
                $item->recommend = $item->recommend == 1 ? '是' : '否';
                $item->status    = $item->status    == 1 ? '启用' : '禁用';
                return $item;
            });
    }

    /**
     * 视频信息删除
     */
    public function delete()
    {
        $id = request()->param('id');
        $video = VideoModel::bypk($id)->find();
        if (empty($video)) {
            return error('请确认操作对象是不存在');
        }

        if (!$video->delete()) {
            return error('操作失败');
        }
        return success('操作成功');
    }
}
