<?php

namespace App\Http\Controllers\API\Internal;

use App\Http\Controllers\Controller;
use App\Services\ReportService;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class SiXinPushController extends Controller
{
  public static $request;

  public function PushInfo(Request $request)
  {

    $key = $request->query('key');
    $code = $request->query('code');//推送类型 "UpdateInfo".套餐、项目、分组 信息变更 "report".报告推送 "pdf".推送pdf
    $content = $request->post();
    $codeMark = [
      'updateInfo' => '套餐项目分组',
      'report' => '报告',
      'pdf' => 'pdf文件'
    ];
    if (!array_key_exists($code, $codeMark)) return \Yz::echoError1("code不正确");
    if (isset($key) && $key == "xFgq6WzWFNYL6QwKKLtxqYn2NfQnNu3a") {
      self::RequestLog('', $content, $code, $codeMark[$code]);
      //如果推送的是报告
      if ($code == 'report') {
        $report = new ReportService();
        return $report->Save($content);
      }
      //如果推送的是套餐、项目、分组
      if ($code == 'updateInfo') {

      }
      return \Yz::Return(true, "接收完成", $code);
    } else {
      return \Yz::echoError1("密钥错误");
    }
  }

  public static function RequestLog($url, $post_data, $code, $mark)
  {
    self::CheckTableName();

    $post_data = json_encode($post_data, JSON_UNESCAPED_UNICODE);
    self::$request->code = $code;
    self::$request->mark = $mark;
    self::$request->post_data = $post_data == '[]' ? '{}' : $post_data;
    self::$request->request_url = $url;
    self::$request->save();
  }

  public static function CheckTableName()
  {
    $table_name = 'zz_sixin_push_log_' . date('ym');
    $table_count = DB::select('select count(1) as c from information_schema.TABLES where table_schema = ? and table_name = ?', [env('DB_DATABASE'), $table_name])[0];
    if ($table_count->c === 0) {
      Schema::create($table_name, function (Blueprint $table) {
        $table->id();
        $table->string('code', 50)->index();
        $table->string('mark', 50)->index();
        $table->longText('post_data');
        $table->text('response_data')->nullable();
        $table->string('request_url', 300);
        $table->timestamps();
      });
    }
    self::$request = new \App\Models\PEISLog();
    self::$request->setTable($table_name);
  }
}
