<?php
namespace app\server;

use app\model\Orders;
use support\Log;
use support\Redis;

class Kuaishou {

    private $gate = 'https://lbs.kuaishou.com/rest/tp/seller/order/b/searchList';

    private $phone = 'https://lbs.kuaishou.com/rest/tp/seller/order/decrypt';


    public $totalPage = 0;

    public function __construct()
    {
    }
    
    public function _cookie($data = '') {
        if($data) Redis::set('Kuaishou:cookie', $data);
        return Redis::get('Kuaishou:cookie');
    }

    public function _id($id = '') {
        if($id) Redis::set('Kuaishou:id', $id);
        return Redis::get('Kuaishou:id');
    }

    public function voucher($check_sn) {

        $res = $this->_curl('/nib/trade/b/voucher/show',[
            'voucherCode' => $check_sn,
            'yodaReady' => 'h5',
            'csecplatform' => '4',
            'csecversion' => '2.4.0'
        ]);

        return $res;
    }
    /**
     * 快手是按每天
     */
    public function get($page, $start = '', $end = '', $orderId = null) {

        if(empty($start) || empty($end)) {
            $start = date('Y-m-d 00:00:00');
            $end = date('Y-m-d 23:59:59');
        }

        $start = strtotime($start) * 1000;
        $end = strtotime($end) * 1000 +999;

        if($orderId) {
            $start = $end = null;
        }

        $params = [
            'startTime' => $start,
            'endTime' => $end,
            'channelType' => null,
            'orderId' => $orderId,
            'phoneNum' => null,
            'orderStatus' => 0,  //订单状态
            'assetStatus' => 0,  //核销状态
            'refundStatus' => 0, //退款状态
            'itemId' => null,
            'itemName' => null,
            'itemType' => 0,
            'distributorId' => null,
            'buyerId' => null,
            'shopId' => '210000460100115195',
            'visitorId' => $this->_id(),
            'page' => [
                'currentPage' => $page,
                'pageSize' => 10,
                'noMore' => false
            ]
        ];

        $list = $this->_curl($this->gate, $params,'POST');

        if(empty($list) || $list->success != true) {
            $list = $this->_curl($this->gate, $params,'POST');

            if(empty($list) || $list->success != true) {
                throw new \Exception("快手拉单失败,Err:".json_encode($list));
            }
        }

        if(!empty($list) && $list->success == true) {
            $this->totalPage = ceil($list->data->page->totalCount / $list->data->page->pageSize);
        }

        $_list = [];
        if(is_array($list->data->sellerOrderResultDOS) && count($list->data->sellerOrderResultDOS)) {
            echo  "Order start\n\n";
            foreach($list->data->sellerOrderResultDOS as $order) {
                echo "快手订单号:".$order->orderId."\n";
                $item = new Orders();
                $item->os = 2;
                $item->sn = "$order->orderId";
                $item->product_id = "$order->itemId";
                $item->product_name = $order->itemName;
                $item->category_id = $order->itemType;
                $item->create_at = $order->createTime;
                $item->cname = $order->userInfo->userNick;
                $item->unit_price = $order->skuSinglePrice;
                $item->total_price = $order->totalAmount;
                $item->actual_price = $order->payAmount;
                $item->quantity = $order->skuQuantity;
                $item->order_status = $order->orderStatus;
                $item->refund_status = $order->refundStatus;
                $item->asset_status = $order->assetStatus;
                $item->category_desc = $order->itemTypeDesc;
                $item->asset_price = $order->consumeQuantity * $order->skuSinglePrice;

                $old = Orders::where('sn', "$order->orderId")->where('os', 2)->find();
                if(empty($old) || empty($old->mobile)) {
                    $mobile = $this->_mobile($order->orderId, $order->phoneNumEncrypted);
                    if(!empty($mobile->data)) {
                        $item->mobile = $mobile->data;
                    }
                }

                $_list[] = $item;
            }
        }

        return $_list;
    }

    public function _mobile($orderId, $enc) {

        $params = [
            'encryptedInfo' => $enc,
            'orderId' => $orderId,
            'decryptType' => 'PHONE'
        ];

        return $this->_curl($this->phone, $params,'POST');
    }

    public function _curl($url, $params, $method = 'POST') {

        $http = $url;
        if($method == 'GET') {
            $http = $http.'?'. http_build_query($params);
        }

        $ch = curl_init($http);
        
        $header = [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
            'Sec-Ch-Ua-Platform: "Windows"',
            'Host: lbs.kuaishou.com',
            'Origin: https://lbs.kuaishou.com',
            'Sec-Ch-Ua: "Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
            'Accept-Language: zh-CN,zh;q=0.9',
            'Content-Type: application/json;charset=UTF-8'
        ];
        curl_setopt($ch, CURLOPT_COOKIE, $this->_cookie());
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        if($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
        }

        $body = curl_exec($ch);
        $json =  json_decode($body);
        if(!empty($json->result) && $json->result == 109) throw new \Exception("快手登录超时");
        if(!empty($json->result) && $json->result != 200) throw new \Exception("快手请求失败了");
        return $json;
    }

}