<?php
declare (strict_types = 1);

namespace app\admin\controller\v1;

use app\admin\model\v1\SysBannerModel;
use app\admin\validate\v1\SysBannerValidate;

/**
 * 横幅（分类）模型
 */
class Banner
{
    // 列表
    public function list()
    {
        $param = request()->param([
            'name'
        ]);

        $banners = SysBannerModel::field([
                'id',
                'name',
                'at_platform'
            ])
            ->withSearch(['name'], [
                'name' => $param['name'] ?? null
            ])
            ->language(request()->lang_id)
            ->enabled()
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->select();

        $datas = [];
        if (!$banners->isEmpty()) {
            $temp = [];
            $map  = ['pc' => ['id' => -1, 'name' => 'PC端'], 'mobile' => ['id' => -2, 'name' => '移动端']];
            foreach ($banners as $banner) {
                if (!isset($temp[$banner->at_platform])) {
                    $temp[$banner->at_platform] = [
                        'id'       => $map[$banner->at_platform]['id'] ?? 0,
                        'name'     => $map[$banner->at_platform]['name'] ?? '未知平台',
                        'children' => []
                    ];
                }
                $temp[$banner->at_platform]['children'][] = [
                    'id'   => $banner->id,
                    'name' => $banner->name
                ];
            }
            $datas = array_values($temp);
        }

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

    // 分页
    public function index()
    {
        $param = request()->param([
            'name',
            'page/d' => 1,
            'size/d' => 10
        ]);

        $banners = SysBannerModel::field([
                'id',
                'name',
                'recommend',
                'at_platform',
                'desc',
                'created_at'
            ])
            ->withSearch(['name'], [
                'name' => $param['name'] ?? null
            ])
            ->language(request()->lang_id)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->paginate([
                'list_rows' => $param['size'],
                'page'      => $param['page']
            ]);

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

    // 详情
    public function read()
    {
        $id = request()->param('id');

        $banner = SysBannerModel::withoutField([
                'at_page',
                'language_id',
                'created_at',
                'updated_at',
                'deleted_at'
            ])
            ->bypk($id)
            ->find();
        if (empty($banner)) {
            return error('横幅（分类）不存在');
        }

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

    // 新增
    public function save()
    {
        $post = request()->post([
            'name',
            'desc',
            'recommend',
            'unique_label',
            'at_platform'  => 'pc',
            'status'       => 1
        ]);
        $data = array_merge($post, [
            'language_id'  => request()->lang_id,
            'unique_label' => $post['unique_label'] ?? uniqid('BANNER_')
        ]);

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

        $banner = SysBannerModel::create($data);
        if ($banner->isEmpty()) {
            return error('操作失败');
        }
        return success('操作成功');
    }

    // 修改
    public function update()
    {
        $id  = request()->param('id');
        $put = request()->put([
            'name',
            'desc',
            'recommend',
            'unique_label',
            'at_platform'  => 'pc',
            'status'       => 1
        ]);

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

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

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

    // 删除
    public function delete()
    {
        $id = request()->param('id');

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

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