<?php
declare (strict_types = 1);

namespace app\admin\controller\v1;

use app\admin\model\v1\LeaveMessageModel;

/**
 * 留言记录（联系我们）控制器
 */
class LeaveMessage
{
    // 分页
    public function index()
    {
        $param = request()->param([
            'created_at',
            'page/d' => 1,
            'size/d' => 10
        ]);

        $msgs = LeaveMessageModel::withoutField([
                'language_id',
                'user_agent'
            ])
            ->withSearch(['created_at'], [
                'created_at' => !empty($param['created_at']) ? explode(',', $param['created_at']) : null
            ])
            ->language(request()->lang_id)
            ->order(['id' => 'desc'])
            ->paginate([
                'list_rows' => $param['size'],
                'page'      => $param['page']
            ]);

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

    // 导出
    public function export()
    {
        $schema = [
            'created_at' => '提交时间',
            'id'         => 'ID',
            'name'       => '姓名',
            'email'      => '邮箱',
            'ip'         => 'IP',
            'content'    => '留言内容'
        ];

        // 获取留言导出数据
        $msgs = $this->getLeaveMessageExportData();

        // 导出
        return xlsx_writer($msgs, $schema, '联系我们列表' . date('YmdHis'));
    }
    // 获取留言导出数据
    private function getLeaveMessageExportData()
    {
        $param = request()->param([
            'created_at'
        ]);

        return LeaveMessageModel::withoutField([
                'language_id',
                'user_agent'
            ])
            ->withSearch(['created_at'], [
                'created_at' => !empty($param['created_at']) ? explode(',', $param['created_at']) : null
            ])
            ->language(request()->lang_id)
            ->order(['id' => 'desc'])
            ->select();
    }
}
