<?php
/**
 * Created by PhpStorm.
 * User: phperstar
 * Date: 2020/9/7
 * Time: 11:33 AM
 */

namespace Util\KeRuYun;

use Mall\Framework\Core\ResultWrapper;
use Mall\Framework\Core\ErrorCode;
use Mall\Framework\Factory;

class Open
{

    // 基础域名
    //private $baseUrl = 'https://gldopenapi.keruyun.com';
    private $baseUrl = 'https://openapi.keruyun.com';

    // 客如云门店id
    private $shopIdenty = '';
    // 授权KEY
    private $appKey = '';
    // 授权密钥
    private $secretKey = '';

    // 版本
    private $version = '1.0';

    //公共header头
    private  $commonHeader = [
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json'
        ],
    ];

    public function __construct($shopIdenty='', $appKey = '', $secretKey = '' )
    {
        $this->shopIdenty = $shopIdenty;
        $this->appKey     = $appKey;
        $this->secretKey  = $secretKey;
    }

    /**
     * 公共请求参数
     * 官方文档地址: https://open.keruyun.com/apidoc/cn/common/common-1.html
     */
    public function commonRequestData()
    {
        return $commonRequestData = [
            'appKey' => $this->appKey,
            'shopIdenty' => $this->shopIdenty,
            'version' => $this->version,
            'timestamp' => time(),
            'sign' => ''
        ];
    }

    /**
     * 生成签名方法
     * 官方文档地址: https://open.keruyun.com/apidoc/cn/common/common-3.html
     */
    public function getSign($token)
    {
        $commonRequestData = self::commonRequestData();
        unset($commonRequestData['sign']);

        ksort($commonRequestData, SORT_STRING);
        $parameters = '';
        foreach ($commonRequestData as $key => $value){
            $parameters .= $key.$value;
        }
        return hash('sha256', $parameters.$token);
    }

    /**
     * 生成请求地址
     */
    public function getUrl($apiUrl, $token)
    {
        $commonRequestData = self::commonRequestData();
        $sign = self::getSign($token);
        $commonRequestData['sign'] = $sign;

        $url = '';
        foreach ($commonRequestData as $key => $value){
            $url .= $key.'='.$value;
            if($key != 'sign'){
                $url .= '&';
            }
        }

        return $this->baseUrl.$apiUrl.'?'.$url;
    }

    /**
     * 获取门店token
     * 官方文档地址: https://open.keruyun.com/apidoc/cn/common/common-2.html
     */
    public function getToken()
    {
        $url = self::getUrl('/open/v1/token/get', $this->secretKey);
        $response = request($url, null, 30,  true);
        return self::commonReponseResult($response);
    }


    /**
     * 菜品分页查询
     * 官方文档地址: https://open.keruyun.com/apidoc/cn/dish/dish-3.html
     */
    public function dishMenu($token, $startId = 1, $pageNum = 1000)
    {
        $url = self::getUrl('/open/v1/cater/dish/dishMenu', $token);

        $postData = [
            'shopIdenty' => $this->shopIdenty,
            'startId'    => $startId,
            'pageNum'    => $pageNum
        ];

        $response = request($url, json_encode($postData), 30,  true, $this->commonHeader);
        return self::commonReponseResult($response);
    }

    /**
     * 菜品精确查询
     * 官方文档地址: https://open.keruyun.com/apidoc/cn/dish/dish-4.html
     */
    public function dishMenuByIds($token, $ids)
    {
        $url = self::getUrl('/open/v1/cater/dish/dishMenuByIds', $token);

        $postData = [
            'shopIdenty' => $this->shopIdenty,
            'ids' => $ids,
        ];

        $response = request($url, json_encode($postData), 30,  true, $this->commonHeader);
        return self::commonReponseResult($response);
    }

    /**
     * 创建顾客
     * 官方文档地址: https://open.keruyun.com/apidoc/cn/crm/crm-1.html
     */
    public function createCustomer($token, $customerData)
    {
        $url = self::getUrl('/open/v1/crm/createCustomer', $token);

        $postData = [
            'birthday'   => $customerData['birthday'], // 生日时间戳
            'loginId'    => $customerData['loginId'], // 手机号或者微信id
            'loginType'  => $customerData['loginType'], //登陆类型(0:手机注册客户;1:微信注册用户;2:座机号;101:微信会员卡卡号;)
            'name'       => $customerData['name'],
            'sex'        => $customerData['sex'],
        ];

        $response = request($url, json_encode($postData), 30,  true, $this->commonHeader);
        return self::commonReponseResult($response);
    }

    /**
     * 创建/升级会员
     * 官方文档地址: https://open.keruyun.com/apidoc/cn/crm/crm-2.html
     */
    public function createOrUpgradeMember($token, $customerData)
    {
        $url = self::getUrl('/open/v1/crm/createOrUpgradeMember', $token);

        $postData = [
            'attentionWxTime' => time(), // 关注微信时间
            'birthday'   => time(), // 生日时间戳
            'consumePwd' => '123456',
            'customerId' => 0,
            'customerMainId' => 0,
            'loginId'    => $customerData['loginId'], // 手机号或者微信id
            'loginType'  => $customerData['loginType'], //登陆类型(0:手机注册客户;1:微信注册用户;2:座机号;101:微信会员卡卡号;)
            'name'       => $customerData['name'],
            'sex'        => $customerData['sex'],
        ];

        $response = request($url, json_encode($postData), 30,  true, $this->commonHeader);
        return self::commonReponseResult($response);
    }

    /**
     * 顾客/会员登录
     * 官方文档地址: https://open.keruyun.com/apidoc/cn/crm/login-1.html
     */
    public function login($token, $mobile)
    {
        $url = self::getUrl('/open/v1/crm/login', $token);

        $postData = [
            'loginId'    => $mobile, // 手机号或者微信id
            'loginType'  => 0, //登陆类型(0:手机注册客户;1:微信注册用户;2:座机号;101:微信会员卡卡号;)
        ];

        $response = request($url, json_encode($postData), 30,  true, $this->commonHeader);
        return self::commonReponseResult($response);
    }

    /**
     * 查询会员信息
     * 官方文档地址; https://open.keruyun.com/apidoc/cn/crm/crm-3.html
     */
    public function getCustomerDetailById($token, $customerId)
    {
        $url = self::getUrl('/open/v1/crm/getCustomerDetailById', $token);

        $postData = [
            'customerId' => $customerId,
            'isNeedCredit' => 1
        ];

        $response = request($url, json_encode($postData), 30,  true, $this->commonHeader);
        return self::commonReponseResult($response);
    }

    /**
     * 会员充值
     * 官方文档地址：https://open.keruyun.com/apidoc/cn/crm/charge-2.html
     */
    public function recharge($token, $customerRechargeData)
    {
        $url = self::getUrl('/open/v1/crm/member/recharge', $token);

        $postData = [
            'customerId' => $customerRechargeData['customerId'],
            'cardType' => 2,
            'businessType' => 1,
            'amount' => $customerRechargeData['amount'],
            'tpOrderId' => $customerRechargeData['tpOrderId'],
        ];

        $response = request($url, json_encode($postData, JSON_UNESCAPED_UNICODE), 30,  true, $this->commonHeader); V($response);
        return self::commonReponseResult($response);
    }

    /**
     * 外卖下单
     * 官网文档地址：https://open.keruyun.com/apidoc/cn/takeout/takeout-1.html
     */
    public function createTakeoutOrder($token, $orderData)
    {
        $url = self::getUrl('/open/v1/takeout/order/create', $token);

        $postData = [
            'tpOrderId'   => $orderData['tpOrderId'],   // 第三方订单号
            'createTime'  => $orderData['createTime'],  // 订单创建时间
            'peopleCount' => 1,                         // 就餐人数
            'shop' =>[
                'shopIdenty' => $this->shopIdenty,      // 客如云门店ID
                'tpShopId'   => $orderData['tpShopId'], // 合作方商户id
                'shopName'   => $orderData['shopName']  // 商户名称
            ],
            'products' => $orderData['products'],  // 商品信息
            'delivery' => $orderData['delivery'],  // 配送信息
            'payment'  => $orderData['payment'],   // 支付信息
            'customers' => $orderData['customers'],   // 客户信息
            'remark' => $orderData['remark'],
        ];

        $response = request($url, json_encode($postData, JSON_UNESCAPED_UNICODE), 30,  true, $this->commonHeader);
        return self::commonReponseResult($response);
    }


    /**
     * 堂食快餐下单
     * 官网地址:
     */
    public function createSnackOrder($token, $orderData)
    {
        $postData = [
            'tpOrderId'   => $orderData['tpOrderId'],
            'createTime'  => $orderData['createTime'],
            'updateTime'  => $orderData['updateTime'],
            'payment' => $orderData['payment'],
            'peopleCount' => 1, // 就餐人数
            'print'       => 1, // 打印
            'remark'      => '小程序订单', // 备注
            'status'      => 2, // 已经确认
            'shopIdenty' => $this->shopIdenty,
            'shopName'   => $orderData['shopName'],
            'products' => $orderData['products'],
            'customers'   => [$orderData['customers']],
            'totalPrice' => $orderData['totalPrice'],
        ];

        $url = self::getUrl('/open/v1/snack/order/create', $token);
        $response = request($url, json_encode($postData), 30,  true, $this->commonHeader); V($response);
        return self::commonReponseResult($response);
    }

    /**
     * 取消订单
     * 官网文档地址 https://open.keruyun.com/apidoc/cn/takeout/takeout-6.html
     */
    public function cancel($token, $orderId)
    {
        $url = self::getUrl('/open/v1/takeout/order/cancel', $token);

        $postData = [
            'orderId' => $orderId,  // 创建订单时系统返回给开发者的开放平台订单id
            'reason'  => '不想买了'
        ];

        $response = request($url, json_encode($postData, JSON_UNESCAPED_UNICODE), 30,  true, $this->commonHeader); V($response);
        return self::commonReponseResult($response);
    }

    /**
     * 堂食快餐订单查询
     * 官网地址: https://open.keruyun.com/apidoc/cn/zhengcan/zhengcan-19.html
     */
    public function dinnerOrderDetail($token, $orderId)
    {
        $url = self::getUrl('/open/v1/dinner/order/detail', $token);

        $postData = [
            'id' => $orderId,
        ];

        $response = request($url, json_encode($postData, JSON_UNESCAPED_UNICODE), 30,  true, $this->commonHeader);
        return self::commonReponseResult($response);
    }

    /**
     * 订单详情
     * 官方文档地址
     */
    public function orderExportDetail($token, $orderIds = [])
    {
        $url = self::getUrl('/open/v1/data/order/exportDetail', $token);

        $postData = [
            'shopIdenty' => $this->shopIdenty,
            'ids' => $orderIds,
        ];

        $response = request($url, json_encode($postData, JSON_UNESCAPED_UNICODE), 30,  true, $this->commonHeader); V($response);
        return self::commonReponseResult($response);
    }




    /**
     * 公共的请去响应处理函数
     */
    public function commonReponseResult($response)
    {
        if ($response['httpcode'] != 200) {
            return ResultWrapper::fail('请求外部系统接口报错', ErrorCode::$apiNotResult);
        }
        $responseData = json_decode($response['content'], true);
        if($responseData['code'] != 0){
            return ResultWrapper::fail($responseData['message'], $responseData['code']);
        }

        return ResultWrapper::success(isset($responseData['result'])?$responseData['result']:$responseData['message']);
    }

}