<?php

namespace app\controller\manager;

use app\model\{Message as MMessage, Log, VisitLogoModel};
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;
use think\response\View;

class VisitLog 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 del()
    {
        if ($this->request->isPost()) {
            $id = input('post.id/d');
            if (is_numeric($id) && $id > 0) {
                $item = VisitLogoModel::getById($id);
                if (!empty($item)) {
                    VisitLogoModel::destroy($id);
                    if (!empty($item['file'])) {
                        Tool::delFile($item['file']);
                    }
                    Log::write('visit_log', 'del', '删除访问记录，ID：'.$id);
                    return $this->json();
                }
                return $this->json(3, '待删除记录不存在');
            }
            return $this->json(2, '参数错误,请核对之后再操作!');
        }
        return $this->json(1, '非法请求!');
    }

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

        $param = [];
        if (!empty($startDate)) {
            $param['startDate'] = $startDate;
        }
        if (!empty($endDate)) {
            $param['endDate'] = $endDate;
        }

        if (!empty($keyword)) {
            $param['keyword'] = $keyword;
        }

        $paginate = [
            'list_rows' => 20,
            'query'     => $param
        ];

        $items = VisitLogoModel::when(!empty($startDate) && strtotime($startDate), function ($query) use ($startDate) {
            $startTime = strtotime(date('Y-m-d 00:00:00', strtotime($startDate)));
            $query->where('create_time', '>=', $startTime);
        })
            ->when(!empty($endDate) && strtotime($endDate), function ($query) use ($endDate) {
                $endTime = strtotime(date('Y-m-d 23:59:59', strtotime($endDate)));
                $query->where('create_time', '<=', $endTime);
            })
            ->when(!empty($keyword), function ($query) use ($keyword) {
                $query->where('referer|visit', 'like', '%'.$keyword.'%');
            })
            ->order("create_time", 'desc')
            ->paginate($paginate);

        $items->each(function ($item) {
           $item->source_title = '其他';
           if (str_contains($item->referer, 'baidu.com')) {
               $item->source_title = '百度';
           }

            if (str_contains($item->referer, 'so.com')) {
                $item->source_title = '360';
            }
        });

        $this->data['items']     = $items;
        $this->data['startDate'] = $startDate;
        $this->data['endDate']   = $endDate;
        $this->data['keyword']   = $keyword;
        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');
    }

}
