<?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 = 6;
    public $os;
    private $tryTimes = 0;

    public function __construct($os = 1)
    {
        $this->os = $os;
        $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' => 50,
            '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));
            }
        }

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

                if(in_array($order->orderId, ['',''])) {
                    Log::info( "异常订单:". $order->orderId);
                    sleep(100);
                }
                // 过滤未付款订单
                if ($order->orderStatus == 1) {
                    continue;
                }
                $item = new Orders();
                $item->os = $this->os;
                $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->is_zhibo = $order->bizOrderChannel == 5 ? 1 : 0; // 是否直播(5-视频号,3-小程序)
                $item->asset_price = $order->orderStatus == 4 ? $order->totalPrice: 0; //已核销订单,核销金额为订单金额
                $item->is_refunded = $item->order_status == 5 ? 1 : 0; // 是否已退款(1-已退款,0-未退款)

                $_list[] = $item;
            }
        }

        return $_list; //返回半成品
    }

    public function _cookie($data = '') {
        $key = sprintf('Meituan:cookie-%s', $this->os);
        if($data) Redis::set($key, $data);
        return Redis::get($key);
    }

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

        // 请求次数统计
        $key   = sprintf("Meituan:ReqiestCount:%s", date('Y-m-d'));
        $requestCount = Redis::incrBy($key, 1);
        if ($requestCount == 1) {
            Redis::expire($key, 604800); // 7天
        }

        $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);
        }

        $body = curl_exec($ch);
        curl_close($ch);
        $res = json_decode($body);
        if (!isset($res->code) || $res->code != 0) {
            Log::info('os:' . $this->os);
            Log::info('http:' . $http);
            Log::info('body:' . $body);

            if ($this->tryTimes > 1) {
                (new ThirdApiService())->weComNotice($this->os);
            }
            $this->tryTimes++;
        }
        return $res;
    }
}