<?php
declare(strict_types=1);

namespace app\admin\controller\v1;

use app\admin\model\v1\ProductCategoryRecommendModel;
use app\admin\validate\v1\ProductCategoryRecommendValidate;

/**
 * 产品分类推荐管理控制器
 */
class ProductCategoryRecommend
{
    /**
     * 分页列表
     */
    public function index()
    {
        $param      = request()->get([
            'keywords',
            'category_name',
            'page/d' => 1,
            'size/d' => 10
        ]);

        // 查询数据
        $data = ProductCategoryRecommendModel::withJoin(['category' => function($query) use ($param) {
                if (!empty($param['category_name'])) {
                    $query->where('category.name', 'like', '%' . $param['category_name'] . '%');
                }
            }])
            ->withSearch(['keywords'], ['keywords' => $param['keywords']??null])
            ->language(request()->lang_id)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->paginate([
                'list_rows' => $param['size'],
                'page'      => $param['page'],
            ])
            ->bindAttr('category', ['category_name' => 'name'])
            ->hidden(['category', 'language_id', 'updated_at', 'deleted_at'])
            ?->each(function($item) {
                // 列表页面图片输出缩略图
                if (!empty($item['image'])) {
                    $item['image'] = thumb($item['image']);
                }
            });

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

    /**
     * 导出Excel
     */
    public function export()
    {
        $schema = [
            'id'            => 'ID',
            'image'         => '图片',
            'category_name' => '分类名称',
            'desc'          => '产品介绍',
            'link'          => '链接地址',
            'sort'          => '排序',
            'disabled'      => '状态',
            'created_at'    => '添加时间'
        ];

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

        // 导出
        return xlsx_writer($data, $schema, '产品推荐列表' . date('YmdHis'));
    }
    // 获取要导出的推荐记录数据
    private function getProductCategoryRecommendData()
    {
        $server     = request()->server();
        $image_host = $server['REQUEST_SCHEME'] . "://" . $server['SERVER_NAME'] . '/';
        $param      = request()->get(['keywords']);

        // 查询数据
        return ProductCategoryRecommendModel::withJoin(['category' => function($query) use ($param) {
                if (!empty($param['category_name'])) {
                    $query->where('category.name', 'like', '%' . $param['category_name'] . '%');
                }
            }])
            ->withSearch(['keywords'], ['keywords' => $param['keywords']??null])
            ->language(request()->lang_id)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->select()
            ->bindAttr('category', ['category_name' => 'name'])
            ->hidden(['category', 'language_id', 'updated_at', 'deleted_at'])
            ?->each(function($item) use($image_host) {
                // 拼接完整图片URL
                if (!empty($item['image'])) {
                    $item['image'] = url_join($image_host, $item['image']);
                }
                // 状态
                $item['disabled'] = $item['disabled'] == 1 ? '禁用' : '启用';
            })
            ->toArray();
    }

    /**
     * 获取详细数据
     */
    public function read()
    {
        $id = request()->param('id/d');
        $record = ProductCategoryRecommendModel::bypk($id)
            ->withoutField(['language_id', 'created_at', 'updated_at', 'deleted_at'])
            ->find();
        if (empty($record)) {
            return error('推荐数据不存在');
        }

        return success('success', $record);
    }

    /**
     * 新增数据
     */
    public function save()
    {
        $post = request()->post([
            'category_id',
            'title',
            'image',
            'desc',
            'link',
            'sort',
            'disabled'
        ]);
        $data = array_merge($post, ['language_id' => request()->lang_id]);

        // 参数校验
        $validate   = new ProductCategoryRecommendValidate();
        if (!$validate->scene('create')->check($data)) {
            return error($validate->getError());
        }

        // 保存推荐数据
        $recommend = ProductCategoryRecommendModel::create($data);
        if ($recommend->isEmpty()) {
            return error('保存失败');
        }
        return success('保存成功');
    }

    /**
    * 更新数据
    */
    public function update()
    {
        $id = request()->param('id/d');
        $post = request()->post([
            'category_id',
            'title',
            'image',
            'desc',
            'link',
            'sort',
            'disabled'
        ]);
        $data = array_merge($post, ['language_id' => request()->lang_id]);

        // 参数校验
        $validate   = new ProductCategoryRecommendValidate();
        $check_data = array_merge($data, ['id' => $id]);
        if (!$validate->scene('update')->check($check_data)) {
            return error($validate->getError());
        }

        // 更新推荐数据
        $recommend = ProductCategoryRecommendModel::bypk($id)->find();
        if (empty($recommend)) {
            return error('请确认操作对象是否存在');
        }
        if (!$recommend->save($data)) {
            return error('操作失败');
        }

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

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

        // 删除推荐记录数据
        $record = ProductCategoryRecommendModel::bypk($id)->find();
        if (empty($record)) {
            return error('请确认操作对象是否正确');
        }
        if (!$record->delete()) {
            return error('操作失败');
        }

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