<?php
declare(strict_types=1);

namespace app\admin\controller\v1;

use app\admin\model\v1\SysMallStoreEntranceModel;
use app\admin\validate\v1\SysMallStoreEntranceValidate;

/**
 * 系统商城店铺入口管理控制器
 */
class SysMallStoreEntrance
{
    /**
     * 分页列表
     */
    public function index()
    {
        $param = request()->get([
            'name',
            'page/d' => 1,
            'size/d' => 10
        ]);

        // 查询数据
        $data = SysMallStoreEntranceModel::withoutField([
                'language_id',
                'hover_image',
                'updated_at',
                'deleted_at'
            ])
            ->withSearch(['name'], ['name' => $param['name']??null])
            ->language(request()->lang_id)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->paginate([
                'list_rows' => $param['size'],
                'page'      => $param['page'],
            ])
            ?->each(function($item) {
                // 列表页面图片输出缩略图
                if (!empty($item['image'])) {
                    $item['image'] = thumb($item['image']);
                }
            });

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

    /**
     * 获取详情
     */
    public function read()
    {
        $id     = request()->param('id/d');
        $record = SysMallStoreEntranceModel::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([
            'name',
            'image',
            'hover_image',
            'link',
            'sort',
            'disabled'
        ]);
        $data = array_merge($post, ['language_id' => request()->lang_id]);

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

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

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

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

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

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

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

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

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

    /**
     * 导出Excel
     */
    public function export()
    {
        $schema = [
            'id'           => 'ID',
            'image'        => '图片',
            'hover_image'  => '悬浮图',
            'name'         => '名称',
            'link'         => '链接地址',
            'sort'         => '排序',
            'disabled'     => '状态',
            'created_at'   => '添加时间'
        ];

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

        // 导出
        return xlsx_writer($data, $schema, '系统商城店铺入口列表' . date('YmdHis'));
    }

    // 获取要导出的数据
    private function getExportData()
    {
        $server     = request()->server();
        $image_host = $server['REQUEST_SCHEME'] . "://" . $server['SERVER_NAME'] . '/';
        $param      = request()->get(['name']);

        // 查询数据
        return SysMallStoreEntranceModel::withoutField([
                'language_id',
                'updated_at',
                'deleted_at'
            ])
            ->withSearch(['name'], ['name' => $param['name']??null])
            ->language(request()->lang_id)
            ->order(['sort' => 'asc', 'id' => 'desc'])
            ->select()
            ?->each(function($item) use($image_host) {
                // 拼接完整图片URL
                if (!empty($item['image'])) {
                    $item['image'] = url_join($image_host, $item['image']);
                }
                if (!empty($item['hover_image'])) {
                    $item['hover_image'] = url_join($image_host, $item['hover_image']);
                }
                // 状态转换
                $item['disabled'] = $item['disabled'] == 1 ? '禁用' : '启用';
            })
            ->toArray();
    }
}
