<?php
namespace app\server;

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

class Meituan {

    private $cookie = '';
    private $gate = 'https://lvyou.meituan.com';
    public $totalPage = 10;

    public function __construct()
    {
        $this->cookie = $this->_cookie();
    }

    public function login() {
        
    }

    public function voucher($check_sn) {

        //https://lvyou.meituan.com/nib/trade/b/voucher/show?voucherCode=130949862550187&yodaReady=h5&csecplatform=4&csecversion=2.4.0

        //https://lvyou.meituan.com/nib/trade/b/voucher/show?voucherCode=130949862550187&yodaReady=h5&csecplatform=4&csecversion=2.4.0
        $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 = null, $end = null, $orderId = '') {

        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 = [
            'page' => $page,
            'count' => 20,
            'orderId' => $orderId,
            'productId' => '',
            'orderTimeTo' => $end ?? '',
            'travelTimeTo' => '',
            'orderTimeFrom' => $start ?? '',
            'travelTimeFrom' => '',
            'yodaReady' => '',
            'h5' => '',
            'csecplatform' => 4,
            'csecversion' => '2.4.0',
        ];

        $list = $this->_curl('/nib/trade/b/order/search/list', $params);

        if(empty($list) || $list->code != 0) {
            $list = $this->_curl('/nib/trade/b/order/search/list', $params);

            if(empty($list) || $list->code != 0) {
                throw new \Exception("美团拉单失败,Err:".json_encode($list));
            }
        }

        if($list && $list->code == 0) {
            $this->totalPage = $list->data->totalPage;
        }

        $_list = [];
        if($list && $list->code == 0 && $list->data && is_array($list->data->orderList)) {
            foreach($list->data->orderList as  $order) {
                echo "美团 订单号：{$order->orderId} \n\n";

                if(in_array($order->orderId, ['',''])) {
                    echo "异常订单:". $order->orderId;
                    sleep(100);
                }
                $item = new Orders();
                $item->os = 1;
                $item->sn = $order->orderId;
                $item->product_id = $order->productId;
                $item->product_name = $order->productName;
                $item->category_id = $order->categoryId;
                $item->create_at = $order->createTime;
                $item->travel_date = $order->travelDate;
                $item->mobile = $order->mobile;
                $item->unit_price = $order->unitPrice;
                $item->total_price = $order->totalPrice;
                $item->actual_price = $order->actualPrice;
                $item->quantity = $order->quantity;
                $item->order_status = $order->orderStatus;
                $item->refund_status = $order->refundStatus;
                $item->category_desc = $order->categoryDesc;
                $item->asset_price = $order->orderStatus == 4 ? $order->totalPrice: 0; //已核销订单,核销金额为订单金额

                $_list[] = $item;
            }
        }
        
        return $_list; //返回半成品
    }

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

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

        $http = $this->gate.$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: lvyou.meituan.com',
            'Sec-Ch-Ua: "Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
            'Accept-Language: zh-CN,zh;q=0.9'
        ];

        curl_setopt($ch, CURLOPT_COOKIE, $this->_cookie());
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        if($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }

        echo $body = curl_exec($ch);
        curl_close($ch);
        return json_decode($body);
    }
}