<?php
namespace App\Http\Controllers\Api\OtherSystemInterfaces;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Crypt;
use App\Http\Models\Api\Common;

// 速电对接 -- 门店绑定
class OtherSystemShopController extends Controller
{
    // 门店绑定关系
    public function correlation(Request $request)
    {
        if (empty($request['ser_id']) || empty($request['shop_id'])) {
            return response()->json(['code'=>202, 'msg'=>'参数错误']);
        }
        $url = config('apisystem.sd_server_name').'/index.php/get_user';
        $post_data['time'] = date('Y-m-d H:i:s');
        $post_data['token'] = md5(md5($post_data['time'].config('apisystem.sd_token')));
        $post_data['ser_id'] = $request['ser_id'];
        $res = $this->doPost($url, $post_data);
        $res = json_decode($res, true);
        if ($res['code'] == 200) {
            $find_system_shop_id = DB::table('shop_correlation')
                ->where('shco_system_shop_id', $request['ser_id'])
                ->value('shco_system_shop_id');
            if ($find_system_shop_id) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'当前账号id已绑定']);
            }
            $shco_data['shco_shop_id'] = $request['shop_id'];//门店id
            $shco_data['shco_system_cid'] = 1;//第三方系统所属企业/品牌方id
            $shco_data['shco_system_shop_id'] = $request['ser_id'];//第三方系统的门店id
            $shco_data['shco_update_time'] = date('Y-m-d H:i:s');//第三方系统的门店id
            $shco_res = DB::table('shop_correlation')->insert($shco_data);
            if ($shco_res) {
                return response()->json(['code'=>200, 'msg'=>'success', 'data'=>'绑定成功']);
            } else {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'绑定失败']);
            }
        } else {
            return response()->json(['code'=>201, 'msg'=>'匹配失败']);
        }
    }
    
    //验证门店秘钥
    public function secretKey(Request $request)
    {
        // 接收数据流
        $request = file_get_contents("php://input");
        Common::write_log($request, 2, 'OtherSystemShop-secretKey');
        $request = json_decode($request, true);
        if(empty($request['secretKey']) || !in_array($request['type'], [1,2]) || empty($request['ser_id']) || empty($request['time']) || empty($request['token'])){
            return response()->json(['code'=>202, 'msg'=>'参数错误']);
        }
        $token = md5(md5($request['time'].config('apisystem.sd_token')));
        if ($request['token'] != $token) {
            return response()->json(['code'=>203, 'msg'=>'token校验失败']);
        }
        $shop_token = DB::table('shop')
            ->where('shop_token',$request['secretKey'])
            ->first(['shop_token','shop_id','shop_cid','shop_store_name','shop_name']);
        $shop_data['store_name'] = $shop_token->shop_store_name;
        $shop_data['user_name'] = $shop_token->shop_name;
        if($shop_token){
            $shco_id = DB::table('shop_correlation')
                ->orwhere('shco_shop_id',$shop_token->shop_id)
                ->orwhere('shco_system_shop_id',$request['ser_id'])
                ->where('shco_system_cid',1)
                ->value('shco_id');
            if(!empty($shco_id)){
                return response()->json(['code'=>203, 'msg'=>'已经被绑定']);
            }
            if($request['type'] == 1){
                return response()->json(['code'=>200, 'msg'=>'秘钥存在','data'=>$shop_data]);
            }else{
                $data['shco_shop_id'] = $shop_token->shop_id;
                $data['shco_system_shop_id'] = $request['ser_id'];
                $data['shco_system_cid'] = $shop_token->shop_cid;
                $data['shco_state'] = 2;
                $res = DB::table('shop_correlation')->insert($data);
                return response()->json(['code'=>200, 'msg'=>'绑定成功']);
            }
        }else{
            return response()->json(['code'=>203, 'msg'=>'秘钥不存在']);
        }
    }

    // 模拟提交数据函数
    function doPost($url, array $param)
    {
        //$post_data = http_build_query($param, '', '&');
        $post_data = $this->toUrlencode($param);
        $post_data=urldecode(json_encode($post_data));
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            echo 'Errno' . curl_error($curl);//捕抓异常
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据，json格式
    }

    public function toUrlencode($arr)
    {
        $temp = array();
        if (is_array($arr)) {
            foreach ($arr AS $key => $row) {
                $temp[$key] = $row;
                if (is_array($temp[$key])) {
                    $temp[$key] = $this->ToUrlencode($temp[$key]);
                } else {
                    $temp[$key] = urlencode($row);
                }
            }
        } else {
            $temp = $arr;
        }
        return $temp;
    }
}
