<?php

namespace App\Console\Commands;

use App\Modules\Book\Models\BookSearchStat;
use App\Modules\Statistic\Services\SendStatsEmailService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;

class BookSearchInfoStat extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'book_search_stat';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '用户搜索图书记录信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $end_time = date("Y-m-d", strtotime("-1 day"));
        $begin_time = date("Y-m-d", strtotime("-8 day"));
        $type = 'WECHAT';
        $wechat_search_result = BookSearchStat::getInfo(compact('begin_time', 'end_time', 'type'), true);

        $type = 'WAP';
        $wap_search_result = BookSearchStat::getInfo(compact('begin_time', 'end_time', 'type'), true);

        $this->sendResultEmail($wechat_search_result, $wap_search_result, $begin_time, $end_time);
    }

    public function sendResultEmail($wechat_search_result, $wap_search_result, $start_date, $end_date)
    {
        if ($wechat_search_result && count($wechat_search_result) > 0) {
            $filename = '微信内搜索.' . 'csv';
            Storage::append($filename, mb_convert_encoding("关键词,搜索人数,搜索次数", 'gbk'));
            $str = '';
            foreach ($wechat_search_result as $item) {
                $str .= "$item->content,$item->user_num,$item->search_num\r\n";
            }
            Storage::append($filename, mb_convert_encoding($str, 'gbk'));
        }

        if ($wap_search_result && count($wap_search_result) > 0) {
            $filename = 'wap内搜索.' . 'csv';
            Storage::append($filename, mb_convert_encoding("关键词,搜索人数,搜索次数", 'gbk'));
            $str = '';
            foreach ($wap_search_result as $item) {
                $str .= "$item->content,$item->user_num,$item->search_num\r\n";
            }
            Storage::append($filename, mb_convert_encoding($str, 'gbk'));
        }

        $to_user = array(
            ['address'=>'songdb@iqiyoo.com','name'=>'songdb'],
            ['address'=>'zhaojp@yqsd.net','name'=>'赵君平'],
            ['address' => 'zhoulj@iqiyoo.com', 'name' => '周灵杰']
        );

        $file_path1 = storage_path('app/微信内搜索.csv');
        $file_path2 = storage_path('app/wap内搜索.csv');
        $attach = [$file_path1, $file_path2];
        $body = '搜索关键字统计，详情请见附件';
        SendStatsEmailService::SendMultyHtmlEmailWithAcce($to_user, ['subject' => $start_date . '至' . $end_date . " 搜索关键字统计", 'body' => $body], $attach);

        unlink($file_path1);
        unlink($file_path2);
    }
}
