<?php

namespace App\Api\Controllers;

use App\Facades\PingAn\Log as LogFacade;
use App\Models\User;
use Illuminate\Http\Request;
use Response;
use Symfony\Component\HttpFoundation\Response as FoundationResponse;
use XuanChen\Coupon\Traits\Log as LogTraits;

trait ApiResponse
{

    use LogTraits;

    /**
     * [$statusCode description]
     * @var [type]
     */
    protected $statusCode = FoundationResponse::HTTP_OK;

    protected $user;

    /**
     * 加密
     * @param <type> $value
     * @return <type>
     */
    public function keyasc($value)
    {
        $iv  = substr($this->user->des3key, 0, 8);
        $ret = openssl_encrypt($value, 'DES-EDE3-CBC', $this->user->des3key, 0, $iv);
        if (false === $ret) {
            return openssl_error_string();
        }

        return $ret;
    }

    /**
     * 解密
     * @param <type> $value
     * @return <type>
     */
    public function keydesc($value)
    {
        $iv  = substr($this->user->des3key, 0, 8);
        $ret = openssl_decrypt($value, 'DES-EDE3-CBC', $this->user->des3key, 0, $iv);
        if (false === $ret) {
            return openssl_error_string();
        }

        return $ret;
    }

    public function checkSign(Request $request)
    {
        $server_id = $request->server_id ?? false;
        $key       = $request->key ?? false;
        $data      = $request->data ?? false;
        $addcode   = $request->addcode ?? false;
        $sign      = $request->sign ?? false;
        if (!$server_id) {
            return '参数server_id不能为空';
        }

        if (!$key) {
            return '参数key不能为空';
        }

        $this->user = User::where('server_id', $server_id)
                          ->where('server_key', $key)->first();

        if (!$this->user) {
            return '参数server_id与key不匹配';
        }

        if ($this->user->status != 1) {
            return '渠道商状态不正确';
        }

        if (!$sign) {
            return '参数sign不能为空';
        }

        if (!$data) {
            return '参数data不能为空';
        }

        if (!$addcode) {
            return '参数addcode不能为空';
        }

        $data      = str_replace('\\', '', $data);
        $data      = str_replace(' ', '+', $data);
        $checksign = $this->keysign($data, $addcode);
        if ($checksign != $sign) {
            return '参数sign不正确';
        }
        $keydesc    = $this->keydesc($data);
        $keydescArr = json_decode($this->keydesc($data), true);
        if (empty($keydescArr) && !empty($keydesc)) {
            return '传递的json数据不对';
        }

        return $keydescArr;
    }

    public function keysign($jsonData = '', $addcode = '')
    {
        $signStr = 'data=' . $jsonData . '&addcode=' . $addcode . '&key=' . $this->user->server_key;
        $sign    = hash_hmac('sha256', $signStr, $this->user->server_key);

        return $sign;
    }

    /**
     * 成功的返回
     * @Author  :<C.Jason>
     * @Date    :2018-05-22
     * @param   [type] $data [description]
     * @param string $log
     * @return  [type] [description]
     */
    public function success($data, $log = '')
    {
        $jsonData = json_encode($data);                    //数据JSON化
        $ascdata  = $this->keyasc($jsonData);              //加密
        $addcode  = sprintf("%08d", mt_rand(0, 99999999)); //随机code 验证签名用
        $sign     = $this->keysign($ascdata, $addcode);
        $data     = [
            'code'    => 1,
            'message' => 'SUCCESS',
            'data'    => $ascdata,
            'addcode' => $addcode,
            'sign'    => $sign,
        ];

        if ($log) {
            if (!is_array($data)) {
                $data = [$data];
            }

            $this->updateLog($log, $data); //更新日志
        }

        return $this->respond(200, $data);
    }

    public function error($message = '', $log = '')
    {
        $data = [
            'code'    => 0,
            'message' => $message,
        ];

        if ($log) {
            $this->updateLog($log, [$message]); //更新日志
        }

        return $this->respond(200, $data);
    }

    public function respond($code, $data, $header = [])
    {
        $rt = microtime(true) - LARAVEL_START;

        $header = array_merge($header, ['rt' => round($rt * 1000, 2) . 'ms', 'qps' => round(1 / $rt, 1)]);

        return Response::json($data, $code, $header);
    }

}
