<?php

namespace app\event;

use app\model\saas\SaasCart;
use app\model\saas\SaasOrder;
use app\model\saas\SaasOrderDetail;
use Webman\RedisQueue\Redis;

class CreateOrder
{

    public function createOrder(array $data = [])
    {
        try {
            $cart = (new SaasCart)->where("shop_id",$data['shop'])->where("openid",$data['openid'])->where("print_id",$data['print'])->order("create_at desc")->select();
            if ($cart->isEmpty()) return success('ok',['cart' => []]);
            $order = (new SaasOrder)->where("order_sn",$data['order'])->findOrEmpty();
            $orderDetail = [];
            $print_name = !empty($order['print_name']) ? explode("-",$order['print_name']) : [];
            $printNameOut = $print_name[1] ?? '';
            echo "订单号：{$data['order']}====打印机名：{$printNameOut}====打印机id：{$order['print_id']}\n";
            foreach ($cart->toArray() as $key=>$val)
            {
                unset($val['id']);
                $orderDetail[$key] = $val;
                $orderDetail[$key]['order_sn'] = $data['order'];
                $orderDetail[$key]['print_id'] = $order['print_id']?$order['print_id']:$val['print_id'];
                $orderDetail[$key]['print_name'] = $print_name[1] ?? $val['print_name'];
                $orderDetail[$key]['status'] = 1;
//                if ($val['extension'] == "pdf") {
//                    $orderDetail[$key]['status'] = 1;
//                } else {
//                    $orderDetail[$key]['status'] = 0;
//                }
            }
            $state = (new SaasOrderDetail)->strict(false)->insertAll($orderDetail);
            Redis::send("push-print",['type' => 'order' , 'order' => $data['order']]);
//            events("merge-pdf",$data);
            if (empty($printNameOut)) {
                $order->print_name = $cart[0]['print_name']??'';
                $order->save();
            }
            (new SaasCart)->where("shop_id",$data['shop'])->where("openid",$data['openid'])->delete();
        } catch (\Throwable $throwable) {
            echo "写入订单详情错误\n";
            echo $throwable->getLine()."\n";
            echo $throwable->getFile()."\n";
            echo $throwable->getMessage()."\n";
            return error($throwable->getMessage());
        }
    }

}