<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2017/11/20
 * Time: 下午5:26
 */

namespace App\Console\Commands;

use App\Modules\Statistic\Services\SendStatsEmailService;
use DB;
use GuzzleHttp\Client;
use Illuminate\Console\Command;
use Log;

class CheckSiteStatus extends Command
{
    /**
     * 执行命令 检查站点信息
     *
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'check_site_status';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '检查掌中云站点信息';

    public $table_name = 'novel_platform_sites';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        Log::info('CheckSiteStatus start command');
        $this->loadSiteIndexInfo();
        //$this->loadCompanyName();
        Log::info('CheckSiteStatus end command');
    }

    function loadCompanyName()
    {
        $pageCount = 0;
        $pageSize = 1000;
        $client = new Client(['timeout' => 3.0,]);
        $totalCount = DB::table($this->table_name)->max('site');
        $totalPageCount = ceil($totalCount / $pageSize);
        while ($pageCount < $totalPageCount) {
            $beginIndex = $pageCount * $pageSize;
            $data = DB::table($this->table_name)->offset($beginIndex)->limit($pageSize)->get();
            if ($data) {
                foreach ($data as $item) {
                    $gzh_name = trim($item->gzh_name);
                    $companyInfo = $this->getCompanyInfo($client, $gzh_name);
                    $companyInfo['updated_at'] = date("Y-m-d H:i:s");
                    DB::table($this->table_name)->where('id', $item->id)->update($companyInfo);
                    sleep(1);
                }
            }
            $pageCount++;
        }
    }

    function loadSiteIndexInfo()
    {
        $trueSiteArray = [];
        $client = new Client(['timeout' => 3.0,]);
        $lastIndex = DB::table('novel_platform_sites')->max('site');
        $index = $lastIndex + 1;
        while ($index <= $lastIndex + 1000) {
            Log::info('check_site_status index is: ' . $index);
            $siteUrl = 'https://c' . $index . '.818tu.com/spa/config?tdsourcetag=s_pcqq_aiomsg';
            Log::info('check_site_status siteUrl is: ' . $siteUrl);
            try {
                $response = $client->request('get', $siteUrl);
                $resultCode = $response->getStatusCode();
                //成功
                if ($resultCode == 200 || $resultCode == 302) {
                    $content = $response->getBody()->getContents();
                    //Log::info('content is :' . $content);
                    if ($content) {
                        $findStr = "mp:";
                        $findBegin = strpos($content, $findStr);
                        if ($findBegin) {
                            $findBegin = $findBegin + strlen($findStr);
                            $findEnd = strpos($content, '},', $findBegin);
                            if ($findEnd) {
                                $content = substr($content, $findBegin, $findEnd - $findBegin + 1);
                                Log::info('content is :' . $content);
                                $content = json_decode($content);
                                $gzh_name = trim($content->raw_id);
                                $companyInfo = $this->getCompanyInfo($client, $gzh_name);
                                $params = [
                                    'site' => $index,
                                    'gzh_name' => $gzh_name,
                                    'platform_name' => '掌中云',
                                    'appid' => $content->app_id,
                                    'nickname' => $content->nickname,
                                    'qrcode' => $companyInfo['qrcode'],
                                    'company' => $companyInfo['company'],
                                    'created_at' => date("Y-m-d H:i:s"),
                                    'updated_at' => date("Y-m-d H:i:s"),
                                    'fans_num_estimate' => $companyInfo['fans_num_estimate']
                                ];
                                $trueSiteArray[] = $params;
                                DB::table('novel_platform_sites')->insert($params);
                            }
                        }
                    } else {
                        Log::info('content is :' . $content);
                    }
                } else {
                    Log::info('CheckSiteStatus load error resultCode is:' . $resultCode);
                }
            } catch (\Exception $e) {
                Log::info('CheckSiteStatus load error');
                Log::info($e->getMessage());
            }
            $index++;
        }

        if ($trueSiteArray) {
            Log::info('CheckSiteStatus need sendEmail');
            $this->sendEmail($trueSiteArray);
        } else {
            Log::info('CheckSiteStatus not need sendEmail');
        }
    }

    function getCompanyInfo($client, $gzh_name)
    {
        $qrcode = '';
        $company = '';
        $fans_num_estimate = '';
        $time_stamp = time();
        $sign_params = 'app_id=364c32166857f0131a0ac35396d6c0&kw=' . $gzh_name . '&page=1&timestamp=' . $time_stamp;
        $sign = md5($sign_params . 'sjadf92jf9vh@827*sjfo09n30');
        $url = 'https://api.wxb.com/data/search?' . $sign_params . '&sign=' . $sign;
        try {
            $response = $client->request('get', $url);
        } catch (\Exception $e) {
            Log::info($e->getMessage());
            return compact('qrcode', 'company', 'fans_num_estimate');
        }

        $resultCode = $response->getStatusCode();
        if ($resultCode == 200 || $resultCode == 302) {
            $content = $response->getBody()->getContents();
            $content = json_decode($content);
            $content = $content->data;
            if (is_array($content) && count($content) > 0) {
                $content = $content[0];
                $qrcode = $content->qrcode;
                $company = $content->company;
                $fans_num_estimate = $content->fans_num_estimate;
            }
        }
        return compact('qrcode', 'company', 'fans_num_estimate');
    }

    function sendEmail($trueSiteArray)
    {
        Log::info('CheckSiteStatus start sendEmail');
        $to_user = array(
            ['address' => 'zhangzg@iqiyoo.com', 'name' => '张总'],
            ['address' => 'songdb@iqiyoo.com', 'name' => 'songdb'],
            ['address' => 'zhaojp@yqsd.net', 'name' => '赵君平'],
            ['address' => 'sijj@yqsd.net', 'name' => 'sijj'],
            ['address' => 'qincp@iqiyoo.com', 'name' => '阿才'],
        );

        $content = "<table border='1' cellpadding='10' cellspacing='0'><tr><td align='center'>序号</td><td align='center'>站点id</td><td align='center'>公众号名称</td><td align='center'>主体公司名称</td></tr>";
        $index = 0;
        foreach ($trueSiteArray as $item) {
            $index++;
            $content .= "<tr><td align='center'>{$index}</td><td align='center'>{$item['site']}</td><td align='center'>{$item['nickname']}</td><td align='center'>{$item['company']}</td></tr>";
        }
        $content .= "</table>";
        SendStatsEmailService::SendHtmlEmailWithAcce($to_user, ['subject' => date("Y-m-d", time()) . "掌中云昨天新增站点" . $index . "个", 'body' => $content]);
    }
}
