<?php
namespace app\controller\manager;

use app\model\{Message as MMessage, Log};
use app\service\Tool;
use app\service\File;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;

class Message extends Base
{
    protected $excelStyle = [
        'font'      => [
            'name' => '宋体',
        ],
        'alignment' => [
            'horizontal' => Alignment::HORIZONTAL_CENTER,  // 水平居中
            'vertical'   => Alignment::VERTICAL_CENTER,  // 垂直居中
            'wrapText'   => true,
        ],
        'borders'   => [
            'allBorders' => [
                'borderStyle' => Border::BORDER_THIN,
                'color'       => ['rgb' => 'eeeeee'],
            ]
        ],
    ];

    protected $defaultSetting = [
        'cell_width'    => 30,
        'font_size'     => 12
    ];

    //下载文件
    public function file()
    {
        $id = input('param.id/d');
        if(is_numeric($id) && $id > 0) {
            $item = MMessage::getById($id);
            if(empty($item)){
                return $this->error('留言不存在');
            }
            if(empty($item['file'])){
                return $this->error('无文件需要下载');
            }
            $file = app()->getRootPath() . 'public' . $item['file'];
            if(!file_exists($file)){
                return $this->error('无文件需要下载');
            }
            $fileInfo = pathinfo($file);
            $fileName = $item['name'] . '上传文件.' . $fileInfo['extension'];
            $fileSize = filesize($file);

            //以只读和二进制模式打开文件   
            $file = fopen ( $file, "rb" ); 

            //告诉浏览器这是一个文件流格式的文件    
            Header ( "Content-type: application/octet-stream" );
            //请求范围的度量单位  
            Header ( "Accept-Ranges: bytes" );
            //Content-Length是指定包含于请求或响应中数据的字节长度    
            Header ( "Accept-Length: " . $fileSize );
            //用来告诉浏览器，文件是可以当做附件被下载，下载后的文件名称为$file_name该变量的值。
            Header ( "Content-Disposition: attachment; filename=" . $fileName );

            //读取文件内容并直接输出到浏览器    
            echo fread ( $file, $fileSize );
            fclose ( $file );
            exit ();
        }
        return $this->error('参数错误,请核对之后再操作!');
    }
    //可以删除一个
    public function del()
    {
        if ($this->request->isPost()) {
            $id = input('post.id/d');
            if(is_numeric($id) && $id > 0) {
                $item = MMessage::getById($id);
                if(!empty($item)){
                    MMessage::destroy($id);
                    if(!empty($item['file'])){
                        Tool::delFile($item['file']);
                    }
                    Log::write('link', 'del', '删除留言，ID：' . $id . '，姓名：' . $item['name']);
                    return $this->json();
                }
                return $this->json(3, '待删除留言不存在');
            }
            return $this->json(2, '参数错误,请核对之后再操作!');
        }
        return $this->json(1, '非法请求!');
    }

    //列表
    public function index()
    {
        $startDate  = input('param.startDate', '');
        $endDate    = input('param.endDate', '');

        $items = MMessage::getList(20, $startDate, $endDate);
        $this->data['items']        = $items;
        $this->data['startDate']    = $startDate;
        $this->data['endDate']      = $endDate;
        return $this->view();
    }

    // 导出留言
    public function export()
    {
        File::cancelTimeLimit();

        $startDate  = input('param.startDate', '');
        $endDate    = input('param.endDate', '');
        $list = MMessage::getExportList($startDate, $endDate, 10000);

        $spreadsheet    = new Spreadsheet();
        $header         = ['序号', '姓名', '电话', '公司/团队名称', '申请日期'];

        $sheet = $spreadsheet->getActiveSheet();
        $sheetTitle = '预约记录';
        $cellValues = [];
        $cellWidthList = [];

        foreach ($list as $item) {
            $cellValues[] = [
                [$item['id'], DataType::TYPE_STRING],
                $item['name'],
                $item['tel'],
                $item['company'],
                date('Y-m-d H:i', $item['create_time']),
            ];
        }

        File::setExcelCells($sheet, $cellValues, $header, $sheetTitle, $cellWidthList, $this->excelStyle, $this->defaultSetting);
        File::export($spreadsheet, '预约记录导出_' . date('YmdHis') . '.xlsx');
    }

}
